How to return HTTP error code from servlet filter?

servlet filter return response
servlet filter response example
chain dofilter example
servlet filter abort request
httpservletresponsewrapper
java skip filter chain
spring boot response filter
filter vs servlet

I have pages in my web application which are accessible only by the administrator. I wrote filter, but I don't understand how to return HTTP error code(403) from the filter if user isn't the admin.

public class AdminFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String username = servletRequest.getParameter("username");
        String password = servletRequest.getParameter("password");

        UserDao userDaoImpl = new UserDaoImpl();
        if(userDaoImpl.findByUsername(username).getPassword().equals(password)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            //respond with 403
        }
    }
}

I understand that I can redirect to my custom 403 page but I'm wondering how to return HTTP error code.

You need to cast servletResponse to HttpServletResponse first:

HttpServletResponse response = (HttpServletResponse) servletResponse;

Then use its sendError() method:

response.sendError(HttpServletResponse.SC_FORBIDDEN);

SC_FORBIDDEN stands for code 403.

By the way, you don't redirect to 403 page, you just respond with that status. If you do that, the servlet container will serve a special 403 page to the user. You can configure that page in your web.xml:

<error-page>
    <error-code>403</error-code>
    <location>/error-403.htm</location>
</error-page>

This instructs the container to serve your custom page /error-403.htm when you set 403 status.

If you want a redirect, you could use response.sendRedirect() (it issues a 302 redirect).

Setting response code in Servlet Filter, My mistake was doing response.setStatus(403) what needed to happen was response.sendError(403); return;. Browse other questions tagged java servlets servlet-filters http-status-codes or ask your own question. The Overflow Blog Podcast 234: We’re doing it live!

I have solved in this way:

((HttpServletResponse) response).setStatus(HttpServletResponse.SC_BAD_REQUEST);
(HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST, "HMAC Failed - X-Authenticated-Id not available");
return;

How to modify HTTP response using Java Filter, Java filter example to modify, change, alter response of webpages. the response are sent to the client, without touching any existing code of the web So the servlet container will write the response of the target page to this  Try to implement a standard servlet filter. By the way. 404 comes from the server not from your application. Also 500. You can return these codes by yourself, in that case, the filter should work. Also, another solution would be to set the headers before any request. But this won't save you from the 404 problem. How to set servlet filters

Resolved it by setting 401 as error code in the backend and catching the error in angular interceptor as below.

Backend Java code:

(HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);

Angular code:

intercept(req: HttpRequest, next: HttpHandler): Observable> {

    return next.handle(req)
        .catch(error => {

            if (error instanceof HttpErrorResponse && error.status == 401) {
                this.router.navigateByUrl('/sessionExpired', { replaceUrl: true });

                return new EmptyObservable();
            }
            return _throw(error);
        });
}

Java – Break Filter Chain and Return Custom POJO Response from , Using a Java Servlet Filter to intercept the response HTTP status code with NetBeans IDE 7 and Maven. by. Chad Lung. ·. Oct. 23, 11 · Java Zone · Not set. 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.

Using a Java Servlet Filter to intercept the response HTTP status , As well as sending the Servlet output to a given request, it is sometimes necessary to set a status code. An HTTP status code— sometimes called a response  The status line consists of the HTTP version (HTTP/1.1 in the example), a status code (200 in the example), and a very short message corresponding to the status code (OK in the example). Following is a list of HTTP status codes and associated messages that might be returned from the Web Server −

Setting the HTTP status (response) code from a Java Servlet, Modular code is more manageable and documentable, is easier to debug, and Second, filters can be used to transform the response from a servlet or a JSP page. Examines response headers after it has invoked the next filter in the chain  @Component public class AuthFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Cast the servlet request and response to HttpServletRequest and HttpServletResponse HttpServletResponse httpServletResponse = (HttpServletResponse

The Essentials of Filters, You can filter HTTP requests to reject or modify them before they are delivered is changed in the * request URI if it matches one of a number of known aliases. void doFilter(ServletRequest request, ServletResponse response, FilterChain  The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only one method: public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control to the next filter or resource.

Comments
  • I don't get the "don't redirect" part. What if I want custom 403 page with funny design? I need to respond with the status and have something that will respond to this status with the page?
  • I've updated the answer to clearify the situation with a 403 page with a funny design