try {
javax.naming.InitialContext ctx=new javax.naming.InitialContext ();
Object ref = ctx.lookup("User");
//cast to Home interface
UserHome userHome = (UserHome) PortableRemoteObject.narrow(ref, UserHome.class);
return userHome;
}
catch (ClassCastException ex) {
ex.printStackTrace() ;
return null;
}catch (NamingException ex) {
ex.printStackTrace() ;
return null;
}
}
/**
* 返回UserInfoHome接口
* @return
*/
private UserInfoHome getUserInfoHome(){
try {
javax.naming.InitialContext ctx=new javax.naming.InitialContext ();
Object ref = ctx.lookup("UserInfo");
//cast to Home interface
UserInfoHome userInfoHome = (UserInfoHome) PortableRemoteObject.narrow(ref,
UserInfoHome.class);
return userInfoHome;
}
catch (ClassCastException ex) {
throw new EJBException();
}catch (NamingException ex) {
throw new EJBException(ex.toString());
}
}
/**
* 返回所有用户记录
* @return c
* @throws javax.ejb.FinderException
*/
public java.util.Collection findAll() {
Collection c = null;
try {
UserHome uh=this.getUserHome() ;
c=uh.findAll() ;
}
catch (FinderException ex) {
throw new javax.ejb.EJBException ();
}
return c;
}
/**
* 删除所有记录
*/
public void delAll(){
try {
UserHome u=getUserHome();
java.util.Collection c=u.findAll() ;
java.util.Iterator i=c.iterator() ;
while(i.hasNext() ){
u.remove(((User)i.next()).getName()) ;
}
}
catch (Exception ex) {
throw new EJBException(ex.toString());
}
}
/**
* 根据用户名删除记录
* @param name
*/
public void delByName(String name) {
try {
User user=findByName(name);
UserHome uh=getUserHome();
uh.remove(user.getName()) ;
}
catch (Exception ex) {
throw new javax.ejb.EJBException (ex.toString());
}
}
/**
* 通过用户名查找用户记录
* @param name
* @return
*/
public User findByName(String name) {
try {
UserHome uh=this.getUserHome() ;
User user=(User)uh.findByPrimaryKey(name) ;
UserHome u=this.getUserHome() ;
User uu=u.findByPrimaryKey(name) ;
return user;
}
catch (FinderException ex) {
throw new EJBException(ex.toString());
}
}
}
UserManagerBean是一个session bean ,它主要是对user的管理,和客户端通讯,其实是session facade模式 。代码里面有注释,这里不多叙述了。
ejb-jar.xml 部署文件描述
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"
<ejb-jar>
<enterprise-beans>
<session>
<display-name>UserManager</display-name>
<ejb-name>UserManager</ejb-name>
<local-home>usersystem.UserManagerLocalHome</local-home>
<local>usersystem.UserManagerLocal</local>
<ejb-class>usersystem.UserManagerBean</ejb-class>
<session-type>Stateless</session-type>
<transaction-type>Container</transaction-type>
<ejb-local-ref>
<description />
<ejb-ref-name>User</ejb-ref-name>
<ejb-ref-type>Entity</ejb-ref-type>
<local-home>usersystem.UserHome</local-home>
<local>usersystem.User</local>
<ejb-link>User</ejb-link>
</ejb-local-ref>
<ejb-local-ref>
<description />