20130305 checkbox

 

 

お題

HTMLでcheckboxを使用する場合の、jsp及び、servletの書き方

(strutsのmultiboxを使う必要がでてきそうなので基礎のおさらい。)

 

■index.jsp

<%@ page pageEncoding="Windows-31J" contentType="text/html; charset=Windows-31J" %>

<html>
<head>
<title>checkboxtest</title>
</head>
<body>
 <h1>ようこそ</h1>

 <form action="loginInit.do" method="post">  
  <p>Default<br>
  <input type="checkbox" name="q1" value="chk1"> check1
  <input type="checkbox" name="q2" value="chk2"> check2
  </p>
  
  <input type="submit" value="Submit" />
 </form>

</body>

</html>

 

■FirstPageAction.java

package hoge;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FirstPageAction extends HttpServlet {

 public static final String RESULT_PAGE_JSP = "/result.jsp";

 protected void doPost(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {

  String q1 = request.getParameter("q1");
  String q2 = request.getParameter("q2");

  request.setAttribute("q1", q1);
  request.setAttribute("q2", q2);
  String nextJsp = RESULT_PAGE_JSP;

  ServletContext context = getServletContext();
  RequestDispatcher rd = context.getRequestDispatcher(nextJsp);
  rd.forward(request, response);
 }
}

■result.jsp

<%@ page pageEncoding="Windows-31J"
 contentType="text/html; charset=Windows-31J"%>

<html>
<head>
<title>checkboxtest</title>
</head>
<body>
  <%=request.getAttribute("q1")%>
  <%=request.getAttribute("q2")%>
</body>

</html>

 

<ポイント>

<input type="checkbox" name="q1" value="chk1"> check1

input type= textと同じで、name属性とvalueを書く。

getParameterでnameを指定するとvalueが得られる。

 

結果は下図。

f:id:mocomei:20130305224034j:plain