1. 程式人生 > >Struts2 checkbox複選框 傳值/取值

Struts2 checkbox複選框 傳值/取值

jsp 程式碼:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
< prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>Struts2 複選框資料傳值</title>
 <script type="text/javascript">
  function checkAll(){
   var listc = document.getElementsByName("listCheck");
   if(document.getElementById("CheckAll").checked==true){
    for(var i=0;i<listc.length;i++){
     listc[i].checked=true;
    }
   }else{
    for(var i=0;i<listc.length;i++){
     listc[i].checked=false;
    }
   }
  }
 </script>
  </head>
  <body>
    <form action="test" method="post">&nbsp;&nbsp; 
     <input type="checkbox" name="CheckAll" id="CheckAll" onclick="checkAll()"/>全選<br/>
     <input type="checkbox" name="listCheck" value="111" />111<br/>
     <input type="checkbox" name="listCheck" value="222" />222<br/>
     <input type="checkbox" name="listCheck" value="333" />333<br/>
     <input type="checkbox" name="listCheck" value="444" />444<br/>
     <input type="checkbox" name="listCheck" value="555"/>555 <br/>
     <input type="submit" value="提交"/>
    </form>
    <c:forEach items="${listCheck }" var="che">
     <c:out value="${che }" /> &nbsp;&nbsp; &nbsp;&nbsp;
    </c:forEach>
  </body>
</html>

struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <package name="index" namespace="/" extends="struts-default">
  <action name="test" class="com.okttl.web.action.CheckBoxTestAction" method="findAll">
   <result>
    /index.jsp
   </result>
  </action>
 </package>
</struts>   

Action 類:

package com.okttl.web.action;

import java.util.List;

import com.okttl.entity.Users;
import com.opensymphony.xwork2.ActionSupport;

public class CheckBoxTestAction extends ActionSupport {

 private List listCheck;
 
 public List getListCheck() {
  return listCheck;
 }
 public void setListCheck(List listCheck) {
  this.listCheck = listCheck;
 }


 public String findAll(){
   System.out.println(listCheck);
  return SUCCESS;
 }
}

-----傳值判斷是否要選中複選框

<s:iterator value="bookList" id="book">
    <s:property value="name"/> 
    <input type="checkbox" name="bookIds" value="${book.id}"
        <s:iterator value="bookIds" id="id">
            <s:if test="#book.id==id">
                checked="checked"
            </s:if>
        </s:iterator>
    /> <br/>       <%--checkbox的結尾--%>
</s:iterator>

bookList是action中的List<Book>屬性,查詢資料庫所有的book放值棧中
bookIds是action中的Integer[]屬性,某個人已經選的書