Servlet response filter for non-2xx HTTP code

I want to add some headers to the http response from my server. I need the headers to be added regardless of the code (2xx, 4xx, 5xx) that the application returns. I tried to implement javax.servlet.Filter

with annotation @WebFilter

and javax.ws.rs.container.ContainerResponseFilter

with annotation @Provider

, but the methods doFilter

and filter

are only called when the app returns 200 http status code. Can filters be used for non-2xx responses?

I am using Wildfly 8.2.0 as my application server but I think it doesn't matter

EDIT

I think I should give more information about my problem. My application is a REST service implemented by Resteasy. I also configured a security policy for authorization using the Wildlfy security subsystem. I need the REST service response to always contain CORS headers for every request from the frontend, even the client failed the authorization check. But when the response code is 401, the filtering methods are not called even if I use DispatcherType.ERROR

as @Steve C suggested . This way I am not returning status codes, all codes are returned by the server (as @ACV says ). Perhaps this is the reason that the filters are not working for my case.

EDIT II

I found a partial answer in this question . It is possible to add headers to all responses without errors (not 5xx) by configuring the subsystem in Wildfly standalone.xml

+3


source to share


3 answers


You need to include DispatcherType in your @WebFilter declaration:



@WebFilter(urlPatterns={...}, dispatcherTypes={ERROR, REQUEST, ...})
public class ...

      

+3


source


Try to implement a standard servlet filter. By the way. 404 comes from server not from your application. Also 500. You can return these codes yourself, in this case the filter should work. Also, another solution would be to set headers before any request. But that won't save you 404 problems. How to install servlet filters



0


source


I think you should try to catch errors through the error page declaration in your web.xml:

<!--
The error-page element contains a mapping between an error code
or exception type to the path of a resource in the web application
-->
<error-page>

    <!--
    The error-code contains an HTTP error code, ex: 404
    -->
    <error-code></error-code>

    <!--
    The location element contains the location of the resource in the web
    application relative to the root of the web application. The value of
    the location must have a leading `/'.
    -->
    <location>/my.jsp</location>
</error-page>

      

... and then my.jsp code to handle the response in case of error (I've always done exception handling with JSP, I don't know if the Servlet URI will work).

The only drawback is that you will need to explicitly specify node for every HTTP error you want to handle.

See http://docs.oracle.com/cd/E14571_01/web.1111/e13712/web_xml.htm#WBAPP537

0


source







All Articles