angular.js - ApringMVC接收angular的post请求,参数为null或者直接400,求破?
我想大声告诉你
我想大声告诉你 2017-05-15 17:01:12
0
1
568

这两天被这个东西搞死,最可恨的是,有些项目没事,有些项目有事,而我却不知道为什这样。刚学一个星期。

是这样地,下面有两个方法,前一个呢,接收的就是json,没事。

后一个呢,接受的是text,然后直接400,如果改成@requestBody呢,就是null。

/**
     * 验证注册名
     **/

    @ResponseBody
    @RequestMapping(value = "validateName", method = RequestMethod.POST)
    public String userNameValidate(@RequestParam("name") String name) {

        if (userServive.checkRegisterName(name)) {
            return "1";
        } else {
            return "0";
        }
    }

    /**
     * 保存注册信息
     **/
    @ResponseBody
    @RequestMapping(value = "/saveNewUser", method = RequestMethod.POST, consumes = "application/x-www-form-urlencoded")
    public String saveRegisterInfo(@RequestParam("user") User user) {

        System.out.println(user);

        //        User u = userServive.saveRegisterUser(user);
        if (user != null) {
            return "1";

        } else {

            return "0";
        }
    }

然后,你看看这两者的请求头和响应头的区别:

前一个方法的:Content-Type都对应着呢,没事。


Response Headers
view source
Content-Length:1
Content-Type:application/json;charset=UTF-8
Date:Mon, 25 Apr 2016 13:51:18 GMT
Proxy-Connection:keep-alive
Server:Apache-Coyote/1.1


Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, lzma
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Content-Length:11
Content-Type:application/x-www-form-urlencoded

但是后一个就不对应了:就出事了。


Response Headers
view source
Connection:close
Content-Language:en
Content-Length:1105

Content-Type:text/html;charset=utf-8

Date:Mon, 25 Apr 2016 14:10:17 GMT
Proxy-Connection:keep-alive
Server:Apache-Coyote/1.1


Request Headers
view source
Accept:application/json, text/plain, */*
Accept-Encoding:gzip, deflate, lzma
Accept-Language:zh-CN,zh;q=0.8
Connection:keep-alive
Content-Length:50

Content-Type:application/x-www-form-urlencoded

所以,我上面的第二个方法,就加个consumer或者production,甚至header都试过了,还是改不了那个:

Content-Type:text/html;charset=utf-8

还是错错错错错错。我加了jackson的三个包的呀

怎么回事??

最可恨的是,前些日子,同样的方法,用得好好地,换一个马甲,就不行了。哎

我想大声告诉你
我想大声告诉你

reply all(1)
给我你的怀抱

The request of angular post will not serialize the data, you need to modify $httpProvider

$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
$httpProvider.defaults.transformRequest = function(obj){
    var str = [];
    for(var p in obj) {
        str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
    }
    return str.join("&");
};
$httpProvider.defaults.headers.post = {
    'Content-Type': 'application/x-www-form-urlencoded'
};
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template