Spring MVC - 单选按钮示例



以下示例说明如何使用 Spring Web MVC 框架在表单中使用单选按钮。首先,我们需要一个可运行的 Eclipse IDE,并按照以下步骤使用 Spring Web 框架开发基于动态表单的 Web 应用程序。

步骤 描述
1 创建一个名为 HelloWeb 的项目,位于 com.tutorialspoint 包下,如 Spring MVC - Hello World 章节所述。
2 在 com.tutorialspoint 包下创建 Java 类 User 和 UserController。
3 在 jsp 子文件夹下创建视图文件 user.jsp 和 users.jsp。
4 最后一步是创建源文件和配置文件的内容,并导出应用程序,如下所述。

User.java

package com.tutorialspoint;

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.tutorialspoint;

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 "users";
   }
   
   @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 Wicket");
      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 对象中传递了一个空的 User 对象,名称为“command”,因为如果您在 JSP 文件中使用 <form:form> 标签,Spring 框架会期望一个名为“command”的对象。因此,当调用 user() 方法时,它会返回 user.jsp 视图。

第二个服务方法 **addUser()** 将针对 **HelloWeb/addUser** URL 上的 POST 方法调用。您将根据提交的信息准备模型对象。最后,服务方法将返回“users”视图,这将导致呈现 users.jsp。

user.jsp

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>
   <body>

      <h2>User Information</h2>
      <form:form method = "POST" action = "/HelloWeb/addUser">
         <table>
            <tr>
               <td><form:label path = "username">User Name</form:label></td>
               <td><form:input path = "username" /></td>
            </tr>
            <tr>
               <td><form:label path = "password">Age</form:label></td>
               <td><form:password path = "password" /></td>
            </tr>  
            <tr>
               <td><form:label path = "address">Address</form:label></td>
               <td><form:textarea path = "address" rows = "5" cols = "30" /></td>
            </tr>  
            <tr>
               <td><form:label path = "receivePaper">Subscribe Newsletter</form:label></td>
               <td><form:checkbox path = "receivePaper" /></td>
            </tr> 
            <tr>
               <td><form:label path = "favoriteFrameworks">Favorite Web Frameworks</form:label></td>
               <td><form:checkboxes items = "${webFrameworkList}" path = "favoriteFrameworks" /></td> 
            </tr>
            <tr>
               <td><form:label path = "gender">Gender</form:label></td>
               <td>
                  <form:radiobutton path = "gender" value = "M" label = "Male" />
                  <form:radiobutton path = "gender" value = "F" label = "Female" />
               </td>
            </tr>
            <tr>
               <td><form:label path = "favoriteNumber">Favorite Number</form:label></td>
               <td>
                  <form:radiobuttons path = "favoriteNumber" items = "${numbersList}" />        	
               </td>
            </tr>  	  
            <tr>
               <td colspan = "2">
                  <input type = "submit" value = "Submit"/>
               </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>    

users.jsp

<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
   <head>
      <title>Spring MVC Form Handling</title>
   </head>
   <body>
      <h2>Submitted User Information</h2>
      <table>
         <tr>
            <td>Username</td>
            <td>${username}</td>
         </tr>
         <tr>
            <td>Password</td>
            <td>${password}</td>
         </tr>    
         <tr>
            <td>Address</td>
            <td>${address}</td>
         </tr>  
         <tr>
            <td>Subscribed to Newsletter</td>
            <td>${receivePaper}</td>
         </tr>    
         <tr>
            <td>Favorite Web Frameworks</td>
            <td> <% String[] favoriteFrameworks = (String[])request.getAttribute("favoriteFrameworks");
               for(String framework: favoriteFrameworks) {
                  out.println(framework);
               }
            %></td>
         </tr>     	 
         <tr>
            <td>Gender</td>
            <td>${(gender=="M"? "Male" : "Female")}</td>
         </tr>
         <tr>
            <td>Favourite Number</td>
            <td>${favoriteNumber}</td>
         </tr>     	  
      </table>  
   </body>
</html>

完成源文件和配置文件的创建后,导出您的应用程序。右键单击您的应用程序,使用 **导出 → WAR 文件** 选项并将 HelloWeb.war 文件保存到 Tomcat 的 webapps 文件夹中。

现在,启动 Tomcat 服务器,并确保您可以使用标准浏览器访问 webapps 文件夹中的其他网页。尝试以下 URL – **https://127.0.0.1:8080/HelloWeb/user**,如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。

Spring RadioButtons Form

提交所需信息后,单击提交按钮提交表单。如果 Spring Web 应用程序一切正常,我们将看到以下屏幕。

Spring RadioButtons Form Result
广告