以编程方式从web.xml检索安全性约束

时间:2013-05-24 11:29:20

标签: java-ee servlets security

是否有可能从web.xml获取约束列表?

 <security-constraint>
    <web-resource-collection>
        <web-resource-name>admin</web-resource-name>
        <url-pattern>/admin/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
        <role-name>admin</role-name>
    </auth-constraint>
 </security-constraint>

更好的是有一种编程方式来添加新约束吗?

谢谢, 维克多

2 个答案:

答案 0 :(得分:3)

如果你的ServletContainerInitializer方法有onStartup(),那么你基本上就可以解析你的容器在解析你的web.xml时所做的事情。例如:

@Override
public void onStartup(Set<Class<?>> classes, ServletContext ctx) throws ServletException {
    ServletRegistration.Dynamic servlet = ctx.addServlet("myServlet", "com.package.myServlet"); // loop through classes set to find all your servlets
    HttpConstraintElement constraint = new HttpConstraintElement(); // many constructors with options
    ServletSecurityElement securityElement = new ServletSecurityElement(constraint); // many different constructors
    servlet.setServletSecurity(securityElement);
}

我为各种配置评论的构造函数中有很多选项,即使是通过servlet 3.0 security annotations也是如此。我会让你发现它们。

至于在初始化后添加新约束,setServletSecurity()的javadoc说:

* @throws IllegalStateException if the {@link ServletContext} from
* which this <code>ServletRegistration</code> was obtained has
* already been initialized

我找不到任何通过ServletContext接口获取约束列表的内容,但您始终可以自己解析web.xml。

答案 1 :(得分:0)

根据Servlet 3.0 on Annotations and Deployment descriptors,没有提及以编程方式添加新security-constraints。所以,我怀疑你是否可以以编程方式添加安全约束。