初見(jiàn)SpringMVC之?dāng)?shù)據(jù)綁定
數(shù)據(jù)綁定的內(nèi)容非常通俗易懂温技,后臺(tái)受理網(wǎng)絡(luò)請(qǐng)求的方法獲取http請(qǐng)求參數(shù)的過(guò)程就是數(shù)據(jù)綁定。Spring提供了多種數(shù)據(jù)綁定的方法:
-
綁定默認(rèn)數(shù)據(jù)類型:
SpringMVC中常用的默認(rèn)數(shù)據(jù)類型包括入愧,HttpServletRequest贬堵,HttpServletResponse划纽,HttpSession拗窃。下面通過(guò)一個(gè)例子介紹瞎领,如何通過(guò)默認(rèn)數(shù)據(jù)類型綁定泌辫,獲取請(qǐng)求參數(shù)。
導(dǎo)入SpringMVC相關(guān)包九默,在web.xml中配置DsipatcherServlet
編寫Handler,處理具體的網(wǎng)絡(luò)請(qǐng)求震放,在此處是通過(guò)Controll注解標(biāo)識(shí)一個(gè)Handller,通過(guò)RequestMapping完成Handler和url之間的映射荤西。
@Controller
public class DataBinding {
@RequestMapping(value="/defaultDataBinding")
public String defaultDataBinding(HttpServletRequest request){
Stringid = request.getParameter("id");
System.out.println("id="+id);
return "success";
}
}
defaultDataBinding是受理以”/DefaultDataBinging”結(jié)尾的網(wǎng)絡(luò)請(qǐng)求的方法澜搅,通過(guò)默認(rèn)參數(shù)HttpServletRequest完成數(shù)據(jù)綁定伍俘,而http請(qǐng)求提交的參數(shù)均通過(guò) request.getParameter()方法獲取邪锌。
- Spring-cofig.xml文件配置
<?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 定義組件掃描器,指定需要掃描的包 -->
<context:component-scan base-package="com.bupt.controller"/>
<!-- 定義視圖解析器 -->
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--設(shè)置前綴 -->
<propertyname="prefix" value="/WEB-INF/" />
<!--設(shè)置后綴 -->
<propertyname="suffix" value=".jsp" />
</bean>
</beans>
- 測(cè)試結(jié)果:
在瀏覽器輸入如下網(wǎng)址 http://localhost:8080/HelloSpringMV/defaultDataBinding?id=1
可以看見(jiàn)上述通過(guò)Get方式提交一個(gè)名為id的參數(shù)癌瘾,參數(shù)值為1觅丰。在控制臺(tái)可以看見(jiàn)如下輸出:
圖1.1默認(rèn)參數(shù)的數(shù)據(jù)綁定
-
綁定簡(jiǎn)單數(shù)據(jù)類型
簡(jiǎn)單數(shù)據(jù)類型是指java中的基本數(shù)據(jù)類型以及String類型,假如提交的參數(shù)僅僅只是一個(gè)id妨退,可以采用綁定簡(jiǎn)答數(shù)據(jù)類型的方法妇萄,而不用通過(guò)綁定request后再獲取id數(shù)據(jù)。在DataBinding類中添加如方法:
- 在Handler中添加方法
@RequestMapping(value="/SimpleDataBinding")
publicString simpleDataBinding(HttpServletRequestrequest,int id){
System.out.println("request中獲取id="+request.getParameter("id"));
System.out.println("id="+id);
return"success";
}
在上述代碼中咬荷,新增了一個(gè)參數(shù)int id冠句。id直接可以獲取http請(qǐng)求中對(duì)應(yīng)的id字段。
- 測(cè)試幸乒,在瀏覽器中輸入如下url:http://localhost:8080/HelloSpringMV/SimpleDataBinding?id=1
從測(cè)試結(jié)果中可以發(fā)現(xiàn)懦底,方法中id參數(shù)可以字節(jié)獲取http請(qǐng)求中攜帶的id字段,同時(shí)還可以綁定HttpServletRequest的方法獲取請(qǐng)求參數(shù)罕扎。這里需要特別注意的是,http請(qǐng)求中的字段名稱必須和方法中參數(shù)名稱保持一致。假如不一致是不能綁定參數(shù)的怒见。
-
綁定POJO數(shù)據(jù)類型
??當(dāng)http請(qǐng)求攜帶的參數(shù)很多的時(shí)候搂抒,采用綁定簡(jiǎn)單數(shù)據(jù)類型的方法就需要設(shè)置過(guò)多的方法形參,此時(shí)可以利用一個(gè)POJO對(duì)象充當(dāng)方法形參臀蛛,獲取http請(qǐng)求中的參數(shù)亲桦。下面通過(guò)一個(gè)驗(yàn)證用戶登錄的例子來(lái)介紹綁定POJO數(shù)據(jù)類型的方式。
??用戶登錄時(shí)候需要提交用戶名(userName)和密碼(password)給服務(wù)器去驗(yàn)證浊仆,此時(shí)如果采用綁定簡(jiǎn)單數(shù)據(jù)類型的方法時(shí)客峭,需要兩個(gè)形參來(lái)完成數(shù)據(jù)綁定。此時(shí)就可以采用綁定POJO類型的方法獲取請(qǐng)求參數(shù)
- 在服務(wù)器一端創(chuàng)建一個(gè)POJO類
public class User {
//POJO類的屬性名要和http請(qǐng)求的字段名保持一致
publicString userName;
publicString password;
publicStringgetUserName() {
return userName;
}
publicvoid setUserName(String userName){
this.userName= userName;
}
publicString getPassword() {
returnpassword;
}
publicvoid setPassword(String password){
this.password= password;
}
}
- 在Handler中添加接收請(qǐng)求的方法:
@RequestMapping("/POJODataBinding")
publicString POJODataBinding(User user){
System.out.println("username="+user.getUserName());
System.out.println("password="+user.getPassword());
return"success";
}
- 在WebConten目錄下氧卧,創(chuàng)建一個(gè)user.html文件桃笙,顯示一個(gè)簡(jiǎn)單的登錄頁(yè)面
<!DOCTYPEhtml>
<html>
<head>
<metacharset="UTF-8">
<title>helloSpringMVC</title>
</head>
<body>
<form action="http://localhost:8080/HelloSpringMV/POJODataBinding"
method="post">
用戶名<input type="text" name="userName"></input><br>
密碼<input type="password" name="password"></input><br>
<input type="submit"name="submit" value="登錄"></input><br>
</form>
</body>
</html>
- 在Springmvc-config.xml文件中添加一行配置:
<!--dispatcherServelet不攔截靜態(tài)資源-->
<mvc:default-servlet-handler/>
- 測(cè)試,在瀏覽器中訪問(wèn)url:http://localhost:8080/HelloSpringMV/user.html
圖3.1 登錄頁(yè)面
點(diǎn)擊提交后沙绝,觀察服務(wù)器控制臺(tái)輸出:
-
自定義數(shù)據(jù)綁定
??自定義數(shù)據(jù)綁定搏明,是一種比較冷門的數(shù)據(jù)綁定方法鼠锈,假設(shè)存在這樣一種情景:請(qǐng)求攜帶的參數(shù)類型為A,后臺(tái)接收方法的形參類型為B星著,比如http請(qǐng)求攜帶的參數(shù)是日期字符串”2017-11-20 4:15:30”,而后臺(tái)接收方法的形參類型是Date,在這樣一種參數(shù)不匹配的情況下购笆,就需要用到自定義數(shù)據(jù)綁定。
??完成自定義數(shù)據(jù)綁定虚循,最主要的工作就是設(shè)計(jì)一個(gè)類型轉(zhuǎn)化器同欠,通過(guò)日期轉(zhuǎn)換的例子介紹自定義數(shù)據(jù)綁定。
- 構(gòu)建一個(gè)數(shù)據(jù)類型轉(zhuǎn)換器横缔,創(chuàng)建一個(gè)名為DateConverter的類铺遂,繼承Converter接口。
第一個(gè)泛型參數(shù)代表待轉(zhuǎn)換類型茎刚,第二個(gè)泛型參數(shù)代表目標(biāo)轉(zhuǎn)換類型襟锐,所有的轉(zhuǎn)換工作均只在convert方法中完成。
public class DateConverter implements Converter<String,Date>{
privateString datePattern="yyyy-mm-dd HH:mm:ss";
@Override
publicDate convert(String source) {
// TODO Auto-generated method stub
SimpleDateFormat sdf = new SimpleDateFormat(datePattern);
try{
return sdf.parse(source);
} catch(ParseException e) {
// TODO Auto-generated catch block
throw newIllegalArgumentException("無(wú)效日期格式,請(qǐng)使用如下格式:"+datePattern);
}
}
}
- 在Spring-config.xml文件中配置類型轉(zhuǎn)換器
<pre name="code" class="html" style="box-sizing: border-box; margin: 0px 0px 24px; padding: 0px 16px; overflow-x: auto; background-color: rgb(240, 240, 240); font-family: Consolas, Inconsolata, Courier, monospace; font-size: 12px; line-height: 20px; color: rgb(0, 0, 0); font-style: normal; font-variant-ligatures: normal; font-variant-caps: normal; font-weight: 400; letter-spacing: normal; orphans: 2; text-align: justify; text-indent: 0px; text-transform: none; widows: 2; word-spacing: 0px; -webkit-text-stroke-width: 0px; text-decoration-style: initial; text-decoration-color: initial;"><?xml version="1.0" encoding="UTF-8"?>
<beansxmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 定義組件掃描器膛锭,指定需要掃描的包 -->
<context:component-scan base-package="com.bupt.controller" />
<!-- 配置注解驅(qū)動(dòng) -->
<!-- <mvc:annotation-driven />-->
<mvc:annotation-driven conversion-service="conversionService"/>
<!--dispatcherServelet不攔截靜態(tài)資源-->
<mvc:default-servlet-handler/>
<!-- 定義視圖解析器 -->
<bean id="viewResolver" class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--設(shè)置前綴 -->
<propertyname="prefix" value="/WEB-INF/" />
<!--設(shè)置后綴 -->
<propertyname="suffix" value=".jsp" />
</bean>
<!-- 自定義類型轉(zhuǎn)換器配置 -->
<bean id="conversionService"class=
"org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.bupt.converter.DateConverter"/>
</set>
</property>
</bean></pre>
- 在Handler中添加處理網(wǎng)絡(luò)請(qǐng)求的方法
@RequestMapping(value="/ConverterDateBinding")
publicString ConverterDateBinding(Date date){
System.out.println(date.toString());
return"success";
}
- 測(cè)試粮坞,在瀏覽器中輸入如下url http://localhost:8080/HelloSpringMV/ConverterDateBinding?date=2017-11-20%2017:13:02??? 服務(wù)端控制臺(tái)輸出結(jié)果:
圖4.1服務(wù)端輸出結(jié)果
-
綁定數(shù)組類型
??假如前端發(fā)送的Http請(qǐng)求攜帶了同名的多個(gè)參數(shù)時(shí),就會(huì)用到綁定數(shù)組類型的情況初狰,比如前端使用復(fù)選框來(lái)完成選定操作的情景莫杈。
- 在Handler中添加處理網(wǎng)絡(luò)請(qǐng)求的方法
@RequestMapping(value="/arrayDateBinding")
publicString arrayDateBinding(String[] users){
for(int i=0;i<users.length;i++){
System.out.println("刪除user="+users[i]);
}
return"success";
}
- 在WebConten下創(chuàng)建array.html文件
<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title>Inserttitle here</title>
</head>
<body>
<form action="http://localhost:8080/HelloSpringMV/arrayDateBinding"
method="POST">
<table width="20%"border=1>
<tr>
<td>選擇</td>
<td>用戶名稱</td>
</tr>
<tr>
<td> <input type="checkbox"name="users" value="SmartTu"></input></td>
<td>SmartTu</td>
</tr>
<td> <input type="checkbox"name="users" value="SmartTu1"></input></td>
<td>SmartTu1</td>
</tr>
<td> <input type="checkbox"name="users" value="SmartTu2"></input></td>
<td>SmartTu2</td>
</tr>
</table>
<input type="submit" value="提交">
</form>
</body>
</html>
- 測(cè)試
點(diǎn)擊提交按鈕看,觀察服務(wù)器控制臺(tái)輸出
Reference:
[1] Java企業(yè)級(jí)應(yīng)用開(kāi)發(fā)教程 2017.黑馬程序員編著
[2] csdn博客原文