spring mvc ajax form提交报请求因 HTTP 状态 415 失败: Unsu...

   之前用ajax异步GET方式提交数据

$.ajax({
      type: "GET",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      url: "<%=request.getContextPath()%>/test.html",
      data:{username:"zsd"},
      success: function(text){
       alert(text.username)
      },
      error: function(err) {
                           alert("err");
                       }
     });

Controller 中-------------------

@RequestMapping(value = "/test.html", method = RequestMethod.GET)
 @ResponseBody
 public  User getShopInJSON(User   user ) {

  System.out.println("--------------:"+user.getUsername());
  User shop = new User();
  shop.setId(2);
  shop.setUsername("haha");
  shop.setPassword("zhoushunde");
  shop.setNickname("zxx");
  return shop;

 }
以上以通过;但当用jquery form 提交时就报415错了,

最后换成

public  User add(HttpServletRequest request,
	        HttpServletResponse response ) {
		
		System.out.println("--------------:"+request.getParameter("username"));
		User shop = new User();
		shop.setId(2);
		shop.setUsername("haha");
		shop.setPassword("zhoushunde");
		shop.setNickname("zxx");
		return shop;
}
或者是public  User add(@RequestParam(value = "username", required = true)String  username) {这种也可以通过 public  User add(@RequestParam String  username) {}

 form是使用的是post的方式提交 ,以下对于post方式的处理

	var obj={};
		obj.username="zsd";
		var param = JSON.stringify(obj);
		alert(param);
                $.ajax({
		type: "POST",
		contentType: "application/json; charset=utf-8",
		url: "<%=request.getContextPath()%>/test.html",
		data:param,//若这里改成data:{"username":"zsd"}请求会报400 dataType: "json",
		 success: function(text){
		 alert(text.username)
		 },
		 error: function(err) {
			alert("err"); } 
					}); 

 Controller中----------

 

	@RequestMapping(value = "/test.html", method = RequestMethod.POST)
	@ResponseBody
	public  User getShopInJSON(@RequestBody User user) {

		System.out.println("--------------:"+user.getUsername());
		User shop = new User();
		shop.setId(2);
		shop.setUsername("haha");
		shop.setPassword("zhoushunde");
		shop.setNickname("zxx");
		return shop;

	}


你可能感兴趣的:(spring,spring,Ajax,Ajax,mvc,mvc,form,post,状态415,form提交报请求因HTTP)