調査に関する「簡単な」アプリケーションを実行しようとしていました。いくつかのオプション (チェックボックス) があり、結果 (投票) が他のページに表示されます。
結果を常に保持できるこのクラスがあります (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 *********/
さて、これは JavaBean をセッションに入れようとするメイン フォーム (jsp) です。
<%@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>
ここでの問題は、オブジェクトを使用できないことSurveyBean
です。最初のページ (フォーム) が Bean を正しく初期化するかどうかはわかりません。そして、セッションからオブジェクトを取得できません。
注: 申し訳ありませんが、私の英語は本当に下手です。