Spring MVC Interceptor error not detected by Tomcat error handler

In my Spring MVC application (servlet 3.0), I defined my own error handler in web.xml:

<error-page>
    <location>/error</location>
</error-page>

which maps to the controller:

@Controller
class CustomErrorController {

 @RequestMapping("error")
 public String customError(HttpServletRequest request, HttpServletResponse response, Model model) {
...
 }
}

This works fine for most errors, such as 404 errors. However, I also defined an Interceptor that returns a 403 response if there is no authenticated user:

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    HttpSession httpSession = request.getSession();
    ((HttpServletResponse) response).setStatus(HttpURLConnection.HTTP_FORBIDDEN);
    return false;
}

The 403 response is not captured by the custom error handler — the browser does not receive a response with the 403 error code.

I guess this is because I am doing something wrong in the Interceptor - How do I change the code in the Interceptor to work with a normal error?

+3
source share
1 answer

Change response.setStatustoresponse.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

[setStatus] , . , , -, sendError (int, java.lang.String).

+9

All Articles