在过滤器中重定向时停止进一步处理
Posted
技术标签:
【中文标题】在过滤器中重定向时停止进一步处理【英文标题】:Stop further processing when redirecting in a filter 【发布时间】:2012-01-16 18:28:33 【问题描述】:我有 URLRewirteFilter,它检查请求的域是否以 www 开头。并重定向到无 www url。当请求被重定向时,如何停止进一步处理(调用 JSF 应用程序、调用 servlet 等)? 到目前为止,我有这个:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
HttpServletRequest req = (HttpServletRequest) request;
String sn = req.getServerName().toLowerCase();
if (sn.startsWith("www."))
String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
HttpServletResponse resp = (HttpServletResponse) response;
resp.reset();
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
resp.setHeader("Location", url);
chain.doFilter(request, response);
【问题讨论】:
【参考方案1】:只需将return
语句添加到if
的末尾
if (sn.startsWith("www."))
String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
HttpServletResponse resp = (HttpServletResponse) response;
resp.reset();
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
resp.setHeader("Location", url);
return;
chain.doFilter(request, response);
或添加else
if (sn.startsWith("www."))
String url = "http://" + getDefaultDomain() + req.getContextPath() + req.getRequestURI();
HttpServletResponse resp = (HttpServletResponse) response;
resp.reset();
resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
resp.setHeader("Location", url);
else
chain.doFilter(request, response);
另见:
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed【讨论】:
基本不要打电话chain.doFilter
以上是关于在过滤器中重定向时停止进一步处理的主要内容,如果未能解决你的问题,请参考以下文章