SpringMVC學習系列(4) 之 數據綁定-1


在系列(3)中我們介紹了請求是如何映射到一個action上的,下一步當然是如何獲取到請求中的數據,這就引出了本篇所要講的內容—數據綁定。

首先看一下都有哪些綁定數據的注解:

1.@RequestParam,綁定單個請求數據,可以是URL中的數據,表單提交的數據或上傳的文件;
2.@PathVariable,綁定URL模板變量值;
3.@CookieValue,綁定Cookie數據;
4.@RequestHeader,綁定請求頭數據;
5.@ModelAttribute,綁定數據到Model;
6.@SessionAttributes,綁定數據到Session;
7.@RequestBody,用來處理Content-Type不是application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等;
8.@RequestPart,綁定“multipart/data”數據,並可以根據數據類型進項對象轉換;

下面我們來看如何使用:

1.@RequestParam:

為了驗證文件綁定我們需要先做以下工作:

a.把commons-fileupload-1.3.1.jar和commons-io-2.4.jar兩個jar包添加到我們項目。

b.配置我們項目中的springservlet-config.xml文件使之支持文件上傳,內容如下:

<!-- 支持上傳文件 -->  
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <!-- 設置上傳文件的最大尺寸為1MB -->  
    <property name="maxUploadSize">  
        <value>1048576</value>  
    </property>
    <property name="defaultEncoding"> 
        <value>UTF-8</value> 
    </property>
</bean>

其中maxUploadSize用於限制上傳文件的最大大小,也可以不做設置,這樣就代表上傳文件的大小木有限制。defaultEncoding用於設置上傳文件的編碼格式,用於解決上傳的文件中文名亂碼問題。

下面就看具體如何使用:

添加一個DataBindController,里面有2個paramBind的action分別對應get和post請求:

package com.demo.web.controllers;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/databind")
public class DataBindController {

    @RequestMapping(value="/parambind", method = {RequestMethod.GET})
    public ModelAndView paramBind(){
        
        ModelAndView modelAndView = new ModelAndView();  
        modelAndView.setViewName("parambind");  
        return modelAndView;
    }
    
    @RequestMapping(value="/parambind", method = {RequestMethod.POST})
    public ModelAndView paramBind(HttpServletRequest request, @RequestParam("urlParam") String urlParam, @RequestParam("formParam") String formParam, @RequestParam("formFile") MultipartFile formFile){
        
        //如果不用注解自動綁定,我們還可以像下面一樣手動獲取數據
         String urlParam1 = ServletRequestUtils.getStringParameter(request, "urlParam", null);
        String formParam1 = ServletRequestUtils.getStringParameter(request, "formParam", null);
        MultipartFile formFile1 = ((MultipartHttpServletRequest) request).getFile("formFile"); 
        
        ModelAndView modelAndView = new ModelAndView();  
        modelAndView.addObject("urlParam", urlParam);  
        modelAndView.addObject("formParam", formParam);  
        modelAndView.addObject("formFileName", formFile.getOriginalFilename());  
        
        modelAndView.addObject("urlParam1", urlParam1);  
        modelAndView.addObject("formParam1", formParam1);  
        modelAndView.addObject("formFileName1", formFile1.getOriginalFilename());  
        modelAndView.setViewName("parambindresult");  
        return modelAndView;
    }
        
}

在views文件夾中添加parambind.jsp和parambindresult.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form action="parambind?urlParam=AAA" method="post" enctype="multipart/form-data"> 
        <input type="text" name="formParam" /><br/> 
        <input type="file" name="formFile" /><br/>
        <input type="submit" value="Submit" />
    </form>  
</body>
</html>
<%@ 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    自動綁定數據:<br/><br/>
    ${urlParam}<br/>
    ${formParam}<br/>
    ${formFileName}<br/><br/><br/><br/>
    手動獲取數據:<br/><br/>
    ${urlParam1}<br/>
    ${formParam1}<br/>
    ${formFileName1}<br/>
</body>
</html>

運行項目,輸入內容,選擇上傳文件:

1

提交查看結果:

2

可以看到綁定的數據已經獲取到了。

上面我們演示了如何把數據綁定到單個變量,但在實際應用中我們通常需要獲取的是model對象,別擔心,我們不需要把數據綁定到一個個變量然后在對model賦值,只需要把model加入相應的action參數(這里不需要指定綁定數據的注解)Spring MVC會自動進行數據轉換並綁定到model對象上,一切就是這么簡單。測試如下:

添加一個AccountModel類作為測試的model:

package com.demo.web.models;

public class AccountModel {
    
    private String username;
    private String password;
    
    public void setUsername(String username){
        this.username=username;
    }
    public void setPassword(String password){
        this.password=password;
    }
    
    public String getUsername(){
        return this.username;
    }
    public String getPassword(){
        return this.password;
    }
}

在DataBindController里面添加2個modelAutoBind的action分別對應get和post請求:

@RequestMapping(value="/modelautobind", method = {RequestMethod.GET})
public String modelAutoBind(HttpServletRequest request, Model model){
    
    model.addAttribute("accountmodel", new AccountModel());
    return "modelautobind";
}

@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})
public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){
    
    model.addAttribute("accountmodel", accountModel);
    return "modelautobindresult";
}

在views文件夾中添加modelautobind.jsp和modelautobindresult.jsp 2個視圖用於提交數據和展示提交的數據:

modelautobind.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 prefix="form" uri="http://www.springframework.org/tags/form" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <form:form modelAttribute="accountmodel" method="post">     
        用戶名:<form:input path="username"/><br/>
        密 碼:<form:password path="password"/><br/>
        <input type="submit" value="Submit" />
    </form:form>  
</body>
</html>

modelautobindresult.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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    用戶名:${accountmodel.username}<br/>
    密 碼:${accountmodel.password}
</body>
</html>

運行測試:

3

用戶名 輸入AAA 密碼 輸入BBB,提交:

4

可以看到結果顯示正確,說明自動綁定成功。

注:

1.關於@RequestParam的參數,這是一個@RequestParam的完整寫法@RequestParam(value="username", required=true, defaultValue="AAA")。

value表示要綁定請求中參數的名字;

required表示請求中是否必須有這個參數,默認為true這是如果請求中沒有要綁定的參數則返回404;

defaultValue表示如果請求中指定的參數值為空時的默認值;

要綁定的參數如果是值類型必須要有值否則拋異常,如果是引用類型則默認為null(Boolean除外,默認為false);

 

2.在剛才添加的2個action中可以看到返回類型和以前的不一樣了由ModelAndView變成了String,這是由於Spring MVC 提供Model、ModelMap、Map讓我們可以直接添加渲染視圖需要的模型數據,在返回時直接指定對應視圖名稱就可以了。同時Map是繼承於ModelMap的,而Model和ModelMap是繼承於ExtendedModelMap的。

 

3.在剛才添加的視圖modelautobind.jsp中可以看到<form:form<form:input 等標簽,這是Spring MVC提供的表單標簽,借助於這些標簽我們可以很方便的把模型數據綁定到表單上面(當然你也可以選擇繼續使用原生的HTML表單標簽),要使用Spring MVC只要在視圖中添加引用 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>即可,關於Spring MVC表單標簽的具體內容會在以后的文章中作介紹。

 

代碼下載:http://pan.baidu.com/s/1pJyiS2Z

 

好了,寫到這里其實已經寫了數據綁定的多半部分內容了,數據綁定-1 內容就先寫到這里,后面的幾個數據綁定的注解會在 數據綁定-2 中介紹,明天還要上班,休息去~~~困了

 

 

注: 之前沒注意前11篇的示例代碼,不知道為什么當時打包上傳上去的是沒有.project項目文件的,導致下載后不能直接導入eclipse運行,虛擬機又 被我刪掉了,這些示例代碼也沒有備份,但是代碼文件還在的,所以可以新建一個Dynamic Web Project把對應的配置文件和controller還有view導入就可以了,給大家造成的不便說聲抱歉。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM