The Java EE 5 Tutorial

Declaring Roles Using Annotations

The preferred method of declaring roles referenced in an application is to use the @DeclareRoles annotation. The following code sample provides an example that specifies that the roles of j2ee and guest will be used in the application, and verifies that the user is in the role of j2ee before printing out Hello World.


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@DeclareRoles({"j2ee", "guest"})
public class Servlet extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        PrintWriter out = resp.getWriter();

        out.println("<HTML><HEAD><TITLE>Servlet Output</TITLE>
         if (req.isUserInRole("j2ee") && !req.isUserInRole("guest")) {
            out.println("Hello World");
        } else {
            out.println("Invalid roles");