Spring MVC多項單選按鈕

以下示例顯示如何在使用Spring Web MVC框架的表單中使用多選按鈕(RadioButton)。首先使用Eclipse IDE來創建一個WEB工程,實現一個讓用戶可選擇自己喜歡的數字的功能。並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程序:

  1. 創建一個名稱爲 RadioButtons 的動態WEB項目。
  2. com.yiibai.springmvc 包下創建兩個Java類UserUserController
  3. jsp子文件夾下創建兩個視圖文件:user.jspuserlist.jsp
  4. 最後一步是創建所有源和配置文件的內容並運行應用程序,詳細如下所述。

完整的項目文件目錄結構如下所示 -

Spring

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;

   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;
   }
}

UserController.java 的代碼如下所示 -

package com.yiibai.springmvc;

import java.util.ArrayList;
import java.util.List;

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());
      return "userlist";
   }

   @ModelAttribute("webFrameworkList")
   public List<String> getWebFrameworkList()
   {
      List<String> webFrameworkList = new ArrayList<String>();
      webFrameworkList.add("Spring MVC");
      webFrameworkList.add("Spring Boot");
      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;
   }
}

這裏的第一個服務方法user(),我們已經在ModelAndView對象中傳遞了一個名稱爲「command」的空User對象,因爲如果在JSP文件中使用<form:form>標籤,spring框架需要一個名稱爲「command」的對象。 所以當調用user()方法時,它返回user.jsp視圖。

第二個服務方法addUser()將根據URL => RadioButtons/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="/RadioButtons/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 colspan="2"><input type="submit" value="提交" /></td>
            </tr>
        </table>
    </form:form>
</body>
</html>

這裏使用<form:radiobuttons />標籤來呈現HTML密碼框。 例如 -

<form:radiobuttons path="favoriteNumber" items="${numbersList}" />

它將呈現以下HTML內容。

<span>
<input id="favoriteNumber1" name="favoriteNumber" type="radio" value="1"/>
<label for="favoriteNumber1">1</label>
</span>
<span>
<input id="favoriteNumber2" name="favoriteNumber" type="radio" value="2"/>
<label for="favoriteNumber2">2</label>
</span>
<span>
<input id="favoriteNumber3" name="favoriteNumber" type="radio" value="3"/>
<label for="favoriteNumber3">3</label>
</span>
<span>
<input id="favoriteNumber4" name="favoriteNumber" type="radio" value="4"/>
<label for="favoriteNumber4">4</label>
</span>

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>    
    </table>
</body>
</html>

完成創建源和配置文件後,發佈應用程序到Tomcat服務器。

現在啓動Tomcat服務器,現在嘗試訪問URL => http://localhost:8080/RadioButtons/user ,如果Spring Web應用程序沒有問題,應該看到以下結果:

Spring

提交所需信息後,點擊提交按鈕提交表單。 如果Spring Web應用程序沒有問題,應該看到以下結果:

Spring