1

我正在开发一个具有以下内容的 Web 应用程序:

  1. Glassfish v3.1.2
  2. 日食朱诺 SR2
  3. JPA EclipseLink2.0
  4. JSF 2.0

对于普通用户和管理员用户,我有不同的页面集。在登录期间尝试设置页面过滤器时,我在登录 bean 中收到此错误:javax.faces.FacesException: #{loginBean.login}: java.lang.NullPointerException

没有这部分,我的整个登录代码都可以工作

if (uGDB.validateGroup(username, adminGroup)) {
                return "home.jsf?faces-redirect=true&includeViewParams=true";
            }
            return "normalHome.jsf?faces-redirect=true&includeViewParams=true"

;

我在这里要做的是获取正在登录的用户的组 ID 并检查它是否是管理员。因此,我想将用户引导到相应的页面。这是因为我为管理员用户和普通用户设置了不同的页面。我不想使用 Glassfish 领域,因为最终用户不需要它。

有人可以帮我确定我在哪里出错了。(请原谅我的愚蠢错误,我刚刚开始进行这样的开发)。提前非常感谢!

下面是我的 loginBean 的代码

   package beans;

import java.io.Serializable;

import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import ejb.UserDaoBean;
import ejb.UserGroupDaoBean;

import model.User;

@ManagedBean(name = "loginBean")
@RequestScoped
public class LoginBean implements Serializable {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    @EJB
    private UserDaoBean uDB;
    private UserGroupDaoBean uGDB;
    private User userId;

    private int adminGroup = 1;

    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String login() {
        FacesContext context = FacesContext.getCurrentInstance();

        if (uDB.validateUser(username)) {
            userId = uDB.findUser(username);

            context.getExternalContext().getSessionMap().put("userId", userId);
            if (uGDB.validateGroup(username, adminGroup)) {
                return "home.jsf?faces-redirect=true&includeViewParams=true";
            }
            return "normalHome.jsf?faces-redirect=true&includeViewParams=true";

        } else {
            FacesMessage message = new FacesMessage();
            message.setSeverity(FacesMessage.SEVERITY_ERROR);
            message.setSummary("Username doesn't exists! OR User is trying to login from someone else's account");
            context.addMessage("", message);
            return null;
        }
    }

    public String logout() {
        FacesContext.getCurrentInstance().getExternalContext()
                .invalidateSession();
        return "logout.jsf?faces-redirect=true";
    }

}

这是 Glassfish 日志中的完整错误堆栈

WARNING: #{loginBean.login}: java.lang.NullPointerException
javax.faces.FacesException: #{loginBean.login}: java.lang.NullPointerException
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
    at javax.faces.component.UICommand.broadcast(UICommand.java:315)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: javax.faces.el.EvaluationException: java.lang.NullPointerException
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:102)
    at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
    ... 31 more
Caused by: java.lang.NullPointerException
    at beans.LoginBean.login(LoginBean.java:49)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
    at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
    at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
    at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
    ... 32 more

这是我的控制器类

package ejb;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateful;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import javax.persistence.PersistenceContext;

import model.Group;
import model.User;
import model.UserGroup;

@Stateful
@LocalBean
public class UserGroupDaoBean {
    @PersistenceContext(unitName = "myPU")
    private EntityManager entityManager;

    public UserGroupDaoBean() {

    }

    public UserGroup createNewUserGroup(int groupId, String username) {

        UserGroup newUserGrp = new UserGroup();

        User myUsr;
        myUsr = entityManager.find(User.class, username);
        newUserGrp.setUser(myUsr);

        Group myGrp;
        myGrp = entityManager.find(Group.class, groupId);
        newUserGrp.setGroup(myGrp);

        saveNewUsrGrp(newUserGrp);
        return newUserGrp;
    }

    private void saveNewUsrGrp(UserGroup usrGrp) {
        entityManager.persist(usrGrp);
        entityManager.flush();
    }

    public boolean checkUsertoGroup(String username, int groupId) {

        Group chkGrp;
        chkGrp = entityManager.find(Group.class, groupId);

        User chkUsr;
        chkUsr = entityManager.find(User.class, username);

        if (chkGrp != null) {

            if (chkUsr != null) {

                try {
                    entityManager.createNamedQuery("findGroupsbyUser")
                            .setParameter("username", chkUsr)
                            .setParameter("groupId", chkGrp).getSingleResult();
                    System.out.println("UserGroup already exists");
                    return false;
                } catch (NoResultException e) {
                    return true;
                }

            }
            System.out.println("User doesn't exist");
            return false;
        }
        System.out.println("Group doesn't exist");

        return false;

    }

    public void deleteUserGroup(UserGroup userGroup) {
        userGroup = entityManager.merge(userGroup);
        entityManager.remove(userGroup);
    }

    public UserGroup update(UserGroup myUserGroup) {
        return entityManager.merge(myUserGroup);
    }

    @SuppressWarnings("unchecked")
    public List<UserGroup> getAllUserGroups() {

        try {
            Query query = entityManager.createNamedQuery("findAllUserGroup");
            List<UserGroup> result = (List<UserGroup>) query.getResultList();
            return result;

        } catch (NoResultException e) {
            System.out.println("No Result found");
            return null;
        }
    }

    public boolean validateGroup(String username, int groupId) {

        try {
            UserGroup myGroupId = (UserGroup) entityManager
                    .createNamedQuery("findGroup")
                    .setParameter("username", username)
                    .setParameter("groupId", groupId).getSingleResult();

            if (myGroupId != null) {
                System.out.println("This user is admin!!!");
                return true;
            }

        } catch (NoResultException e) {
            return false;
        }

        System.out.println("This user is not admin");
        return false;
    }
}

下面是我的实体用户组

package model;

import java.io.Serializable;
import javax.persistence.*;


/**
 * The persistent class for the UserGroup database table.
 * 
 */
@NamedQueries({

    @NamedQuery(name = "findGroupsbyUser", query = "Select ug.group from UserGroup ug where ug.user=:username AND ug.group=:groupId"),

    @NamedQuery(name = "findAllUserGroup", query="Select ug from UserGroup ug"),

    @NamedQuery(name = "findAdminGroupId", query = "Select ug from UserGroup ug where ug.user=:username AND ug.group=:groupId"),


})
@Entity
@Table(name="usergroup")
public class UserGroup implements Serializable {
    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="RowId" )
    private int rowId;

    //bi-directional many-to-one association to Group
    @ManyToOne
    @JoinColumn(name="groupId")
    private Group group;

    //bi-directional many-to-one association to User
    @ManyToOne
    @JoinColumn(name="username")
    private User user;

    public UserGroup() {
    }

    public int getRowId() {
        return this.rowId;
    }

    public void setRowId(int rowId) {
        this.rowId = rowId;
    }

    public Group getGroup() {
        return this.group;
    }

    public void setGroup(Group group) {
        this.group = group;
    }

    public User getUser() {
        return this.user;
    }

    public void setUser(User user) {
        this.user = user;
    }

}
4

1 回答 1

1

阅读堆栈跟踪:在 LoginBean.java 的第 49 行抛出 NPE。

很有可能,uGBD为空,因为缺少 EJB 注释。您需要在要注入的每个EJB前面使用 @EJB 注释:

@EJB
private UserDaoBean uDB;
@EJB
private UserGroupDaoBean uGDB;
...
于 2013-03-28T23:32:01.050 回答