數據綁定和表單標籤 |
數據綁定是將用戶輸入綁定到領域模型的一種特性,在Spring MVC的controller和view數據傳遞中,基於HTTP請求的特性,全部HTTP請求參數的類型均爲字符串,若是模型領域須要綁定的類型爲double或int,則須要手動進行類型轉換,而有了數據綁定後,就不須要手動將HTTP請求中的String類型轉換爲模型須要的類型了,數據綁定的另外一個好處是,當輸入驗證失敗時,會從新生成一個HTML表單,無需從新填寫輸入字段。css
表單標籤庫中包含了能夠用在JSP頁面中渲染HTML元素的標籤。爲了使用這些標籤,必須在JSP頁面開頭處聲明taglib指令。html
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
表單標籤庫中有input、password、hidden、textarea、checkbox、checkboxes、radiobutton、radiobuttons、select、option、options、errors。表單標籤有acceptCharset、commandName、cssClass、cssStyle、htmlEscape、modelAttribute等屬性。java
<form:form modelAttribute="user" method="post" action="userSave"> <fieldset> <p> <label for="name">用戶名:</label> <form:input path="userName"/> </p> </fieldset> </form:form>
如上分別介紹了數據綁定的定義和優點,以及一些表單標籤,爲了讓你們能進一步瞭解上面的內容,範例中實現了用戶類屬性和JSP中表單的綁定,同時在JSP中分別展現了input、password、textarea、checkbox、select標籤。web
咱們首先看一下User類,類中包含User的屬性,以及對屬性字段的get和set方法:spring
public class User { private String userName; //用戶名 private String password; //密碼 private Integer sex; //性別 private boolean marriage; //是否結婚 private ArrayList<String> hobby; //興趣愛好 private ArrayList<String> contacts;//人脈 private String carrer; //職業 private String houseRegister; //戶籍 private String remark; //我的描述 public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getHouseRegister() { return houseRegister; } public void setHouseRegister(String houseRegister) { this.houseRegister = houseRegister; } public String getCarrer() { return carrer; } public void setCarrer(String carrer) { this.carrer = carrer; } 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 Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public boolean isMarriage() { return marriage; } public void setMarriage(boolean marriage) { this.marriage = marriage; } public ArrayList<String> getHobby() { return hobby; } public void setHobby(ArrayList<String> hobby) { this.hobby = hobby; } public ArrayList<String> getContacts() { return contacts; } public void setContacts(ArrayList<String> contacts) { this.contacts = contacts; } }
咱們的Controller類中定義映射請求的方法,其中包括處理userInput請求的inputUser方法,以及userSave請求的addUser方法,其中在addUser方法中用到了重定向。其中經過@Autowired註釋在ProductController對象中主動注入UserService對象,實現對user對象的保存和查詢等操做;經過model的addAttribute方法將User類對象、HashMap類型的hobbys對象、String[]類型的carrers對象傳遞給View(JSP),代碼以下:瀏覽器
@Controller public class ProductController { private static final Log logger = LogFactory.getLog(ProductController.class); @Autowired private UserService userService; @RequestMapping(value="/userInput") public String inputUser(Model model){ HashMap<Integer, String> hobbys = new HashMap<Integer, String>(); hobbys.put(1, "籃球"); hobbys.put(2, "羽毛球"); hobbys.put(3, "檯球"); hobbys.put(4, "游泳"); model.addAttribute("user", new User()); model.addAttribute("hobbys", hobbys); model.addAttribute("carrers",new String[]{"教師","學生","醫生","IT民工","其它"}); return "UserAdd"; } @RequestMapping(value="/userSave") public String addUser(@ModelAttribute User user){ userService.addUser(user); return "redirect:/userList"; } @RequestMapping(value="/userList") public String listUsers(Model model){ List<User> users = userService.getUsers(); model.addAttribute("users", users); return "UserList"; } }
同時,爲了不中文亂碼的問題,須要在web.xml文件中增長編碼過濾器,同時JSP頁面編碼設置爲UTF-8,form表單的提交方式必須爲post,咱們先看web.xml文件的配置信息:mvc
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/config/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 避免中文亂碼 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
UserAddJSP文件格式以下,其中將Map類型的hobbys綁定到了checkboxes上,將String[]類型的carrer綁定到了select上,實現了經過option標籤對select添加選項,同時method方法需指定爲post來避免中文亂碼的問題。app
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Add a User</title> </head> <body> <div id="global"> <form:form modelAttribute="user" method="post" action="userSave"> <fieldset> <legend>Add a User</legend> <p> <label>用戶名:</label> <form:input path="userName"/> </p> <p> <label>密碼:</label> <form:password path="password"/> </p> <p> <label>婚姻:</label> <form:checkbox path="marriage" value="已婚"/> </p> <p> <label>愛好:</label> <form:checkboxes items="${hobbys}" path="hobby"/> </p> <p> <label>人脈:</label> <form:checkbox path="contacts" value="張三"/>張三 <form:checkbox path="contacts" value="李四"/>李四 <form:checkbox path="contacts" value="王五"/>王五 <form:checkbox path="contacts" value="趙六"/>趙六 </p> <p> <label>職業:</label> <form:select path="carrer"> <option/>請選擇職業 <form:options items="${carrers }"/> </form:select> </p> <p> <label>戶籍:</label> <form:select path="houseRegister"> <option>請選擇戶籍</option> <option value="1">北京</option> <option value="2">上海</option> <option value="3">廣州</option> <option value="4">深圳</option> <option value="5">其它</option> </form:select> </p> <p> <label>我的描述:</label> <form:textarea path="remark" rows="5"/> </p> <p id="buttons"> <input id="reset" type="reset"> <input id="submit" type="submit" value="Add User"> </p> </fieldset> </form:form> </div> </body> </html>
UserList.JSP文件實現對保存的user信息的遍歷展現。jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body> <div id="global"> <h1>User List</h1> <a href="<c:url value="/userInput"/>">Add User</a> <table> <tr> <th>用戶名</th> <th>密碼</th> <th>性別</th> <th>婚姻</th> <th>興趣愛好</th> <th>人脈</th> <th>職業</th> <th>戶籍</th> <th>我的描述</th> </tr> <c:forEach items="${users }" var="user"> <tr> <td>${user.userName }</td> <td>${user.password }</td> <td>${user.sex }</td> <td>${user.marriage }</td> <td>${user.hobby }</td> <td>${user.contacts }</td> <td>${user.carrer }</td> <td>${user.houseRegister }</td> <td>${user.remark }</td> </tr> </c:forEach> </table> </div> </body> </html>
由於該工程是在上一篇工程中增長的,所以其餘的配置文件與上一篇工程中相同,這裏再也不作過多的贅述,但願讀者見諒。ide
運行該程序在瀏覽器中輸入http://localhost:8081/SpringMVC/userInput能夠看到左圖,填寫表單完成,點擊Add User按鈕,便可看到右圖的輸出信息,不知道讀者是否發現輸出信息中存在問題,興趣愛好爲[1],戶籍也爲1,輸出的爲表單中選擇的索引位置,還有好像保單中忘了指定User的性別了,致使輸入性別列爲空。這些問題是因爲本文的疏忽形成的,有興趣的讀者能夠對這篇博客作更加完善的改正,謝謝閱讀!