的Servlet
如果正在處理來自servlet請求然後將報頭添加到在適當的方法中的反應物(即的doGet,的doPost ...) 。
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setHeader("Content-Security-Policy", "default-src 'self';");
// ...
}
JSF
如果使用JSF然後創建一個過濾器,在web.xml文件中配置它
public class SecurityFilter implements javax.servlet.Filter
{
@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
throws IOException, ServletException
{
HttpServletResponse httpRes = (HttpServletResponse) response;
httpRes.setHeader("Content-Security-Policy", "default-src 'self';");
// Continue the chain.
chain.doFilter(request, response);
}
}
樣本條目添加到web.xml
<filter>
<filter-name>SecurityFilter </filter-name>
<filter-class>com.blah.blah.SecurityFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SecurityFilter</filter-name>
<servlet-name>FacesServlet</servlet-name>
</filter-mapping>