0

我在包含一些单选按钮的 Struts2 JSP 中有以下表单。页面上还有 2 个其他表单可以正常工作,但这个没有。我已经确定所选的值以某种方式没有被传递,这就是我得到 NullPointerException 的原因,但我无法弄清楚它为什么会发生。谁能帮我?这是我的 JSP 表单。

            <s:form action="ProcessPoll3">
                <table>
                    <tr>
                        <td><b><i>Poll #3</i></b></td>
                        <td>How many kids do you have?</td>
                        <td><s:radio name="poll3"
                            list="#{'1':'0.', '2':'1.', '3':'2.', 
                                    '4':'3.', '5':'More than 3.'}" />
                        <s:submit value="Vote Poll #3" align="left" /></td>
                    </tr>
                </table>
            </s:form>

我的 DAO 类被这一行调用(肯定会被调用): String poll3; 私有 HttpServletResponse 响应;

public String getPoll3() {
    return poll3;
}

public void setPoll2(String poll3) {
    this.poll3 = poll3;
}

public String execute() {
        Poll3DAO poll3DAO = new Poll3DAO();

        if (poll3DAO.tallyVote(poll3).equals("success")) {
           // Processing goes on here, not relevant to this problem
        }

这是 DAO 类中的方法,标记了故障点,因为应该传递的参数为空。

public String tallyVote(String vote) {
    String successfulWrite;
    request = ServletActionContext.getRequest();
    SessionFactory sessionFactory = (SessionFactory) request.getSession()
            .getServletContext().getAttribute("sessionFactory");
    Session session = sessionFactory.openSession();
    try {
        // Get previous results
        Transaction tx1 = session.beginTransaction();
        Query myQuery = session.createQuery("from Poll3");
        tx1.commit();

        // Update results
        Iterator<Poll3> iterate = myQuery.iterate();
        Poll3 poll3 = iterate.next();
        // NullPointerException occurs on next line
        if (vote.equals("1")) {
            poll3.setZero(poll3.getZero() + 1);
        } else if (vote.equals("2")) {
            poll3.setOne(poll3.getOne() + 1);
        } else if (vote.equals("3")) {
            poll3.setTwo(poll3.getTwo() + 1);
        } else if (vote.equals("4")) {
            poll3.setThree(poll3.getThree() + 1);
        } else if (vote.equals("5")) {
            poll3.setMoreThanThree(poll3.getMoreThanThree() + 1);
        }

        // Write new results back to database;
        Transaction tx2 = session.beginTransaction();
        session.update(poll3);
        tx2.commit();
        successfulWrite = "success";
    } catch (Exception e) {
        System.out.println(e.toString());
        successfulWrite = "failure";
    }

    return successfulWrite;
}
4

1 回答 1

1

我打赌是这样的:

public void setPoll2(String poll3) { ... }

这就是为什么我们有 map/collection 支持来避免编写像这样的剪切和粘贴 blob。

每当您发现自己在片段中剪切和粘贴代码时,通常是因为抽象被忽略/忽略了。

于 2012-06-26T21:31:44.263 回答