如何使用Glassfish 4.0服务器将EJB3.1会话bean注入到JEE Enterprise应用程序中的JSF2.2托管bean中

时间:2014-03-02 20:35:03

标签: jsf cdi

我在Netbeans 7.4中创建了一个新的Java EE 6企业应用程序。所以我有三个项目:

EAR
EJB
WAR

为了实现登录功能。我创建了以下内容。

  1. 在EJB-Project中,我创建了一个实体bean(Useraccount)和无状态会话Bean(UseraccoountManager),如下所示:
  2. 实体bean:Useraccount

    package com.wms.entities;
    import java.io.Serializable;
    import javax.persistence.Basic;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    import javax.persistence.Id;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    import javax.validation.constraints.NotNull;
    import javax.validation.constraints.Size;
    import javax.xml.bind.annotation.XmlRootElement;
    
    @Entity
    @Table(name = "useraccount")
    @XmlRootElement
    @NamedQueries({
    @NamedQuery(name = "Useraccount.findAll", query = "SELECT u FROM Useraccount u"),
    @NamedQuery(name = "Useraccount.findById", query = "SELECT u FROM Useraccount u WHERE u.id = :id"),
    @NamedQuery(name = "Useraccount.findByUsername", query = "SELECT u FROM Useraccount u WHERE u.username = :username"),
    @NamedQuery(name = "Useraccount.findByPassword", query = "SELECT u FROM Useraccount u WHERE u.password = :password"),
    @NamedQuery(name = "UserAccount.findUseraccount", query = "SELECT a FROM Useraccount a WHERE a.username = :username AND a.password = :password"),
    @NamedQuery(name = "Useraccount.findByUserType", query = "SELECT u FROM Useraccount u WHERE u.userType = :userType")})
    public class Useraccount implements Serializable {
    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "username")
    private String username;
    @Basic(optional = false)
    @NotNull
    @Size(min = 1, max = 45)
    @Column(name = "password")
    private String password;
    @Size(max = 45)
    @Column(name = "userType")
    private String userType;
    
    public Useraccount() {
    }
    
    public Useraccount(Integer id) {
        this.id = id;
    }
    
    public Useraccount(Integer id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }
    
    public Integer getId() {
        return id;
    }
    
    public void setId(Integer id) {
        this.id = id;
    }
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getUserType() {
        return userType;
    }
    
    public void setUserType(String userType) {
        this.userType = userType;
    }
    
    @Override
    public int hashCode() {
        int hash = 0;
        hash += (id != null ? id.hashCode() : 0);
        return hash;
    }
    
    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Useraccount)) {
            return false;
        }
        Useraccount other = (Useraccount) object;
        if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
            return false;
        }
        return true;
    }
    
    @Override
    public String toString() {
        return "com.wms.entities.Useraccount[ id=" + id + " ]";
    }
    
    }
    

    会话bean:UseraccountManager

    package com.wms.sessions;
    import com.wms.entities.Useraccount;
    import java.util.List;
    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    @Stateless
    
    public class UseraccountManager implements UseraccountManagerRemote{
    @PersistenceContext
    private EntityManager em;
    
    public List<Useraccount> getAllUseraccount() {
        Query query=em.createNamedQuery("Useraccount.findAll");
        return query.getResultList();
    }
    
    public Useraccount update(Useraccount useraccount) {
        return em.merge(useraccount);
    }
    @Override
    public void persist(Object object) {
        em.persist(object);
    }
    
    public Useraccount find(Useraccount useraccount){
       Query query=em.createNamedQuery("Useraccount.findByUsername").setParameter("username", useraccount.getUsername());
       List<Useraccount> acts=query.getResultList();
       if(acts.isEmpty()) 
                return null;
        Useraccount act=acts.get(0);
        if(!act.getPassword().equals(useraccount.getPassword()))
            return null;
        return act;
    }
    @Override
    public String validateUser(String username, String password){
        System.out.println("\n\n\nheloooo\n\n\n");
        Query query=em.createNamedQuery("Useraccount.findByUsername").setParameter("username", username);
        List<Useraccount> acts=query.getResultList();
        if(acts.isEmpty()) 
                return "unknown";
        Useraccount act=acts.get(0);
        if(act.getPassword().equals(password))
            return act.getUserType();
        return "unknown";
    }
    }
    

    2.在Web应用程序项目中,我创建了Managed bean(LoginBean)和Login页面(login.xhtml),如下所示 托管bean:LoginBean

    package com.wms.managedbeans;
    
    import com.wms.sessions.UseraccountManager;
    import java.io.Serializable;
    import javax.ejb.EJB;
    import javax.enterprise.context.RequestScoped;
    import javax.faces.application.FacesMessage;
    import javax.faces.context.FacesContext;
    import javax.inject.Named;
    import javax.servlet.http.HttpSession;
    
    @Named
    @RequestScoped
    
    public class LoginBean implements Serializable {
    
    private static final long serialVersionUID = 1L;
    private String password;
    private String message, username;
    private String userType;
    @EJB
    private UseraccountManager uam;
    
    public String getMessage() {
        return message;
    }
    
    public void setMessage(String message) {
        this.message = message;
    }
    
    public String getPassword() {
        return password;
    }
    
    public void setPassword(String password) {
        this.password = password;
    }
    
    public String getUsername() {
        return username;
    }
    
    public void setUsername(String uname) {
        this.username = uname;
    }
    public String getUser() {
        System.out.println(Util.getUserId());
        return Util.getUserId();
    }
    public String getUserType(){
        HttpSession session = Util.getSession();
        if ( session != null )
            return (String) session.getAttribute("userType");
        else
            return null;
    }
    
    
    public String login() {
         userType = uam.validateUser(username, password);
        HttpSession session = Util.getSession();
        if (userType.equals("unknown")){
            FacesContext.getCurrentInstance().addMessage(
                    null,
                    new FacesMessage(FacesMessage.SEVERITY_WARN,
                    "Invalid Login!",
                    "Please Try Again!"));
            // invalidate session, and redirect to other pages
            //message = "Invalid Login. Please Try Again!";
           return "login";
        }
        else{
          // get Http Session and store username
          session.setAttribute("username", username);
          session.setAttribute("userType",userType);
          if (userType.equals("administrator")) 
            return "admin/adminHome?faces-redirect=true";
          else if(userType.equals("warehouseman"))
            return "WM/wmHome?faces-redirect=true"; 
          else if(userType.equals("employee"))
            return "emp/empHome?faces-redirect=true"; 
          else 
              return "man/manHome?faces-redirect=true";
        }
    }
    
    public String logout() {
      HttpSession session = Util.getSession();
      session.invalidate();
      return "/login?faces-redirect=true";
    }
    }
    

    用户界面:login.xhtml

    <ui:composition template="/templates/layout.xhtml"
     xmlns="http://www.w3.org/1999/xhtml"
     xmlns:f="http://java.sun.com/jsf/core"
     xmlns:h="http://java.sun.com/jsf/html"
     xmlns:ui="http://java.sun.com/jsf/facelets"
     xmlns:p="http://primefaces.org/ui">
     <ui:define name="content">
      <h:form styleClass="loginPanelStyle">
                 <p:growl id="msgs" showDetail="true" sticky="false" />                        
                <p:panelGrid columns="2">
                <f:facet name="header">
                    Login Panel
                </f:facet>
    
                <h:outputText value="Username : "></h:outputText>
                <p:inputText id="username" value="#{loginBean.username}" required="true" requiredMessage="Please Enter Username!">
                    <f:validateLength minimum="1" />  
                </p:inputText>
                <h:outputText value="Password : "></h:outputText>
                <p:password id="password" value="#{loginBean.password}" required="true" requiredMessage="Please Enter password!">
                    <f:validateLength minimum="1" />  
                </p:password>
                <f:facet name="footer">
                    <p:commandButton id="Submit" value="Submit" update="msgs" action="#{loginBean.login}" type="submit" icon="ui-icon-check" style="margin:0"></p:commandButton>
                </f:facet> 
            </p:panelGrid>
        </h:form>
     </ui:define>
    </ui:composition>
    

    在我运行Web应用程序时部署项目后,它会显示登录页面,不幸的是,当我插入时,它会生成以下错误

    WARNING:   /login.xhtml @16,131 value="#{loginBean.username}": Target Unreachable, identifier 'loginBean' resolved to null
    javax.el.PropertyNotFoundException: /login.xhtml @16,131 value="#{loginBean.username}": Target Unreachable, identifier 'loginBean' resolved to null
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:100)
    at org.primefaces.renderkit.InputRenderer.findImplicitConverter(InputRenderer.java:170)
    at org.primefaces.renderkit.InputRenderer.findConverter(InputRenderer.java:190)
    at org.primefaces.renderkit.InputRenderer.getConvertedValue(InputRenderer.java:196)
    at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1046)
    at javax.faces.component.UIInput.validate(UIInput.java:976)
    at javax.faces.component.UIInput.executeValidate(UIInput.java:1249)
    at javax.faces.component.UIInput.processValidators(UIInput.java:712)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIForm.processValidators(UIForm.java:253)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at org.primefaces.component.layout.Layout.processValidators(Layout.java:246)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1261)
    at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1195)
    at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at filters.AuthFilter.doFilter(AuthFilter.java:44)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
    at java.lang.Thread.run(Thread.java:744)
    Caused by: javax.el.PropertyNotFoundException: Target Unreachable, identifier 'loginBean' resolved to null
    at com.sun.el.parser.AstValue.getTarget(AstValue.java:174)
    at com.sun.el.parser.AstValue.getType(AstValue.java:86)
    at com.sun.el.ValueExpressionImpl.getType(ValueExpressionImpl.java:201)
    at org.jboss.weld.el.WeldValueExpression.getType(WeldValueExpression.java:93)
    at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:98)
    ... 51 more
    

    我是EJB + JSF的新手请帮我解决上述问题

1 个答案:

答案 0 :(得分:1)

当我在LoginBean托管bean类中用@ManagedBean(name =“loginBean”)替换@Named注释时,它可以完美地工作。但任何人都可以在这个背景下解释两者之间的区别。感谢Luiggi Medoza的帮助