-->

Putting a JavaBean into a HttpSession in JSP

2019-09-08 03:25发布

问题:

I was trying to do a "simple" application about a survey. Where you have some options (checkboxes) and then the results (votes) are shown in other page.

I have this class where I can keep the results all time (I want to update this class, using HttpSession). I was using the class HashMap, but I changed, I think it doesn't matter:

package beans;
import java.util.ArrayList;
import java.util.List;

public class SurveyBean {

    private List<String> keys;
    private List<String> values;

    public SurveyBean() {
        keys = new ArrayList<String>(); //keys: {"Cat", "Dog", "Other animal"}
        values = new ArrayList<String>(); //Values: {"12","5","4"}
        // By example, a value of 12 means, 12 people like cats.

        keys.add("Cat");
        keys.add("Dog");
        keys.add("Bird");

        // Don't ask me why did I use Strings instead of Integers.
        values.add("0"); // Zero votes 
        values.add("0");
        values.add("0");

    }

    // add one vote to the list of values
    public void addVote( String key, int value ) {
        int index = keys.indexOf(key);
        int newValue = Integer.parseInt(values.get(index)) + value;
        values.set(index, "" + newValue);
    }


    /********* Get and set methods *********/

Now, this is the main form (jsp), which tries to put a JavaBean into the session: Note: I'm using old sintaxis of JSP, because I'm still learning.

<%@page contentType="text/html" session="true" pageEncoding="UTF-8"%>
<!DOCTYPE html>

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <!-- Create the JavaBean "SurveyBean" (Scope: session) -->
    <jsp:useBean id="survey" class="beans.SurveyBean" scope="session"  />

    What's your favorite animal ?
    <form action="page2.jsp" method="POST">
        <%
            java.util.List<String> list = survey.getKeys();

            /* It prints:
             * What's your favorite animal? (Bird,Dog,Cat, etc.)    
            */
            for( int i = 0; i < list.size(); i++ ) {
                out.println("<input type=\"radio\" name=\"name\" value=\"" + list.get(i) +"\">" + list.get(i) + "<br>");
            }
        %>

        <input type="submit" value="Send" />
    </form>

</body>

And here's the page for the results:

<%@page import="beans.SurveyBean, java.util.*"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>

    <%

      // getting the checKbox selected
      String name = request.getParameter("name");

      // Trying to get the object survey from the session
      HttpSession ses = request.getSession(false);
      SurveyBean sv = (SurveyBean) request.getAttribute("survey");

      // Add one vote to the list of values
      List<String> keys = sv.getKeys();
      List<String> values = sv.getValues();

      // I can't use the objects "Keys" and "values", because they are marked as Null.
      // Why they are Null !!!! ???

    %>

</body>

The problem here is I can't use the object SurveyBean. I'm not sure if the first page (form) initializes the bean correctly. And I can't get the object from the session.
Note: Sorry, my English is really bad.

回答1:

Now I've solved the problem. In the first jsp, which puts the object survey in the session. I add this line:

request.setAttribute("survey2",survey2);

And in the second page, which receives the object, I add this other line:

<%@page contentType="text/html" pageEncoding="UTF-8" session="true"%>

I suposse it was neccesary to add the attribute "session" in the directive @page.

Edit: In reality, that's not the solution. I think it works because I've put the code into a Servlet, like this:

PrintWriter out = response.getWriter();
    try {

        //Getting the parameter and the object survey
        String name = request.getParameter("name");
        HttpSession ses = request.getSession(false);
        SurveyBean survey = (SurveyBean) ses.getAttribute("survey");

        // Adding one vote
        survey.addVote(name,1);

        // Forwarding
        ses.setAttribute("survey", survey);
        RequestDispatcher rd = request.getRequestDispatcher("/page2.jsp");
        rd.forward(request, response);

    } finally {            
        out.close();
    }