在我的 Spring MVC 应用程序 (servlet 3.0) 中,我在 web.xml 中定义了一个自定义错误处理程序:
<error-page>
<location>/error</location>
</error-page>
映射到 Controller :
@Controller
class CustomErrorController {
@RequestMapping("error")
public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
...
}
}
这适用于大多数错误,例如 404 错误。 但是,我还定义了一个拦截器,如果没有经过身份验证的用户,它会返回 403 响应:
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
HttpSession httpSession = request.getSession();
((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_FORBIDDEN);
return false;
}
403 响应没有被自定义错误处理程序捕获 - 浏览器只是没有收到错误代码为 403 的响应。
我想这是因为我在拦截器中做错了什么 - 我应该如何更改拦截器中的代码,以便进行正常的错误处理?
最佳答案
将response.setStatus
更改为response.sendError
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.sendError(HttpServletResponse.SC_FORBIDDEN);
return false;
}
这实际上会发出一个错误(而不仅仅是陈述错误)- 并强制 Tomcat 使用 web.xml
如 HttpServletResponse#setStatus(int) javadoc 中所述
If this method [setStatus] is used to set an error code, then the container's error page mechanism will not be triggered. If there is an error and the caller wishes to invoke an error page defined in the web application, then sendError(int, java.lang.String) must be used instead.
关于java - Tomcat 自定义错误处理程序未捕获 Spring MVC 拦截器错误响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21666392/