Spring MVC---數(shù)據(jù)綁定和表單標(biāo)簽詳解
數(shù)據(jù)綁定和表單標(biāo)簽
數(shù)據(jù)綁定
數(shù)據(jù)綁定是將用戶(hù)輸入綁定到領(lǐng)域模型的一種特性,在Spring MVC的controller和view數(shù)據(jù)傳遞中,基于HTTP請(qǐng)求的特性,所有HTTP請(qǐng)求參數(shù)的類(lèi)型均為字符串,如果模型領(lǐng)域需要綁定的類(lèi)型為double或int,則需要手動(dòng)進(jìn)行類(lèi)型轉(zhuǎn)換,而有了數(shù)據(jù)綁定后,就不需要手動(dòng)將HTTP請(qǐng)求中的String類(lèi)型轉(zhuǎn)換為模型需要的類(lèi)型了,數(shù)據(jù)綁定的另一個(gè)好處是,當(dāng)輸入驗(yàn)證失敗時(shí),會(huì)重新生成一個(gè)HTML表單,無(wú)需重新填寫(xiě)輸入字段。
表單標(biāo)簽庫(kù)
表單標(biāo)簽庫(kù)中包含了可以用在JSP頁(yè)面中渲染HTML元素的標(biāo)簽。為了使用這些標(biāo)簽,必須在JSP頁(yè)面開(kāi)頭處聲明taglib指令。
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
表單標(biāo)簽庫(kù)中有input、password、hidden、textarea、checkbox、checkboxes、radiobutton、radiobuttons、select、option、options、errors。表單標(biāo)簽有acceptCharset、commandName、cssClass、cssStyle、htmlEscape、modelAttribute等屬性。
1.input標(biāo)簽:input標(biāo)簽渲染<input type="text"/>元素,這個(gè)標(biāo)簽最重要的是path屬性,該字段將輸入綁定到form backing object的一個(gè)屬性。如下所示,這個(gè)input標(biāo)簽被綁定到了user對(duì)象的userName屬性上
<form:form modelAttribute="user" method="post" action="userSave"> <fieldset> <p> <label for="name">用戶(hù)名:</label> <form:input path="userName"/> </p> </fieldset> </form:form>
2.password標(biāo)簽:渲染<input type="password"/>元素,password標(biāo)簽與input標(biāo)簽相似,只不過(guò)它有一個(gè)showPassword屬性。
3.textare標(biāo)簽:渲染一個(gè)HTML的textarea元素。textarea基本上就是支持多行輸入的input元素。
4.checkbox標(biāo)簽:渲染<input type="checkbox"/>元素,同樣是通過(guò)path屬性實(shí)現(xiàn)數(shù)據(jù)綁定,同時(shí)checkboxes渲染多個(gè)checkbox元素。
5.radiobutton標(biāo)簽渲染<input type="radio"/>元素,radiobuttons渲染多個(gè)radio元素。
6.select標(biāo)簽:渲染一個(gè)HTML的select元素,被渲染元素的選項(xiàng)可能來(lái)自賦予其items屬性的Collection、Map、Array,或者來(lái)自一個(gè)嵌套的option或options標(biāo)簽。
數(shù)據(jù)綁定范例
如上分別介紹了數(shù)據(jù)綁定的定義和優(yōu)勢(shì),以及一些表單標(biāo)簽,為了讓大家能進(jìn)一步了解上面的內(nèi)容,范例中實(shí)現(xiàn)了用戶(hù)類(lèi)屬性和JSP中表單的綁定,同時(shí)在JSP中分別展示了input、password、textarea、checkbox、select標(biāo)簽。
我們首先看一下User類(lèi),類(lèi)中包含User的屬性,以及對(duì)屬性字段的get和set方法:
public class User { private String userName; //用戶(hù)名 private String password; //密碼 private Integer sex; //性別 private boolean marriage; //是否結(jié)婚 private ArrayList<String> hobby; //興趣愛(ài)好 private ArrayList<String> contacts;//人脈 private String carrer; //職業(yè) private String houseRegister; //戶(hù)籍 private String remark; //個(gè)人描述 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類(lèi)中定義映射請(qǐng)求的方法,其中包括處理userInput請(qǐng)求的inputUser方法,以及userSave請(qǐng)求的addUser方法,其中在addUser方法中用到了重定向。其中通過(guò)@Autowired注釋在ProductController對(duì)象中主動(dòng)注入U(xiǎn)serService對(duì)象,實(shí)現(xiàn)對(duì)user對(duì)象的保存和查詢(xún)等操作;通過(guò)model的addAttribute方法將User類(lèi)對(duì)象、HashMap類(lèi)型的hobbys對(duì)象、String[]類(lèi)型的carrers對(duì)象傳遞給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, "臺(tái)球"); hobbys.put(4, "游泳"); model.addAttribute("user", new User()); model.addAttribute("hobbys", hobbys); model.addAttribute("carrers",new String[]{"教師","學(xué)生","醫(yī)生","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"; } }
同時(shí),為了避免中文亂碼的問(wèn)題,需要在web.xml文件中增加編碼過(guò)濾器,同時(shí)JSP頁(yè)面編碼設(shè)置為UTF-8,form表單的提交方式必須為post,我們先看web.xml文件的配置信息:
<?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類(lèi)型的hobbys綁定到了checkboxes上,將String[]類(lèi)型的carrer綁定到了select上,實(shí)現(xiàn)了通過(guò)option標(biāo)簽對(duì)select添加選項(xiàng),同時(shí)method方法需指定為post來(lái)避免中文亂碼的問(wèn)題。
<%@ 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>用戶(hù)名:</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>愛(ài)好:</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>職業(yè):</label> <form:select path="carrer"> <option/>請(qǐng)選擇職業(yè) <form:options items="${carrers }"/> </form:select> </p> <p> <label>戶(hù)籍:</label> <form:select path="houseRegister"> <option>請(qǐng)選擇戶(hù)籍</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>個(gè)人描述:</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文件實(shí)現(xiàn)對(duì)保存的user信息的遍歷展示。
<%@ 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>用戶(hù)名</th> <th>密碼</th> <th>性別</th> <th>婚姻</th> <th>興趣愛(ài)好</th> <th>人脈</th> <th>職業(yè)</th> <th>戶(hù)籍</th> <th>個(gè)人描述</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>
因?yàn)樵摴こ淌窃谏弦黄こ讨性黾拥?,因此其他的配置文件與上一篇工程中相同,這里不再做過(guò)多的贅述,希望讀者見(jiàn)諒。
運(yùn)行該程序在瀏覽器中輸入http://localhost:8081/SpringMVC/userInput可以看到左圖,填寫(xiě)表單完成,點(diǎn)擊Add User按鈕,即可看到右圖的輸出信息,不知道讀者是否發(fā)現(xiàn)輸出信息中存在問(wèn)題,興趣愛(ài)好為[1],戶(hù)籍也為1,輸出的為表單中選擇的索引位置,還有好像保單中忘了指定User的性別了,導(dǎo)致輸入性別列為空。這些問(wèn)題是由于本文的疏忽造成的,有興趣的讀者可以對(duì)這篇博客做更加完善的改正。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
spring boot實(shí)戰(zhàn)教程之shiro session過(guò)期時(shí)間詳解
這篇文章主要給大家介紹了關(guān)于spring boot實(shí)戰(zhàn)教程之shiro session過(guò)期時(shí)間的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起看看吧。2017-10-10Java8之lambda最佳實(shí)踐_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
在8 里面Lambda是最火的主題,不僅僅是因?yàn)檎Z(yǔ)法的改變,更重要的是帶來(lái)了函數(shù)式編程的思想,我覺(jué)得優(yōu)秀的程序員,有必要學(xué)習(xí)一下函數(shù)式編程的思想以開(kāi)闊思路2017-06-06帶你了解Java數(shù)據(jù)結(jié)構(gòu)和算法之鏈表
這篇文章主要為大家介紹了Java數(shù)據(jù)結(jié)構(gòu)和算法之鏈表 ,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助2022-01-01zuul轉(zhuǎn)發(fā)后服務(wù)取不到請(qǐng)求路徑的解決
這篇文章主要介紹了zuul轉(zhuǎn)發(fā)后服務(wù)取不到請(qǐng)求路徑的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Java創(chuàng)建型設(shè)計(jì)模式之單例模式
Java單例模式是一種設(shè)計(jì)模式,它確保一個(gè)類(lèi)只有一個(gè)實(shí)例,并提供一個(gè)全局訪問(wèn)點(diǎn)??梢允褂枚喾N方式實(shí)現(xiàn)單例模式,如餓漢式、懶漢式、雙重檢查鎖定、靜態(tài)內(nèi)部類(lèi)、枚舉等,每種方式都有其優(yōu)缺點(diǎn),需要根據(jù)具體情況選擇使用2023-05-05java 中用split分割字符串,最后的空格等不被拆分的方法
下面小編就為大家?guī)?lái)一篇java 中用split分割字符串,最后的空格等不被拆分的方法。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-02-02