java 在 Spring 控制器上 $.ajax POST 后收到错误请求错误 (400)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14630139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:53:46  来源:igfitidea点击:

Receiving a Bad Request Error (400) after $.ajax POST on Spring Controller

javajqueryajaxspringrequest-mapping

提问by Abderrazak BOUADMA

Hello StackOverFlow(s)

你好 StackOverFlow

I'm running with this issue since more than 2 hours now It's simple

我从 2 个多小时以来一直在处理这个问题 很简单

I'm trying to send a JSON object to a Spring Controller by using a $.ajax POST call

我正在尝试使用 $.ajax POST 调用将 JSON 对象发送到 Spring Controller

I'm using AngularJS but that point is okey

我正在使用 AngularJS,但这一点很重要

here's the code of both server and client and the spring configuration

这是服务器和客户端的代码以及spring配置

Thank's in advance

提前致谢

JQuery :

查询:

    $scope.push = function() {
    $.ajax({
        type: "PUT",
        url:"rest/todo/greeting/",
        data : {id:"1",title:"ajax",description:"ajax"},
        dataType: "json",
        contentType : "application/json",
        success : function(data) {
            $log.info(data)
        }
    })
}

Spring Controller :

弹簧控制器:

@Controller
@RequestMapping("/todo")
public class TodoController {
@RequestMapping(value = "/greeting", method = RequestMethod.PUT,consumes="application/json",produces="text/html")
public @ResponseBody String push(@RequestBody Todo todo) {
    System.out.println(todo.getTitle());
    return "test";
}

}

}

Spring Configuration :

弹簧配置:

<mvc:annotation-driven />
<context:component-scan base-package="org.lab.todo.controller" />
<bean id="defaultViews" class="org.springframework.web.servlet.view.json.MappingHymanson2JsonView" />

web.xml :

网页.xml :

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

<!--
    Spring WEBMVC/REST Controllers
-->
<servlet>
    <servlet-name>todo-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>todo-dispatcher</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>

Ajax Call Update :

Ajax 调用更新:

    $scope.push = function() {
    var jsonString = {id:"1",title:"ajax",description:"ajax"};
    var Todo = function(){}
    Todo.id = "id";
    Todo.title = "ajax";
    Todo.description = "ajax";
    $.post("rest/todo/greeting",JSON.stringify(Todo),function(response){console.log(response)},'json');
}

Fiddle Raw Request Header :

小提琴原始请求标头:

POST http://localhost:8080/todo-rest/rest/todo/greeting HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 0
Accept: application/json, text/javascript, */*; q=0.01
Origin: http://localhost:8080
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko)     Chrome/24.0.1312.56 Safari/537.17
Referer: http://localhost:8080/todo-rest/
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8,fr;q=0.6
Accept-Charset: UTF-8,*;q=0.5

Fiddle Response Header

小提琴响应头

HTTP/1.1 415 Unsupported Media Type
Server: Apache-Coyote/1.1
Content-Type: text/html;charset=utf-8
Content-Length: 1048
Date: Thu, 31 Jan 2013 17:11:40 GMT

回答by Abderrazak BOUADMA

Here's the answer

这是答案

It's simply a matter of properly writing the JSON string

这只是正确编写 JSON 字符串的问题

instead of

代替

var jsonString = {id:"1",title:"ajax",description:"ajax"};

I wrote it like this

我是这样写的

var jsonString = '{"id":"1","title":"ajax","description":"ajax"}';

what is still weird is that JSON.stringify(MyObject) seems not to work in my case !!

仍然奇怪的是 JSON.stringify(MyObject) 在我的情况下似乎不起作用!

回答by Sotirios Delimanolis

If you're getting a 400 status code, it can only be for the following reason (from W3):

如果您收到 400 状态代码,则只能出于以下原因(来自W3):

10.4.1 400 Bad Request

The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.

10.4.1 400 错误请求

由于语法格式错误,服务器无法理解该请求。客户端不应该在没有修改的情况下重复请求。

With Spring, this either means that the ajax request is wrong (see my comment about the data JSON string) or it can't parse and translate the JSON String in the request body to your command object Todo. So Spring has a method it can call, your push()method, but it doesn't have the parameter your are looking for to pass to it, so it throws a 400 Bad Request.

对于 Spring,这要么意味着 ajax 请求是错误的(请参阅我对数据 JSON 字符串的评论),要么它无法解析请求正文中的 JSON 字符串并将其转换为您的命令对象Todo。所以 Spring 有一个可以调用的push()方法,你的方法,但它没有你正在寻找传递给它的参数,所以它会抛出一个 400 Bad Request。

415 Unsupported Media Typemeans that Spring cannot find a method to consume what you are sending. Your push()Spring method consumes="application/json"but your request isn't using that content-type.

415 Unsupported Media Type意味着 Spring 找不到使用您发送的内容的方法。您的push()Spring 方法,consumes="application/json"但您的请求未使用该内容类型。

回答by Kurt Du Bois

Could you post your web.xml? Since you're not defining a suffix for your request and place a slash in the end, you're doing a request to the index.jsp of that directory.

你能发布你的 web.xml 吗?由于您没有为请求定义后缀并在末尾放置一个斜杠,因此您正在向该目录的 index.jsp 发出请求。