在我当前的 Web 应用程序中,我试图摆脱 web.xml,但我无法正确设置强制对应用程序的所有请求都使用 HTTPS 的安全约束。
<security-constraint>
<web-resource-collection>
<web-resource-name>all</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>
<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
如何在执行相同操作的 servlet 3.x 配置代码中转换上述 web.xml 配置片段?
更新
我希望将约束应用于应用程序中的每个 servlet、过滤器和静态资源,到目前为止我在网上看到的示例显示将安全约束附加到 servlet,但我希望将安全约束附加到 web 应用程序.在上面的 xml 片段中,您会看到它没有引用任何特定的 servlet
最佳答案
我相信您正在寻找 @ServletSecurity
注释
@WebServlet(urlPatterns = "/*")
@ServletSecurity(value = @HttpConstraint(transportGuarantee = TransportGuarantee.CONFIDENTIAL))
public class SomeServlet extends HttpServlet { ... }
或在 ServletContainerInitializer
中使用 ServletRegistration
(或任何您有权访问 ServletContext
的地方)
ServletRegistration.Dynamic dynamic = context.addServlet("someServlet", SomeServlet.class);
dynamic.addMapping("/*");
HttpConstraintElement httpConstraintElement = new HttpConstraintElement(TransportGuarantee.CONFIDENTIAL);
ServletSecurityElement servletSecurityElement = new ServletSecurityElement(httpConstraintElement);
dynamic.setServletSecurity(servletSecurityElement);
关于java - 如何以编程方式在 Servlets 3.x 中设置 <security-constraint>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19297796/