如果你有一个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安全注释。我会让你发现它们。
至于在初始化后添加新约束,javadoc forsetServletSecurity()
说:
* @throws IllegalStateException if the {@link ServletContext} from
* which this <code>ServletRegistration</code> was obtained has
* already been initialized
我找不到通过ServletContext
接口获取约束列表的任何东西,但您始终可以自己解析 web.xml。