我们目前在从Struts 1迁移到Struts 2的过程中有一个java Web应用程序。我们希望为所有Struts 2操作配置X-Frame-Options
和Content-Security-Policy
标头。我们有很多行动,如果可能的话,我想避免单独修改它们。
我目前拥有的想法是以下拦截器,它将被添加到默认堆栈中:
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
public class HttpHeaderInterceptor implements Interceptor {
private static final long serialVersionUID = 1L;
@Override
public void destroy() {
// TODO Auto-generated method stub
}
@Override
public void init() {
// TODO Auto-generated method stub
}
@Override
public String intercept(ActionInvocation Invocation) throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
response.addHeader("X-Frame-Options", "SAMEORIGIN");
response.addHeader("Content-Security-Policy-Report-Only", "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'self'; connect-src 'self'; report-uri REDACTED");
response.addHeader("X-Content-Security-Policy-Report-Only", "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'self'; connect-src 'self'; report-uri REDACTED");
return Invocation.invoke();
}
}
我尝试了以上操作,但它不起作用,它没有设置标题。
我需要做些什么修改来修复这个拦截器?是否有可能以这种方式更改响应标头?
答案 0 :(得分:2)
在拦截器内获取响应(和请求)的正确方法是通过InvocationContext
,而不是通过ServletActionContext
:
public String intercept(ActionInvocation Invocation) throws Exception {
final ActionContext ac = invocation.getInvocationContext();
HttpServletResponse response = (HttpServletResponse) ac.get(StrutsStatics.HTTP_RESPONSE);
//HttpServletResponse response = ServletActionContext.getResponse();
response.addHeader("X-Frame-Options", "SAMEORIGIN");
response.addHeader("Content-Security-Policy-Report-Only", "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'self'; connect-src 'self'; report-uri REDACTED");
response.addHeader("X-Content-Security-Policy-Report-Only", "default-src 'self'; script-src 'self' 'unsafe-inline'; object-src 'none'; style-src 'self' 'unsafe-inline'; img-src 'self'; media-src 'none'; frame-src 'none'; font-src 'self'; connect-src 'self'; report-uri REDACTED");
return Invocation.invoke();
}