The Java EE 5 Tutorial

Annotating the Bean

The source code for the original cart application was modified as shown in the following code snippet (modifications in bold, method details removed to save space). The resulting file can be found in the following location:

tut-install/javaeetutorial5/examples/ejb/cart-secure/cart-secure-ejb/src/java/cart/secure/
ejb/CartBean.java

The code snippet is as follows:

package com.sun.tutorial.javaee.ejb;

import java.util.ArrayList;
import java.util.List;
import javax.ejb.Remove;
import javax.ejb.Stateful;
import javax.annotation.security.RolesAllowed;
@Stateful()
public class CartBean implements Cart {

    String customerName;
    String customerId;
    List<String> contents;

    public void initialize(String person) throws BookException {
         ...
        }

    public void initialize(String person, String id) throws BookException {
         ... }

    @RolesAllowed("CartUser")
    public void addBook(String title) {
        contents.add(title);
    }

    @RolesAllowed("CartUser")
    public void removeBook(String title) throws BookException {
         ... }
    }
    @RolesAllowed("CartUser")
    public List<String> getContents() {
        return contents;
    }

    @Remove()
        public void remove() {
        contents = null;
    }
}

The @RolesAllowed annotation is specified on methods for which you want to restrict access. In this example, only users in the role of CartUser will be allowed to add and remove books from the cart, and to list the contents of the cart. An @RolesAllowed annotation implicitly declares a role that will be referenced in the application; therefore, no @DeclareRoles annotation is required.