在我的web.xml中,我完成了以下error-page映射,但是当它们被调用时,这些被调用的请求不会通过web.xml文件中指定的过滤器定义传递。
<error-page>
<error-code>403</error-code>
<location>/error.vm?id=403</location>
</error-page>
<error-page>
<error-code>400</error-code>
<location>/error.vm?id=400</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error.vm?id=404</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/servlet-exception.vm</location>
</error-page>我的应用程序正在使用spring-mvc,并且我希望处理spring mvc中的handler not found条件。我的应用程序是一个多租户应用程序,其中一些过滤器负责设置一些与模式相关的信息。
请求正在到达我的error.vm控制器,但是由于它们正在通过过滤器,所以我无法确定theme和SecurityContext等。
如何解决这个问题?
谢谢。
发布于 2012-02-08 16:14:56
您可以使用servlet过滤器,而不是使用web.xml的错误页面。servlet筛选器可用于捕获所有异常,或仅捕获特定异常,如org.springframework.web.portlet.NoHandlerFoundException.(这就是你所说的“处理程序找不到”异常吗?)
滤镜看起来像这样:
package com.example;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.springframework.web.portlet.NoHandlerFoundException;
public class ErrorHandlingFilter implements Filter {
public void init(FilterConfig config) throws ServletException { }
public void destroy() { }
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
try {
chain.doFilter(request, response);
} catch (NoHandlerFoundException e) {
// Or you could catch Exception, Error, Throwable...
// You probably want to add exception logging code here.
// Putting the exception into request scope so it can be used by the error handling page
request.setAttribute("exception", e);
// You probably want to add exception logging code here.
request.getRequestDispatcher("/WEB-INF/view/servlet-exception.vm").forward(request, response);
}
}
}然后,在Spring的DelegatingFilterProxy的帮助下在web.xml中进行设置:
<filter>
<filter-name>errorHandlingFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>errorHandlingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>最后,将过滤器转换为spring上下文xml中的spring bean:
<bean id="errorHandlingFilter" class="com.example.ErrorHandlingFilter" />您可能需要尝试筛选器链中筛选器的顺序,以便失败的请求仍然通过您提到的其他筛选器。如果你在这方面遇到了问题,一种变化是使用HTTP重定向而不是转发,如下所示:
try {
chain.doFilter(request, response);
} catch (NoHandlerFoundException e) {
request.getSession().setAttribute("exception", e);
response.sendRedirect("/servlet-exception.vm");
}这将迫使浏览器将您的错误处理页面作为新的http请求请求,这可能会更容易确保它首先通过所有正确的过滤器。如果您需要原始异常对象,则可以将其放入会话中,而不是放入请求中。
发布于 2013-08-31 16:21:43
也许吧
<filter-mapping>
<filter-name>SomeFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>https://stackoverflow.com/questions/9123403
复制相似问题