Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting response code in Servlet Filter

I have a class which implements javax.servlet.Filter which does some authentication on a token object set in the session, if the token becomes invalid I wish to return a 403 forbidden response. So I have something like

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throw ServletException {
    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    ...
    ...
    // Something has gone wrong with auth set the response code and
    // continue with the chain
    response.setStatus(403);
    chain.doFilter(request, response);
}

What I want then to happen is for the <error-page> defined in the web.xml to trigger against the 403 response code

<error-page>
    <error-code>403</error-code>
    <location>/forbidden.xhtml</location>
</error-page>

I can see that the network tab of the browser dev tools correctly shows a 403 type response. But the browser doesn't redirect to the error page like I'm expecting, what am I doing wrong here?

like image 642
PDStat Avatar asked Dec 18 '22 11:12

PDStat


1 Answers

My mistake was doing response.setStatus(403) what needed to happen was

response.sendError(403);
return;
like image 84
PDStat Avatar answered Dec 20 '22 23:12

PDStat