这就是我使用的并且有效。我从这里得到了一切:Java 中的 OWASP 点击劫持保护 https://www.owasp.org/index.php/Clickjacking_Protection_for_Java_EE
在 web.xml 中,根据您要执行的策略添加其中之一:
<display-name>OWASP ClickjackFilter</display-name>
<filter>
<filter-name>ClickjackFilterDeny</filter-name>
<filter-class>org.owasp.filters.ClickjackFilter</filter-class>
<init-param>
<param-name>mode</param-name>
<param-value>DENY</param-value>
</init-param>
</filter>
<filter>
<filter-name>ClickjackFilterSameOrigin</filter-name>
<filter-class>org.owasp.filters.ClickjackFilter</filter-class>
<init-param>
<param-name>mode</param-name>
<param-value>SAMEORIGIN</param-value>
</init-param>
</filter>
<!-- use the Deny version to prevent anyone, including yourself, from framing the page -->
<filter-mapping>
<filter-name>ClickjackFilterDeny</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- use the SameOrigin version to allow your application to frame, but nobody else
<filter-mapping>
<filter-name>ClickjackFilterSameOrigin</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
-->
...
然后在java代码中:
public class ClickjackFilter implements Filter
{
private String mode = "DENY";
/**
* Add X-FRAME-OPTIONS response header to tell IE8 (and any other browsers who
* decide to implement) not to display this content in a frame. For details, please
* refer to http://blogs.msdn.com/sdl/archive/2009/02/05/clickjacking-defense-in-ie8.aspx.
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse)response;
//If you have Tomcat 5 or 6, there is a known bug using this code. You must have the doFilter first:
chain.doFilter(request, response);
res.addHeader("X-FRAME-OPTIONS", mode );
//Otherwise use this:
//res.addHeader("X-FRAME-OPTIONS", mode );
//chain.doFilter(request, response);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) {
String configMode = filterConfig.getInitParameter("mode");
if ( configMode != null ) {
mode = configMode;
}
}