Spring MVC 接受的請求參數

1. 概述

Spring MVC 容許以多種方式將客戶端的數據傳送到控制器的處理方法中:前端

  • 查詢參數(Query Parameter)
  • 表單參數(Form Parameter)
  • 路徑變量(Path Variable)

2. 詳解

2.1 處理查詢參數

查詢參數都是String類型的,但當綁定到方法參數時會轉換爲相應的類型java

在方法中使用 @RequestParam註解,同時可經過defaultValue屬性設置當參數不存在時的默認值,如ios

public List<Spittle> spittles( @RequestParam(value="max",defaultValue=MAX_LONG_AS_STRING) long max,@RequestParam(value="count",defaultValue="20") int count )
// 不設置默認值時
public List<Spittle> spittles( @RequestParam("max") long max,@RequestParam("count") int count )

2.2 處理路徑參數接受輸入

  1. @RequestMapping中添加佔位符(用{}括起來)表示變量部分,如 @RequestMapping(value="/{spittleId}"),這樣就可以處理針對「/spittles/123454」的請求。
  2. 在方法參數上添加@PathVariable("spittleId") 註解,如public String spittle(@PathVariable("spittleId") long spittleId, Model model)
  3. 若方法參數名與佔位符名稱相同(都是spittleId),則可去掉@PathVariable的 value 屬性:public String spittle(@PathVariable long spittleId, Model model)web

    此時若修改參數名,須要同步修改佔位符名稱ajax

2.3 處理表單

使用HTML的<form>標籤。spring

若是form所在視圖是經過return 視圖名的形式渲染的,那麼,form中能夠沒有action屬性。此時,其將提交到與展示是相同的URL路徑上。如,訪問「/register」獲得帶form的「/registerForm」視圖,則提交form時會提交到「/register」json

處理表單提交時,相應的方法參數可使用包含與請求參數同名屬性的對象(即對象屬性與form中的input的name同名。若Spitter對象有屬性username,則某個表單域中的name須要爲username)
若須要對參數進行校驗時,可以使用Spring對Java Validation API的支持。即對參數使用@Valid註解,並緊跟Errors參數,以便對錯誤進行處理。
具體的校驗規則在參數對象中設置,如數組

public class Spitter{
    @NotNull   //全部的註解位於 javax.validation.constraints 包中
    @Size(min=5,max=16)
    private String username;//非空,5-16個字符
}

則:spring-mvc

public String processRegistration(@Valid Spitter spitter, Errors errs)
{
   if(errs.hasErrors){
       return "registerForm";//若是校驗失敗,從新返回表單,避免重複提交
   }
}

3. 補充內容

此部分非《Spring 實戰》內容

3.1 Ajax/JSON 輸入

http://blog.csdn.net/oTengYue/article/details/51598277
請求的Content-Typeapplication/json,請求數據在request的body中

  • 不能使用String xxx形式
  • 不能使用@RequestParam

@RequestBody註釋進行參數傳遞

@RequestMapping(value = "buAuth/save1")
@ResponseBody
public String save1(@RequestBody BuAuth buAuth){
    return "SUCCESS";
}

  採用@RequestBody標註的參數,SpringMVC 框架底層可以自動完成JSON字符串轉對應的Bean並注入到方法參數中,主要是經過使用HandlerAdapter 配置的HttpMessageConverters來解析post data body,而後綁定到相應的bean上的。此時Ajax發送的data值必須爲Json字符串,若是Controller中須要映射到自定義Bean對象上上,則必須設置Ajax的contentType爲application/json(或application/xml)。這種方式完整舉例以下:

$.ajax({
    type: "POST",
    url: "$!{_index}/buAuth/save1",
    data:JSON.stringify(dataObj) ,//傳遞參數必須是Json字符串
    contentType: "application/json; charset=utf-8",//必須聲明contentType爲application/json,不然後臺使用@RequestBody標註的話沒法解析參數
    dataType: "json",
    success: function (response, info) {}
});
@RequestMapping(value = "buAuth/save1")
@ResponseBody
public String save1(@RequestBody BuAuth buAuth){
    return "SUCCESS";
}

注:(1)此時前端直接用$.post()直接請求會有問題,ContentType默認是application/x-www-form-urlencoded。須要使用$.ajaxSetup()標示下ContentType爲application/json(或application/xml)。

$.ajaxSetup({ContentType:" application/json"});

$.post("$!{_index}/buAuth/save",{buAuth:JSON.stringify(dataObj),menuIds:menu_ids},function(result){});

(2)可使用@ResponseBody傳遞數組,以下舉例(作爲整理直接引用其餘博客例子)

var saveDataAry=[];
var data1={"userName":"test","address":"gz"};
var data2={"userName":"ququ","address":"gr"};
saveDataAry.push(data1);
saveDataAry.push(data2);
$.ajax({
    type:"POST",
    url:"user/saveUser",
    dataType:"json",
    contentType:"application/json",
    data:JSON.stringify(saveData),
    success:function(data){ }
});
@RequestMapping(value = "saveUser", method = {RequestMethod.POST }}) 
@ResponseBody  
public void saveUser(@RequestBody List<User> users) { 
    userService.batchSave(users); 
}

(3)Controller中的同一個方法只能使用@ResponseBody標記一個參數。也便是說沒法直接經過該方法同時傳遞多個對象,不過能夠間接經過設置一箇中間pojo對象(設置不一樣的屬性)來達到傳遞多個對象的效果。舉例以下:

var buAuthPage = {
    buAuth :   data,
    menuInfo : {code:"100"}
};

$.ajax({
    type: "POST",
    url: "$!{_index}/buAuth/save5",
    data: JSON.stringify(buAuthPage),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){
    }
});
public class BuAuthPage {
    BuAuth buAuth;
    public BuAuth getBuAuth() {
        return buAuth;
    }
    public void setBuAuth(BuAuth buAuth) {
        this.buAuth = buAuth;
    }
    public MenuInfo getMenuInfo() {
        return menuInfo;
    }
    public void setMenuInfo(MenuInfo menuInfo) {
        this.menuInfo = menuInfo;
    }
}

@RequestMapping(value = "buAuth/save5")
@ResponseBody
public String save5(@RequestBody BuAuthPage buAuthPage){
    return "SUCCESS";
}

(4)Axios默認的請求數據類型就是application/json

3.2 multipart參數

3.3 接收 header 數據

http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-request-header/
有時候,須要接收並處理請求頭中的數據,此時使用@RequestHeader註解(Controller方法參數)

幾種形式:

  • @RequestHeader("User-Agent") String userAgent@RequestHeader("If-Modified-Since") Date date
  • @RequestHeader(value="User-Agent", defaultValue="foo") String userAgent
  • @RequestHeader HttpHeaders headers
  • @RequestHeader Map<String, String> header

也可使用HttpServletRequestrequest.getHeader("code")

相關文章
相關標籤/搜索