Spring MVC无法获取ajax POST的参数和值

一、怎么会这个样子

很简单的一个想法,ajax以POST的方式提交一个表单,Spring MVC解析。然而一次次的打印null折磨了我整整一天……

最后的解决现在看来是很明显的问题,“只是当时已惘然”……

学海无涯!学海无涯!学海无涯!

 

二、简单的原罪

ajax提交的代码如下:

 1 <script type="text/javascript">
 2     $(document).ready(function() {
 3       $("#submit").click(function(e) {
 4         e.preventDefault();
 5         var obj = $(this);
 6         var name = $("input[name='name']").val();
 7         var phone = $("input[name='phone']").val();
 8         $.ajax({
 9           url : "userAsk",
10           type : "POST",
11           contentType : "application/json;charset=utf-8",
12           data : {name:name,phone:phone},
13           //dataType : "text",
14           success : function(result, status, req) {
15               $(".noticeInfo").css("display", "block");
16           },
17           error : function(req, status, reason) {
18             $(".noticeInfo").css("display", "block").text('Error:' + reason);
19           }
20         })
21         return false;
22       })
23     });
24   </script>

 

三、纠结的后台

顺便复习一下Spring MVC的取值方式:

1. 通过注解PathVariable获取url中的值。

1  @RequestMapping(value="user/{id}/{name}",method=RequestMethod.GET)
2  public String myController(@PathVariable String id,@PathVariable String name, ModelMap model) {
3      ……
4      return "ok";
5  }

2.通过注解RequestParam获取传递过来的值。

1 @RequestMapping(value = "/test", method = RequestMethod.POST) 
2 public String myTest(@RequestParam("name") String name,@RequestParam("phone") String phone, ModelMap model) { 
3     ……
4     return "ok";
5 }

3.通过源生的HttpServletRequest自己动手取值。

1 @RequestMapping(value="/test" method = RequestMethod.POST) 
2 public String get(HttpServletRequest request, HttpServletResponse response) { 
3     String name = request.getParameter("name")); 
4     return "ok"; 
5 }

4.通过注解ModelAttribute直接映射表单中的参数到POJO。

注:暂时没用过,一般这种情况我用JSON序列化。

 

上面的方法我各种尝试,一直无情的打印null。

 

四、怀疑后台有没有收到数据?

 1         BufferedReader br;
 2         try {
 3             br = req.getReader();
 4             String str, wholeStr = "";
 5             while((str = br.readLine()) != null){
 6             wholeStr += str;
 7             }
 8             System.out.println(wholeStr);
 9         } catch (IOException e) {
10             e.printStackTrace();
11         }

打印出来的字符串和前端发送的数据一模一样……

 

五、最后的真相……

我用了最原始的方法,重新写了一个一模一样的表单,这个表单不用ajax,而用form提交。后台能打印出数据了!

对比两个前端的http请求数据,修改了一下ajax提交的数据格式,解决了:

1 contentType : "application/x-www-form-urlencoded",

也就是说:收到ajax请求,Spring MVC根据“数据类型指示”,按照json格式解析收到的请求。

但是看起来name=lings&phone=13899999999这种以表单数据格式提交的字符串无法匹配json解析。

重新指示数据类型后,上面的取值方法都是可行的。

posted @ 2016-09-08 15:24  一沙世界  阅读(23039)  评论(0编辑  收藏  举报