how to modify http response using java filter
Java filters can be used to modify the response sent back to the client. To modify the response, you can implement a filter that wraps the response object and intercepts calls to the response writer.
Here is an example of a filter that adds a header to the HTTP response:
import java.io.IOException; import javax.servlet.*; import javax.servlet.http.HttpServletResponse; public class AddHeaderFilter implements Filter { private String headerName; private String headerValue; public void init(FilterConfig config) throws ServletException { headerName = config.getInitParameter("headerName"); headerValue = config.getInitParameter("headerValue"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletResponse httpServletResponse = (HttpServletResponse) response; httpServletResponse.addHeader(headerName, headerValue); chain.doFilter(request, response); } public void destroy() { } }Source:wwitfigi.wdea.com
In this example, the init
method reads the filter configuration parameters and sets the header name and value. The doFilter
method wraps the response object and adds the header to it. Then, it calls the chain.doFilter
method to allow the request to proceed to its destination. Finally, the destroy
method is empty.
To use this filter, you need to declare it in the web.xml
file and map it to a URL pattern. Here is an example:
<filter> <filter-name>AddHeaderFilter</filter-name> <filter-class>com.example.AddHeaderFilter</filter-class> <init-param> <param-name>headerName</param-name> <param-value>X-MyHeader</param-value> </init-param> <init-param> <param-name>headerValue</param-name> <param-value>MyValue</param-value> </init-param> </filter> <filter-mapping> <filter-name>AddHeaderFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
In this example, the filter is declared with the name AddHeaderFilter
and the class com.example.AddHeaderFilter
. The init-param
tags set the header name and value. The filter-mapping
tags map the filter to all URL patterns.
When a client accesses a page, the filter intercepts the response and adds the header to it before it is sent back to the client.