run in this way,   no why,   only for you heart
CSDN博客(点击进入) CSDN
51CTO(点击进入) 51CTO

在过滤器中设置一个应用范围内的路径

在服务器启动时,filter过滤器便开始工作,这时可以在过滤器中设置一个通用的路径,存放在Application范围中,当我们在JSP超链接重定向使用路径时便可以,直接调用这个路径,是一种软实现,省去很多麻烦


过滤器中实现

public class MyFlilter implements Filter {
    ServletContext sc;

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        sc = request.getServletContext();
        if (sc.getAttribute("basePath") == null) {
            sc.setAttribute("basePath", request.getScheme() + "://" + request.getServerPort()
                    + ((HttpServletRequest) request).getContextPath());
        }
        chain.doFilter(request, response);
    }

    public void destroy() {
    }
}

在servlet中调用该地址

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path=(String)this.getServletContext().getAttribute("basePath");
    }
posted @ 2017-09-26 22:07  _小龙人  阅读(111)  评论(0编辑  收藏  举报