문제

In my Spring MVC app (servlet 3.0), I have defined a custom error handler in web.xml:

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

which maps to a 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 have also defined an Interceptor which 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 being caught by the custom error handler - the browser just gets no response with an error code of 403.

I presume this is because I am doing something incorrectly in the Interceptor - How should I change the code in the Interceptor so that normal error handling works?

도움이 되었습니까?

해결책

Change response.setStatus to response.sendError

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    response.sendError(HttpServletResponse.SC_FORBIDDEN);
    return false;
}

This actually issues an error (rather than just stating it) - and forces Tomcat to use the error location as defined in the web.xml

As stated in the 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top