예제: 엔터프라이즈 Bean 애플리케이션 코드
다음 EJB(Enterprise JavaBeans) 컴포넌트 예제는 EJB 모듈에서의 isCallerInRole 및 getCallerPrincipal 메소드 사용에 대해 설명합니다.
선언 보안 사용을 권장합니다. 다음 예제는 isCallerInRole 및 getCallerPrincipal 메소드를 사용하는 한 가지 방법입니다. 애플리케이션은 적합한 방법으로 이 결과를 사용할 수 있습니다.
원격 인터페이스
File : Hello.java
package tests;
import java.rmi.RemoteException;
/**
* Remote interface for Enterprise 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 애플리케이션 보안을 참조하십시오. security-role-ref 및 role-name을 role-link로 맵핑에 대한 정보를 통해 요소를 작성하십시오.