チェックボックスの選択内容をHttpServletRequestオブジェクトから表示する。またリクエストパラメータを<jsp:setProperty>アクションでJava Beanにセットし、Beanから表示する。
プロジェクト作成
プロジェクト名:Checkbox
HTMLファイル作成
ファイル名:check.html
コーディング
【check.html】
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-31j"> <title>Checkbox</title> </head> <body> <form type="POST" action="checkresult.jsp"> <br> <font size="5" color="red"> Check all Favorite fruits: <br> <input type="checkbox" name="fruit" value="apples"> Apples <br> <input type="checkbox" name="fruit" value="grapes"> Grapes <br> <input type="checkbox" name="fruit" value="oranges"> Oranges <br> <input type="checkbox" name="fruit" value="melons"> Melons <br> <br> <input type="submit" name="submit" value="Submit"> </font> </form> </body> </html>
パッケージ作成
パッケージ名:checkbox
クラス作成(Java Bean)
クラス名:CheckTest
コーディング
【CheckTest.java】
package checkbox;
public class CheckTest {
String b[] = new String[] { "1", "2", "3", "4" };
public String[] getFruit() {
return b;
}
public void setFruit(String[] b) {
this.b = b;
}
}
JSPファイル作成
ファイル名:checkresult.jsp
コーディング
【checkresult.jsp】
<%@ page language="java" contentType="text/html; charset=windows-31j"
pageEncoding="windows-31j"%>
<jsp:useBean id="foo" scope="page" class="checkbox.CheckTest" />
<jsp:setProperty name="foo" property="fruit" param="fruit" />
<%! String[] fruits; %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-31j">
<title>Checkbox</title>
</head>
<body>
<hr>
The checked fruits (got using request) are: <br>
<%
fruits = request.getParameterValues("fruit");
%>
<ul>
<%
if (fruits != null) {
for (int i = 0; i < fruits.length; i++) {
%>
<li>
<%
out.println (fruits[i]);
}
} else out.println ("none selected");
%>
</ul>
<br>
<hr>
The checked fruits (got using beans) are <br>
<%
fruits = foo.getFruit();
%>
<ul>
<%
if (!fruits[0].equals("1")) {
for (int i = 0; i < fruits.length; i++) {
%>
<li>
<%
out.println (fruits[i]);
}
} else out.println ("none selected");
%>
</ul>
</font>
</body>
</html>
詳細request.getParameterValues("fruit") [↑]
| 構文 | java.lang.String[] getParameterValues(java.lang.String name) |
| 対象 | ServletRequestインターフェース |
| 継承 | HttpServletRequestインターフェース |
nameと一致するパラメータを全て返す。一致するパラメータがなければnullを返す。
実行結果
URL: http://localhost:8080/Checkbox/check.html
[1] 初期表示→チェックボックス数個をチェックオン
[2] [Submit]ボタンクリック後
| [1] |
[2] |
|


