This answer is present in RedHat Knowledgebase. As it requires RedHat credentials, I'm posting the same answer here.
Solution:
A servlet filter can be used to add the additional HTTP header to the response. Below is an example filter which uses Servlet 3.0 @WebFilter
. Using annotation does not require to configure web.xml
to enable the filter.
/*
* This is a sample servlet filter to set "X-Frame-Options" http header to
* http response.
*/
package com.redhat.jboss.support;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebFilter;
@WebFilter("/*")
public class AddCustomHeaderFilter implements Filter {
/**
* Take this filter out of service.
*/
public void destroy() {
}
/**
* @param request The servlet request we are processing
* @param result The servlet response we are creating
* @param chain The filter chain we are processing
*
* @exception IOException if an input/output error occurs
* @exception ServletException if a servlet error occurs
*/
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
((HttpServletResponse)response).setHeader("X-Frame-Options", "SAMEORIGIN");
chain.doFilter(request, response);
}
/**
* Place this filter into service.
*
* @param filterConfig The filter configuration object
*/
public void init(FilterConfig filterConfig) throws ServletException {
}
}
- After compiling the
AddCustomHeaderFilter.java
, one package will be
creating named com.redhat.jboss.support
with AddCustomHeaderFilter.class
.
Create a jar for the AddCustomHeaderFilter.class
using following
command. It will generate a jar AddCustomHeaderFilter.jar
:
jar -cvf AddCustomHeaderFilter.jar com
Put this jar in your Web application's WEB-INF/lib
folder. It will enable the Servlet filter in the web application.
NOTE:
The example given in AddCustomHeaderFilter.java
class is for "SAMEORIGIN". There are below possible values for X-Frame-Options:
- DENY: The page cannot be displayed in a frame, regardless of the
site attempting to do so.
- SAMEORIGIN: The page can only be displayed in a frame on the same
origin as the page itself.