在服务器启动时,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"); }