If you have a ServletContainerInitializer
, in its onStartup()
method, you would basically do what your container does when it parses your web.xml. For example:
@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);
}
There are a lot of options in the constructors I've commented for all sorts of configurations, even through the servlet 3.0 security annotations. I'll let you discover them all.
As for adding new constraints after initialization, the javadoc for setServletSecurity()
says:
* @throws IllegalStateException if the {@link ServletContext} from
* which this <code>ServletRegistration</code> was obtained has
* already been initialized
I couldn't find anything for obtaining a list of constraints through ServletContext
interface, but you can always parse the web.xml yourself.