搜尋

首頁  >  問答  >  主體

angular.js - ApringMVC接收angular的post請求,參數為null或直接400,求破?

這兩天被這東西搞死,最可恨的是,有些項目沒事,有些項目有事,而我卻不知道為什這樣。剛學一星期。

是這樣地,下面有兩個方法,前一個呢,接收的就是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的三個包的呀

怎麼回事? ?

最可恨的是,前些日子,同樣的方法,用得好好地,換一個馬甲,就不行了。哎

我想大声告诉你我想大声告诉你2745 天前569

全部回覆(1)我來回復

  • 给我你的怀抱

    给我你的怀抱2017-05-15 17:03:12

    angular post的請求是不會把資料序列化的,你需要修改一下$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'
    };

    回覆
    0
  • 取消回覆