如何使用 servlet 过滤器更改传入的 servlet 请求 url
http://nm-java.appspot.com/Check_License/Dir_My_App/Dir_ABC/My_Obj_123
至
http://nm-java.appspot.com/Check_License?Contact_Id=My_Obj_123
?
更新 :根据以下 BalusC 的步骤,我想出了以下代码:
public class UrlRewriteFilter implements Filter { @Override public void init(FilterConfig config) throws ServletException { // } @Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws ServletException, IOException { HttpServletRequest request = (HttpServletRequest) req; String requestURI = request.getRequestURI(); if (requestURI.startsWith("/Check_License/Dir_My_App/")) { String toReplace = requestURI.substring(requestURI.indexOf("/Dir_My_App"), requestURI.lastIndexOf("/") + 1); String newURI = requestURI.replace(toReplace, "?Contact_Id="); req.getRequestDispatcher(newURI).forward(req, res); } else { chain.doFilter(req, res); } } @Override public void destroy() { // } }
中的相关条目web.xml如下所示:
web.xml
<filter> <filter-name>urlRewriteFilter</filter-name> <filter-class>com.example.UrlRewriteFilter</filter-class> </filter> <filter-mapping> <filter-name>urlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
我尝试了服务器端和客户端重定向并获得了预期的结果。成功了,谢谢 BalusC!
javax.servlet.Filter
doFilter()
ServletRequest
HttpServletRequest
HttpServletRequest#getRequestURI()
java.lang.String
substring()
split()
concat()
ServletRequest#getRequestDispatcher()
RequestDispatcher#forward()
ServletResponse
HttpServletResponse
HttpServletResponse#sendRedirect()
url-pattern
/*
/Check_License/*
@WebFilter
如果需要 更改URL,请不要忘记在代码中添加检查,如果 不需要 ,则只需调用FilterChain#doFilter(),否则它将在无限循环中调用自身。
FilterChain#doFilter()
或者,您也可以只使用现有的 3rd 方 API 为您完成所有工作,例如Tuckey 的 UrlRewriteFilter可以像使用 Apache 的mod_rewrite.
mod_rewrite