我试图做一个关于调查的“简单”应用程序。您有一些选项(复选框),然后结果(投票)显示在其他页面中。
我有这个类,我可以一直保留结果(我想更新这个类,使用 HttpSession)。我使用的是HashMap类,但我改变了,我认为没关系:
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 *********/
现在,这是主窗体 (jsp),它尝试将 JavaBean 放入会话中: 注意:我正在使用 JSP 的旧 sintaxis,因为我还在学习。
<%@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>
这是结果页面:
<%@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>
这里的问题是我不能使用 object SurveyBean
。我不确定第一页(表单)是否正确初始化了 bean。而且我无法从会话中获取对象。
注意:对不起,我的英语真的很差。