问题
Is there any possiblity to obtain the list of constraints from 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>
Even better is there a programmatic way to add new constraints ?
Thanks, Victor
回答1:
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.
回答2:
As per Servlet 3.0 on Annotations and Deployment descriptors there is no mention of adding new security-constraints
programatically. So, I doubt if you can add security contraints programatically.
来源:https://stackoverflow.com/questions/16733946/programmatically-retrieve-security-constraints-from-web-xml