@ServletSecurity annotation is used to define access control constraints to servlets. The equivalent enforcement of security constraint via web.xml looks like this:
In above example we are securing AppController servlet access by supplying matching url pattern of <security-constraint>. That means requester has to provide valid username/password to access the resource. The security applies to only Get method. Also we are using BASIC authentication method specified in <login-config> element, which ends up browser specific standard login dialog. We are going to create equivalent annotation based servlet. Also we will use Tomcat for container managed security.
Prepare project
Create web application using maven-archetype-webapp, steps here.
Here we are not going to delete web.xml as we still need to add <login-config> there.
In pom.xml add dependency of javax.servlet-api:3.0.1
In pom.xml add tomcat7-maven-plugin to run it as embedded server. Also note we have to provide tomcat-users.xml file. In standard installation of tomcat we can find that file under $CATALINA_BASE/conf/ folder.
We don't need any jsp or html file in this example so delete index.jsp created by default
Create a servlet class AppController annotated with @WebServlet and @ServletSecurity
Now we are going to run our web application from root folder:
mvn clean tomcat7:run-war
Put following url in your browser:
http://localhost:8080/servlet-security-example/
You will see Authentication Required dialog (or similar dialog if using browser other than chrome v 47) Enter user name/password as provided in webapp/config/tomcat-users.xml. On successful login you should see the message printed by AppController servlet.