例: エンタープライズ Bean アプリケーションのコード
次の Enterprise JavaBeans (EJB) コンポーネントの例は、 EJB モジュール内の isCallerInRole および getCallerPrincipal メソッドの使用法を示しています。
宣言セキュリティーを使用することをお勧めします。 以下の サンプルは、isCallerInRole メソッドと getCallerPrincipal メソッドを使用した 1 つの方法です。 アプリケーションは、この結果がアプリケーションに対応している限り、これを使用できます。
リモート・インターフェース
File : Hello.java
package tests;
import java.rmi.RemoteException;
/**
* Remote interface for エンタープライズ Bean: Hello
*/
public interface Hello extends javax.ejb.EJBObject {
public abstract String getMessage()throws RemoteException;
public abstract void setMessage(String s)throws RemoteException;
}
ホーム・インターフェース
File : HelloHome.java
package tests;
/**
* Home interface for Enterprise Bean: Hello
*/
public interface HelloHome extends javax.ejb.EJBHome {
/**
* Creates a default instance of Session Bean: Hello
*/
public tests.Hello create() throws javax.ejb.CreateException,
java.rmi.RemoteException;
}
Bean 実装
File : HelloBean.java
package tests;
/**
* Bean implementation class for Enterprise Bean: Hello
*/
public class HelloBean implements javax.ejb.SessionBean {
private javax.ejb.SessionContext mySessionCtx;
/**
* getSessionContext
*/
public javax.ejb.SessionContext getSessionContext() {
return mySessionCtx;
}
/**
* setSessionContext
*/
public void setSessionContext(javax.ejb.SessionContext ctx) {
mySessionCtx = ctx;
}
/**
* ejbActivate
*/
public void ejbActivate() {
}
/**
* ejbCreate
*/
public void ejbCreate() throws javax.ejb.CreateException {
}
/**
* ejbPassivate
*/
public void ejbPassivate() {}
/**
* ejbRemove
*/
public void ejbRemove() {
}
public java.lang.String message;
//business methods
// all users can call getMessage()
public String getMessage() {
return message;
}
// all users can call setMessage() but only few users can set new message.
public void setMessage(String s) {
// get bean's caller using getCallerPrincipal()
java.security.Principal principal = mySessionCtx.getCallerPrincipal();
java.lang.String callerId= principal.getName();
// check if bean's caller is granted Mgr role
boolean isMgr = mySessionCtx.isCallerInRole("Mgr");
// only set supplied message if caller is "bob" or caller is granted Mgr role
if ( isMgr || callerId.equals("bob") )
message = s;
else
message = "Hello";
}
}
エンティティー Bean の開発後に、セッション Bean Hello のデプロイメント記述子内に、
セキュリティー・ロールの参照を作成します。
<security-role-ref>
<description>Only Managers can call setMessage() on this bean (Hello)</description>
<role-name>Mgr</role-name>
</security-role-ref>
<security-role-ref> エレメントの作成方法については、『エンタープライズ Bean アプリケーションの保護』を参照してください。 「Map security-role-ref and role-name to role-link」の情報を使用してエレメントを作成します。