SpringMVC如何接收參數各種場景

表單提交

此處的表單時 -使用JSON.stringify()函數將數組轉換成json類型提交後臺,後臺使用@RequestBody User user接受處理

頁面js

//新增提交按鈕
$("#buildsubmit").click(function() {
   var param = $(".form").serializeJson();
   $.ajax({
    type: 'post',
    url: path + "/web/member/save.do",
    contentType: "application/json",
    dataType: 'json',
    data: JSON.stringify(param),
    success: function(data) {
     
    },
   });
  }
 });

後端代碼

@RequestMapping(value = "/save", method = RequestMethod.POST)
public GeneralResponse save(@RequestBody @Valid MemberInsertDetail member, BindingResult bindingResult)
   throws JsonProcessingException {
  if (bindingResult.hasErrors()) {
   throw new ErrParamException();
  }
  boolean flag = false;
  flag = memberService.save(member);
}

表單提交二

使用.serialize()方法 提交表單內容;

1、可以後臺使用 request.getParamter(“對應字段的name”)獲取參數;

2、也可以使用 Model mdel 的POJO接受。(name要一一對應起來)

  • 格式:var data = $(“#formID”).serialize();
  • 功能:將表單內容序列化成一個以&拼接的字符串,鍵值對的形式,name1=val1&name2=val2&,空格以%20替換。

頁面JS

function sub(){
 $.ajax({
  type:"post",
  url:"/restaurant/addEmployees.do",
  data:$("#form").serialize(),
  dataType :"json",
  success:function(data){
   if(!data.success){
  }
 }); 
}

頁面html代碼:

<form action="" id="staff_form">
<div class="addInfor">
<input type="" name="phone" id="phone" value="" placeholder="請輸入手機號"/>
<input type="" name="password" id="password" value="" placeholder="請輸入密碼"/>
<input type="" name="username" id="username" value="" placeholder="請輸入姓名"/>

<input name="checkbox" value="chief_store_member" type="checkbox" >
<label class="grey-font" >多店管理</label>
<input name="checkbox" value="branch_store_member" type="checkbox">
<label class="grey-font" >單店管理</label>
</div>
<button type="button" class="mui-btn orange-btn" οnclick="sub();">確認</button>
</form>

後臺代碼接收方式一

含有單個的checkbox參數接收

@RequestMapping("/addEmployees")
@ResponseBody
public Result<Integer> addEmployees(HttpServletRequest request) {
  String phone = request.getParameter("phone");
  String password = request.getParameter("password");
  String username = request.getParameter("username");
  身份單checkbox接收。如果是復選框多個checkbox,則用數組String[] 接收。
  String checkbox = request.getParameter("checkbox");
}

後臺代碼接收方式二

@RequestMapping(value="/addCustomer",method=RequestMethod.POST)
@ResponseBody
public LogisticsResult addCustomer(@Valid CustomerInfo customer,BindingResult result ){
        如果是復選框多個checkbox,則在pojo中 用與checkbox的name一樣的 數組接收。
        如: String[] checkbox;
}

接收List<String>集合參數:

1、頁面js代碼:

var idList = new Array();  
idList.push(“1”);   
idList.push(“2”);   
idList.push(“3”);  
var isBatch = false;  
$.ajax({  
    type: "POST",  
    url: "<%=path%>/catalog.do?fn=deleteCatalogSchemes",  
    dataType: 'json',  
    data: {"idList":idList,"isBatch":isBatch},  
    success: function(data){  
        …  
    },  
    error: function(res){  
        …  
    }  
});  

2、Controller方法:

@Controller  
@RequestMapping("/catalog.do")  
public class CatalogController {    
    @RequestMapping(params = "fn=deleteCatalogSchemes")  
    @ResponseBody  
    public AjaxJson deleteCatalogSchemes(@RequestParam("idList[]") List<String> idList,Boolean isBatch) { 
            …  
    }  
}  

接收List<User>、User[]集合參數:

1、User實體類:

public class User {  
        private String name;   
    private String pwd;  
    //省略getter/setter  
}

2、頁面js代碼:

var userList = new Array();  
userList.push({name: "李四",pwd: "123"});   
userList.push({name: "張三",pwd: "332"});   
$.ajax({  
    type: "POST",  
    url: "<%=path%>/catalog.do?fn=saveUsers",  
    data: JSON.stringify(userList),//將對象序列化成JSON字符串  
    dataType:"json",  
    contentType : 'application/json;charset=utf-8', //設置請求頭信息  
    success: function(data){  
        …  
    },  
    error: function(res){  
        …  
    }  
});  

3、Controller方法:

@Controller  
@RequestMapping("/catalog.do")  
public class CatalogController {    
    @RequestMapping(params = "fn=saveUsers")  
    @ResponseBody  
    public AjaxJson saveUsers(@RequestBody List<User> userList) {  
        …  
    }  
}  

如果想要接收User[]數組,隻需要把saveUsers的參數類型改為@RequestBody User[] userArray就行瞭。

接收List<Map<String,Object>>集合參數:

1、頁面js代碼(不需要User對象瞭):

var userList = new Array();  
userList.push({name: "李四",pwd: "123"});   
userList.push({name: "張三",pwd: "332"});   
$.ajax({  
    type: "POST",  
    url: "<%=path%>/catalog.do?fn=saveUsers",  
    data: JSON.stringify(userList),//將對象序列化成JSON字符串  
    dataType:"json",  
    contentType : 'application/json;charset=utf-8', //設置請求頭信息  
    success: function(data){  
        …  
    },  
    error: function(res){  
        …  
    }  
});  

2、Controller方法:

@Controller  
@RequestMapping("/catalog.do")  
public class CatalogController {  
  
    @RequestMapping(params = "fn=saveUsers")  
    @ResponseBody  
    public AjaxJson saveUsers(@RequestBody List<Map<String,Object>> listMap) {  
        …  
    }  
}  

接收User(bean裡面包含List)集合參數:

1、User實體類:

public class User {  
    private String name;   
    private String pwd;  
    private List<User> customers;//屬於用戶的客戶群  
    //省略getter/setter  
}  

2、頁面js代碼:

var customerArray = new Array();  
customerArray.push({name: "李四",pwd: "123"});   
customerArray.push({name: "張三",pwd: "332"});   
var user = {};  
user.name = "李剛";  
user.pwd = "888";  
user. customers = customerArray;  
$.ajax({  
    type: "POST",  
    url: "<%=path%>/catalog.do?fn=saveUsers",  
    data: JSON.stringify(user),//將對象序列化成JSON字符串  
    dataType:"json",  
    contentType : 'application/json;charset=utf-8', //設置請求頭信息  
    success: function(data){  
        …  
    },  
    error: function(res){  
        …  
    }  
});  

3、Controller方法:

@Controller  
@RequestMapping("/catalog.do")  
public class CatalogController {   
    @RequestMapping(params = "fn=saveUsers")  
    @ResponseBody  
    public AjaxJson saveUsers(@RequestBody User user) {  
        List<User> customers = user.getCustomers();  
        …  
    }  
}  

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: