如题。
项目都部署在Glassfish里,ejb和web是分开的两个项目。实体类是TUser,有默认的构造方法、其他的构造方法和get、set方法。
sessionBean
- Java code
package serviceimpl;import java.util.List;import java.util.logging.Level;import javax.ejb.Local;import javax.ejb.Remote;import javax.ejb.Stateless;import javax.persistence.EntityManager;import javax.persistence.PersistenceContext;import javax.persistence.Query;import service.TUserFacadeLocal;import service.TUserFacadeRemote;import util.LogUtil;import entitys.TUser;@Stateless(mappedName="TUserFacadeBean")@Remote(TUserFacadeRemote.class)@Local(TUserFacadeLocal.class)public class TUserFacadeBean implements TUserFacadeLocal, TUserFacadeRemote {@PersistenceContext private EntityManager entityManager; public TUser findById(Integer id) { LogUtil.log("finding TUser instance with id: " + id, Level.INFO, null); try { TUser instance = entityManager.find(TUser.class, id); LogUtil.log("findById userName " + instance.getUserName(), Level.INFO, null); return instance; } catch (RuntimeException re) { LogUtil.log("find failed", Level.SEVERE, re); throw re; } }}
在web的项目里用的是JSF2.1,使用spring查找sessionBean
- Java code
public class UserBean implements Serializable { private TUserFacade userService; public void setUserService(TUserFacade userService) { this.userService = userService; } public void findUser(int id){ TUser user = userService.findById(id); LogUtil.log("userName: " + user.getUserName(), Level.INFO, null); } public List<TUser> getAll() { return userService.findAll(0, 10); } public static void main(String[] args) { System.out.println("begin"); Properties props = new Properties(); props.setProperty("java.naming.factory.initial", "com.sun.enterprise.naming.SerialInitContextFactory"); props.setProperty("java.naming.factory.url.pkgs", "com.sun.enterprise.naming"); props.setProperty("java.naming.factory.state", "com.sun.corba.ee.impl.presentation.rmi.JNDIStateFactoryImpl"); props.setProperty("org.omg.CORBA.ORBInitialHost", "localhost"); props.setProperty("org.omg.CORBA.ORBInitialPort", "3700"); try { InitialContext ctx = new InitialContext(props); TUserFacade helloWorld = (TUserFacade) ctx.lookup("TUserFacadeBean"); TUser user = helloWorld.findById(1); System.out.println(user.getUserName()); } catch (NamingException e) { e.printStackTrace(); } }}
- XML code
<jee:remote-slsb id="userServiceRemote" business-interface="service.TUserFacade" jndi-name="TUserFacadeBean"></jee:remote-slsb> <bean id="userBean" class="backbean.UserBean" scope="session"> <property name="userService" ref="userServiceRemote"/> </bean>
单独运行UserBean,在控制台会显示user.getUserName()的值。
但是在xhml里,使用el表达式调用findUser方法,在日志文件里可以看到TUserFacadeBean里的findById方法显示的user对象的值,但是在UserBean的调用得到的user.getUserName()是null。不知道这是为什么,希望各位不吝赐教,多谢多谢!
------解决方案--------------------
输出一下UserBean的toString,看看地址是不是一样的。
是不是在EJB这边的对象没有传到你的web层去,而在web层里面是一个新new的对象。