The Java EE 5 Tutorial

Declaring Security Roles

There are two annotations that can be used with servlets: @DeclareRoles and @RunAs. In this example, the @DeclareRoles annotation is used to specify which roles are referenced in this example.

The following section of the tut-install/javaeetutorial5/examples/web/hello2_basicauth/src/servlets/GreetingServlet.java file contains the code necessary to declare that the role of helloUser is used in this application:

package servlets;

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.annotation.security.DeclareRoles;
/**
* This is a simple example of an HTTP Servlet that can only be accessed
* by an authenticated user.  It responds to the GET
* method of the HTTP protocol.
*/
@DeclareRoles("helloUser")
public class GreetingServlet extends HttpServlet {

    public void doGet (HttpServletRequest request,
        HttpServletResponse response)
            throws ServletException, IOException

You could also declare security roles using the <security-role> element in the deployment descriptor. If you prefer to declare security roles this way, read Declaring Roles Using Deployment Descriptor Elements.