HTTP Status 415 - Post Json data to Spring MVC 4 u

2019-08-18 23:59发布

问题:

I am trying to Post data from ajax to Spring Controller but not able to Bind the data to the @ModelAttribute.I am using Spring version 4.3.3. I have been trying different methods, which ended up in Errors 400,405,406,415.I have given the codes below.Please do help as i stuck up with this.

Spring Controller

@ResponseBody 
@RequestMapping(value="{urls}/design", method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public String getDesign(@PathVariable("urls") String urls, @ModelAttribute JsonExample jsonExample ){
    System.out.println(jsonExample);
    return jsonExample.getName();
}

Ajax Post

var url = $("#crumblink").attr("href");
var token = $('#csrfToken').val();
var header = $('#csrfHeader').val();
var data = {name:"Abc"};
            $.ajax({                
                type : 'POST',
                contentType : "application/json",
                url : url + '/design',
                data: JSON.stringify(data),
                dataType : 'json',              
                beforeSend: function(xhr) { 
                    xhr.setRequestHeader(header, token); 
                }, 
                success : function(data) {
                    console.log("SUCCESS: ", data);
                },
                error : function(e) {
                    console.log("ERROR: ", e);
                }
            });

JsonExample Model Class

public class JsonExample {  
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "JsonExample [name=" + name + "]";
    }

}

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>******</groupId>
    <artifactId>***</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j13</artifactId>
            <version>1.0.1</version>
        </dependency>
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.1.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.3.0.Final</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>   
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.8.4</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.8.4</version>
        </dependency>

        <!-- Spring Security -->
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-taglibs</artifactId>
            <version>4.1.3.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>5.2.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.4.1209</version>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf</artifactId>
            <version>3.0.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>3.0-alpha-1</version>
        </dependency>
    </dependencies>
    <build>
        <finalName>dcs</finalName>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.6.0</version>
                    <configuration>
                        <source>1.8</source>
                        <target>1.8</target>
                    </configuration>
                </plugin>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.0.0</version>
                    <configuration>
                        <warSourceDirectory>src/main/webapp</warSourceDirectory>
                        <warName>dcs</warName>
                        <failOnMissingWebXml>false</failOnMissingWebXml>
                    </configuration>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

And when I submit the details all I get is

XML Parsing Error: no element found Location: moz-nullprincipal:{2269913a-adbb-43e8-bf5a-d2d9586f35f7} Line Number 1, Column 1:

^

because the data I sent does not bind with the @ModelAttribute specified in the controller.

回答1:

As your incoming data are in JSON format, you can't use @ModelAttribute for binding to a Java object. You have to convert these data before binding them to your model. Spring offers a simple way to do that, using @RequestBodyannotation.

@RequestBody uses implicitly a message converter to convert your data, Spring autoconfigures this message converter for you if you have JSON data-bind jars in your classpath.