如何在Java中使用servlet过滤器来更改传入的servlet请求URL?
2022-08-31 06:18:47
如何使用 servlet 过滤器从
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
<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!