Spring MVC列表多選框


以下範例顯示如何在使用Spring Web MVC框架的表單中使用列表框(Listbox)。首先使用Eclipse IDE來建立一個WEB工程,實現一個讓使用者可選擇自己所善長的技術(多選)的功能。並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程式:

  1. 建立一個名稱為 Listbox 的動態WEB專案。
  2. com.yiibai.springmvc 包下建立兩個Java類UserUserController
  3. jsp子檔案夾下建立兩個檢視檔案:user.jspuserlist.jsp
  4. 最後一步是建立所有源和組態檔案的內容並執行應用程式,詳細如下所述。

完整的專案檔案目錄結構如下所示 -

User.java 的程式碼如下所示 -

package com.yiibai.springmvc;
public class User {

       private String username;
       private String password;
       private String address;
       private boolean receivePaper;
       private String [] favoriteFrameworks;   
       private String gender;
       private String favoriteNumber;
       private String country;
       private String [] skills;

       public String getUsername() {
          return username;
       }
       public void setUsername(String username) {
          this.username = username;
       }

       public String getPassword() {
          return password;
       }
       public void setPassword(String password) {
          this.password = password;
       }
       public String getAddress() {
          return address;
       }
       public void setAddress(String address) {
          this.address = address;
       }
       public boolean isReceivePaper() {
          return receivePaper;
       }
       public void setReceivePaper(boolean receivePaper) {
          this.receivePaper = receivePaper;
       }
       public String[] getFavoriteFrameworks() {
          return favoriteFrameworks;
       }
       public void setFavoriteFrameworks(String[] favoriteFrameworks) {
          this.favoriteFrameworks = favoriteFrameworks;
       }
       public String getGender() {
          return gender;
       }
       public void setGender(String gender) {
          this.gender = gender;
       }
       public String getFavoriteNumber() {
          return favoriteNumber;
       }
       public void setFavoriteNumber(String favoriteNumber) {
          this.favoriteNumber = favoriteNumber;
       }
       public String getCountry() {
          return country;
       }
       public void setCountry(String country) {
          this.country = country;
       }
       public String[] getSkills() {
          return skills;
       }
       public void setSkills(String[] skills) {
          this.skills = skills;
       }
    }

UserController.java 的程式碼如下所示 -

package com.yiibai.springmvc;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;

@Controller
public class UserController {

   @RequestMapping(value = "/user", method = RequestMethod.GET)
   public ModelAndView user() {
      User user = new User();      
      user.setFavoriteFrameworks((new String []{"Spring MVC","Struts 2"}));
      user.setGender("M");
      ModelAndView modelAndView = new ModelAndView("user", "command", user);
      return modelAndView;
   }

   @RequestMapping(value = "/addUser", method = RequestMethod.POST)
   public String addUser(@ModelAttribute("SpringWeb")User user, 
      ModelMap model) {
      model.addAttribute("username", user.getUsername());
      model.addAttribute("password", user.getPassword());
      model.addAttribute("address", user.getAddress());
      model.addAttribute("receivePaper", user.isReceivePaper());
      model.addAttribute("favoriteFrameworks", user.getFavoriteFrameworks());
      model.addAttribute("gender", user.getGender());
      model.addAttribute("favoriteNumber", user.getFavoriteNumber());
      model.addAttribute("country", user.getCountry());
      model.addAttribute("skills", user.getSkills());
      return "userlist";
   }

   @ModelAttribute("webFrameworkList")
   public List<String> getWebFrameworkList()
   {
      List<String> webFrameworkList = new ArrayList<String>();
      webFrameworkList.add("Spring MVC");
      webFrameworkList.add("Struts 1");
      webFrameworkList.add("Struts 2");
      webFrameworkList.add("Apache Hadoop");
      return webFrameworkList;
   }

   @ModelAttribute("numbersList")
   public List<String> getNumbersList()
   {
      List<String> numbersList = new ArrayList<String>();
      numbersList.add("1");
      numbersList.add("2");
      numbersList.add("3");
      numbersList.add("4");
      return numbersList;
   }

   @ModelAttribute("countryList")
   public Map<String, String> getCountryList()
   {
      Map<String, String> countryList = new HashMap<String, String>();
      countryList.put("US", "United States");
      countryList.put("CH", "China");
      countryList.put("SG", "Singapore");
      countryList.put("MY", "Malaysia");
      return countryList;
   }

   @ModelAttribute("skillsList")
   public Map<String, String> getSkillsList()
   {
      Map<String, String> skillList = new HashMap<String, String>();
      skillList.put("Hibernate", "Hibernate");
      skillList.put("Spring", "Spring");
      skillList.put("Apache Hadoop", "Apache Hadoop");
      skillList.put("Struts", "Struts");
      return skillList;
   }
}

這裡的第一個服務方法user(),我們已經在ModelAndView物件中傳遞了一個名稱為「command」的空User物件,因為如果在JSP檔案中使用<form:form>標籤,spring框架需要一個名稱為「command」的物件。 所以當呼叫user()方法時,它返回user.jsp檢視。

第二個服務方法addUser()將根據URL => Listbox/addUser 上的POST方法請求時呼叫。根據提交的資訊準備模型物件。 最後從服務方法返回「userlist」檢視,這將呈現userlist.jsp檢視。

user.jsp 的程式碼如下所示 -

<%@ page contentType="text/html; charset=UTF-8"%>

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC表單處理(列表框)</title>
</head>
<body>

    <h2>使用者資訊</h2>
    <form:form method="POST" action="/Listbox/addUser">
        <table>
            <tr>
                <td><form:label path="username">使用者名:</form:label></td>
                <td><form:input path="username" /></td>
            </tr>
            <tr>
                <td><form:label path="password">密碼:</form:label></td>
                <td><form:password path="password" /></td>
            </tr>
            <tr>
                <td><form:label path="address">地址:</form:label></td>
                <td><form:textarea path="address" rows="5" cols="30" /></td>
            </tr>
            <tr>
                <td><form:label path="receivePaper">是否訂閱:</form:label></td>
                <td><form:checkbox path="receivePaper" /></td>
            </tr>
            <tr>
                <td><form:label path="favoriteFrameworks">喜歡的框架/技術:</form:label></td>
                <td><form:checkboxes items="${webFrameworkList}"
                        path="favoriteFrameworks" /></td>
            </tr>
            <tr>
                <td><form:label path="gender">性別:</form:label></td>
                <td><form:radiobutton path="gender" value="M" label="男" /> <form:radiobutton
                        path="gender" value="F" label="女" /></td>
            </tr>
            <tr>
                <td><form:label path="favoriteNumber">喜歡的數位:</form:label></td>
                <td><form:radiobuttons path="favoriteNumber"
                        items="${numbersList}" /></td>
            </tr>
            <tr>
                <td><form:label path="country">所在國家:</form:label></td>
                <td><form:select path="country">
                        <form:option value="NONE" label="請選擇..." />
                        <form:options items="${countryList}" />
                    </form:select></td>
            </tr>
            <tr>
            <td><form:label path="skills">技術:</form:label></td>
            <td><form:select path="skills" items="${skillsList}"
                    multiple="true" /></td>
        </tr>
            <tr>
                <td colspan="2"><input type="submit" value="提交" /></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

這裡使用<form:select /> 及其屬性 multiple=true標籤來呈現HTML列表多選框。 例如 -

<form:select path="skills" items="${skillsList}" multiple="true" />

它將呈現以下HTML內容。

<select id="skills" name="skills" multiple="multiple">
   <option value="Struts">Struts</option>
   <option value="Hibernate">Hibernate</option>
   <option value="Apache Wicket">Apache Hadoop</option>
   <option value="Spring">Spring</option>
</select>
<input type="hidden" name="_skills" value="1"/>

userlist.jsp 的程式碼如下所示 -

<%@ page contentType="text/html; charset=UTF-8"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<title>Spring MVC表單處理(列表框)</title>
</head>
<body>

    <h2>提交使用者資訊 -</h2>
    <table>
        <tr>
            <td>使用者名:</td>
            <td>${username}</td>
        </tr>
        <tr>
            <td>密碼:</td>
            <td>${password}</td>
        </tr>
        <tr>
            <td>地址:</td>
            <td>${address}</td>
        </tr>
        <tr>
            <td>是否訂閱:</td>
            <td>${receivePaper}</td>
        </tr>
        <tr>
            <td>喜歡的技術/框架:</td>
            <td>
                <%
                    String[] favoriteFrameworks = (String[]) request.getAttribute("favoriteFrameworks");
                    for (String framework : favoriteFrameworks) {
                        out.println(framework);
                    }
                %>
            </td>
        </tr>
        <tr>
            <td>性別:</td>
            <td>${(gender=="M"? "男" : "女")}</td>
        </tr>
        <tr>
            <td>喜歡的數位:</td>
            <td>${favoriteNumber}</td>
        </tr>
        <tr>
            <td>國家:</td>
            <td>${country}</td>
        </tr>
        <tr>
                <td>技術:</td>
                <td>
                    <%
                        String[] skills = (String[]) request.getAttribute("skills");
                            for (String skill : skills) {
                                out.println(skill);
                            }
                    %>
                </td>
            </tr>

    </table>
</body>
</html>

完成建立源和組態檔案後,發布應用程式到Tomcat伺服器。

現在啟動Tomcat伺服器,現在嘗試存取URL => http://localhost:8080/Listbox/user ,如果Spring Web應用程式沒有問題,應該看到以下結果:

提交所需資訊後,點選提交按鈕提交表單。 如果Spring Web應用程式沒有問題,應該看到以下結果: