示例:企业 Bean 应用程序代码

以下 Enterprise JavaBeans (EJB) 组件示例说明了 isCallerInRole 和 getCallerPrincipal 方法在 EJB 模块中的用法。

建议使用声明式安全性。以下示例是使用 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;
}

Home 接口

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 应用程序”。使用“将安全角色引用和角色名映射至角色链接”下的信息来创建元素。


指示主题类型的图标 参考主题



时间戳记图标 最近一次更新时间: last_date
http://www14.software.ibm.com/webapp/wsbroker/redirect?version=cord&product=was-nd-mp&topic=xsec_ejb
文件名:xsec_ejb.html