1 接收普通参数
@RequestMapping("commonparams")
public ModelAndView commonParams(String roleName,String note){
System.out.println("roleName:" + roleName);
System.out.println("note:" + note);
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
如果参数过多的话可以封装成一个对象
@RequestMapping("commonparams1")
public ModelAndView commonParams1(Role role){
System.out.println("roleName:" + role.getRoleName());
System.out.println("note:" + role.getNote());
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("index");
return modelAndView;
}
2 使用@RequestParam注解获取参数
如果参数中参数名为role_name接收参数时用roleName,那么就需要用到@RequestParam了,否则将接收不到参数.
@RequestParam("role_name") String roleName\
3 使用url传递参数
@RequestMapping("/getRole/{id}")
public ModelAndView pathVariable(@PathVariable("id") Long id){
System.out.println("id:" + id);
return new ModelAndView();
}
4 接收json参数
$(document).ready(function(){
var data = {
roleName:'role',
note:'note',
pageParams:{
start:1,
limit:20
}
}
$.post({
url:"./params/findRoles.do",
//此处需要告知传递参数类型为JSON,不能缺少
contentType:"application/json",
data:JSON.stringify(data),
success:function(result){
}
});
});
后台接收
public ModelAndView findRoles(@RequestBody RoleParams roleParams){
...
}
5 接收列表数据
前端js
$(document).ready(function(){
var idList = [1,2,3];
$.post({
url:"./params/deleteRoles.do",
//将JSON转化为字符串传递
data:JSON.stringify(idList),
contentType:"application/json",
success:function(result){}
});
});
后端代码
public ModelAndView deleteRoles(@RequestBody List<Long> idList){
.....
}
接收复杂的列表数据
前端js
$(document).ready(function(){
var roleList = [{roleName:'rolename1',note:'note1'},{roleName:'rolename2',note:'note2'},{roleName:'rolename3',note:'note3'}];
$.post({
url:"./params/addRoles.do",
data:JSON.stringify(roleList),
contentType:"application/json",
success:function(result){
}
});
});
后端代码
public ModelAndView addRoles(@RequestBody List<Role> roleList){
}
6 接收表单序列化数据
前端代码
<form id="form">
<table>
<tr>
<td>角色名称</td>
<td><input id="roleName" name="roleName" value=""></td>
</tr>
<tr>
<td>备注</td>
<td><input id="note" name="note"></td>
</tr>
<tr><td></td>
<td><input id="commit" type="button" value="提交"></td></tr>
</table>
</form>
$(document).ready(function(){
$("#commit").click(function(){
vat str=$("form").serialize();
//提交表单
$.post({
url:"./params/commonParamsPojo2.do",
data:$("form").serialize(),
success:function(result){
}
});
});
});
后端代码
public ModelAndView addRoles(String roleName,String note){
}