本人转载自: http://blog.csdn.net/feicongcong/article/details/54705933
return "redirect:/icProject/index"; 重定向到请求
model.addAttribute("page", page);
return "icProject/index";跳转到页面
1.ajax提交,将数组封装成json,后台用List<Integer>接
2.form提交
方法一:
前台form
<form action="/sysUser/create" method="post"> <input name="roleId" > <input name="roleId" > <input name="roleId" > </form>
后台
public String create(Model model,@Valid SysUserPojo sysUserPojo, BindingResult bindingResult, final RedirectAttributes redirectAttributes,@RequestParam(value="roleId", required = false) List<Long> roleIds) { }方法二:
前台form
<form action="/sysUser/create" method="post"> <input name="menuIds[0]" > <input name="menuIds[1]" > <input name="menuIds[2]" > </form>
后台
@RequestMapping(value = "/create", method = RequestMethod.POST) public String create( @Valid SysRoleDto sysRoleDto, BindingResult bindingResult, final RedirectAttributes redirectAttributes) { }
public class SysRoleDto extends SysRolePojo { @NotNull private List<Long> menuIds; public SysRoleDto() { } public List<Long> getMenuIds() { return menuIds; } public void setMenuIds(List<Long> menuIds) { this.menuIds = menuIds; } }
方法三
@ResponseBody @RequestMapping(value = "/ajaxsortPriority") public ResultDo ajaxsortPriority(@RequestParam("ids[]") Long[] ids) { ResultDo resultDo=new ResultDo(); int size=cmsBannerService.sortPriority(ids); if(size==ids.length){ resultDo.setSuccess(true); }else{ resultDo.setSuccess(false); } return resultDo; }
var param=[]; $("#tb_order").find("td[name='id']").each(function(){ param.push($(this).text()); }) var ids={ids:param}; $.ajax({ cache: true, type: "GET", url: "/cmsBanner/ajaxsortPriority", dataType:"json", data:ids, async: false, success: function (data) {
方法4
@RequestMapping(value = "/cfgRepayRemind", method = RequestMethod.POST) @ResponseBody public ResultDo<?> cfgRepayRemind( @RequestBody List<SysDictPojo> sysDictPojos //@RequestBody 前台请求的数据格式必须为json ) { ResultDo<?> resultDo = ResultDo.build(); try { icProjectRepayService.cfgRepayRemind(sysDictPojos); } catch (Exception e) { resultDo.setSuccess(false); } return resultDo; }
function cfgRepayRemind(ele) { var url = $(ele).attr("value"); var params = []; $("#repayRemindMobile").find("ul").each(function () { var id = $(this).find("input[name='id']").eq(0).val(); var value = $(this).find("input[name='value']").eq(0).val(); params.push({id: id, value: value});//id,value 为java bean里的属性,名字一致 }) $.ajax({ cache: true, type: "POST", url: url, data: JSON.stringify(params),// 指定请求的数据格式为json,实际上传的是json字符串 contentType: 'application/json;charset=utf-8',//指定请求的数据格式为json,这样后台才能用@RequestBody 接受java bean dataType: "json", async: false, success: function (data) { if (data.success) { toastr.success("操作成功"); setTimeout(function () { location.reload(); }, 1000) } } }); }
public class SysDictPojo extends AbstractBasePojo { private Long id; private String key; private String value; private String description; }
PS
场景一
$.ajax({ type:"post", <span style="white-space:pre"> </span> data:{total:'100'}, dataType:'json', url:"http://127.0.0.1:8089/icProject/test", success:function () { } })
@RequestMapping(value = "/test", method = RequestMethod.POST) @ResponseBody public String test(@RequestParam("total") String total ) { return null; }
后台可以取到total=100,发现默认是以 application/x-www-form-urlencoded 格式提交请求数据的
场景二
function testpost1() { $.ajax({ type:"post", data:{total:'100',icProjectPojo:{totalAmount:10000}}, dataType:'json', url:"http://127.0.0.1:8089/icProject/test", success:function () { } }) }
@RequestMapping(value = "/test", method = RequestMethod.POST) @ResponseBody public String test(HttpServletRequest request, @RequestParam("total") String total, IcProjectPojo icProjectPojo ) { return null; }
后台接收时,IcProjectPojo这个bean里的totalAmount明显是就收不到数据的,如果有一个属性叫 icProjectPojo[totalAmount] ,那他会接受到数据
所以传对象要用@RequestBody (方法里只有一个,即必须是一整个对象)和
data:JSON.stringify(params),//此处也不用给对象取key,因为后台的方法里@RequestBody 只允许注解一个对象
contentType: "application/json",
不使用contentType: “application/json”则data可以是对象
使用contentType: “application/json”则data只能是json字符串
方法五:表单数据序列化,ajax提交
var params = $("#sysUserFrm").serialize(); var url = "/sysUser/settingSave" $.ajax({ cache: true, type: "POST", url: url, data: params, dataType: "json", async: false, success: function (data) {} })
@RequestMapping(value = "/settingSave", method = RequestMethod.POST) @ResponseBody public ResultDo<?> settingSave(SysUserPojo sysUserPojo) {}
这样sysUserPojo也能接收到Bean,其实这里的$("#sysUserFrm").serialize() 就相当于组装的 json对象 { }
ps:
var formData = new Object(); $("input").each(function () { if ($(this).val() == "") { return; } formData[$(this).attr("name")] = $(this).val(); });
总结:
get请求
一、url?key1=value1&key2=value2
二、form表单 (浏览器network里可看到实际上可是参数加url后面)
java:
<span style="color:#000000">@GetMapping("/logined") public String logined(@RequestParam(value="userName",required = false) String userName, EpSystemUserPo po, MyUeerPo userPo) {//不采用@RequestBody入参可有多个,可与@RequestParam混用 //前台传来userName参数,后台的userName,po中的userName属性,userPo中的userName属性都会接收到值 return "index"; }</span>
js
<form action="/backend/logined" method="GET" enctype=""> <div class="form-group"> <input name="userName" placeholder="用户名" > </div> <div class="form-group"> <input type="password" class="form-control" name="password" placeholder="密码" required=""> </div> <button type="submit" >登 录</button> </form>发起请求后,后台未响应时(比如下了断点),因为get请求实际就是url后加参数故没有content-type这个参数
后台响应后,响应了会有status
code
post请求
一、form表单 (同get的区别在于content-type)
后台controller入参同样可以 @RequestParam(value="userName",required = false) String userName,
EpSystemUserPo po, 这样混用
后台未响应时
二、ajax的post方式提交请求
1.不用@RequestBody
后台java
@PostMapping("/logined") public String logined( @RequestParam(value="userName",required = false) String userName, EpSystemUserPo po, MyUeerPo userPo ) {//不采用@RequestBody入参可有多个,可与@RequestParam混用 //前台传来userName参数,后台的userName,po中的userName属性,userPo中的userName属性都会接收到值 return "login"; }
前台js
function logined() { $.ajax({ type: "POST", url: "/backend/logined", data: $("#userFrm").serialize(), success: function (data) {} }) }
2.使用@RequestBody(实际上接受的是json的字符串)
@PostMapping("/logined") public String logined( // @RequestParam(value="userName",required = false) String userName, @RequestBody EpSystemUserPo epSystemUserPo // MyUeerPo userPo ) {//采用@RequestBody入参只有一个 return "login"; }
function logined() { $.ajax({ type: "POST", url: "/backend/logined", data:JSON.stringify({userName:"cater",password:"123456"}) ,//转成字符串 contentType: "application/json;charset=utf-8",//不使用contentType: “application/json”则data可以是对象,使用contentType: “application/json”则data只能是json字符串 success: function (data) {} }) }