且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Java中使用servlet过滤器来更改传入的servlet请求URL?

更新时间:2022-04-09 23:37:46


  1. 实施 javax.servlet.Filter

  2. doFilter() 方法,强制传入 ServletRequest HttpServletRequest

  3. 使用 HttpServletRequest#getRequestURI() 获取路径。

  4. 使用s traightforward java.lang.String 类似 substring() split() concat() 等提取感兴趣的部分并撰写新路径。

  5. 使用 ServletRequest#getRequestDispatcher() 然后 RequestDispatcher#forward() 将请求/响应转发到新URL(服务器端)重定向,未反映在浏览器地址栏中),投射传入 ServletResponse HttpServletResponse 然后 HttpServletResponse #sendRedirect() 将响应重定向到新URL(客户端重定向,反映在浏览器地址栏中)。

  6. web.xml中注册过滤器 url-pattern / * / Check_License / * ,取决于上下文路径,或者i如果您已经使用Servlet 3.0,请使用 @WebFilter 注释。

  1. Implement javax.servlet.Filter.
  2. In doFilter() method, cast the incoming ServletRequest to HttpServletRequest.
  3. Use HttpServletRequest#getRequestURI() to grab the path.
  4. Use straightforward java.lang.String methods like substring(), split(), concat() and so on to extract the part of interest and compose the new path.
  5. Use either ServletRequest#getRequestDispatcher() and then RequestDispatcher#forward() to forward the request/response to the new URL (server-side redirect, not reflected in browser address bar), or cast the incoming ServletResponse to HttpServletResponse and then HttpServletResponse#sendRedirect() to redirect the response to the new URL (client side redirect, reflected in browser address bar).
  6. Register the filter in web.xml on an url-pattern of /* or /Check_License/*, depending on the context path, or if you're on Servlet 3.0 already, use the @WebFilter annotation for that instead.

别忘了如果要更改URL 需要并且,请在代码中添加一个检查,然后只需调用 FilterChain #doFilter() ,否则它会自动调用自己。

Don't forget to add a check in the code if the URL needs to be changed and if not, then just call FilterChain#doFilter(), else it will call itself in an infinite loop.

或者您也可以使用现有的第三方API完成所有工作对你而言,例如 Tuckey的UrlRewriteFilter ,它的配置方式与Apache的 mod_rewrite

Alternatively you can also just use an existing 3rd party API to do all the work for you, such as Tuckey's UrlRewriteFilter which can be configured the way as you would do with Apache's mod_rewrite.