简体   繁体   中英

Getting 415 Unsupported Media Type Error when trying to return a view from a spring controller using an Ajax Request

I have two controller methods

@RequestMapping(value = "/link", method = RequestMethod.GET) 
public ModelAndView link(HttpServletRequest httpRequest, @RequestParam(value="name", required=false) String name, @RequestParam(value="id", required=false) String id, @RequestParam(value="type") String type) {

    ModelAndView mav=new ModelAndView("ViewPage");

    SearchRequest request = new SearchRequest();
    request.setName(name);
    request.setId(id);
    request.setType(type);

    mav.addObject("Request", request);

}

@RequestMapping(value="/find", headers="Accept=/", method=RequestMethod.POST) 
public @ResponseBody List find(HttpServletRequest httpRequest, @RequestBody SearchRequest searchRequest) {

}

From the 1st controller method link, the control will be passed to ViewPage.jsp, we will pass a ModelView Object to ViewPage.jsp. And the control should again go to find method.

$(document).ready(function(){


    var myJSON  = {name:"test", id:"test", type:"test"}; 
    myJSON = JSON.stringify(myJSON);


    $.ajax({
            type: "POST",
            url: "../find",         
            dataType:'JSON',
            data: myJSON,
            cache: false,
            success: function(data){

            if(data!=""){

            }
            )}
    }

I am getting below error

"NetworkError: 415 Unsupported Media Type - localhost:8080/myreport/find"

In your Spring XML config, you need to specify the media types that are supported like so...

<beans:property name="mediaTypes">
     <beans:map>
         <beans:entry key="html" value="text/html" />
         <beans:entry key="json" value="application/json" />
     </beans:map>
</beans:property>

In order to get JSON working in your Spring MVC application the first thing you need to do is to add these dependencies:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
        <version>2.1.2</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.1.2</version>
        <scope>compile</scope>
    </dependency>

These dependencies are needed for Spring to managed JSON requests and responses.

Next thing is to define media types by registering ContentNegotiationManagerFactoryBean :

<bean id="contentNegotiationManager" 

class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <property name="favorPathExtension" value="false"/>
        <property name="favorParameter" value="true"/>
        <property name="mediaTypes">
            <value>
                json=application/json
                xml=application/xml
            </value>
        </property>
    </bean>

Also you have to define this negotiation manager in your mvc:annotation-driven tag's attribute content-negotiation-manager :

<mvc:annotation-driven content-negotiation-manager="contentNegotiationManager">
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper" ref="jsonObjectMapper"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

And create your JSON object mapper or use default. I prefer creating my own so that I can managed the configuration I need. For eg:

public class JsonObjectMapper extends ObjectMapper {

    public JsonObjectMapper() {
        super();
        this.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
        this.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
        this.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }

}

Declare it in Spring context:

<bean id="jsonObjectMapper" class="somepackage.JsonObjectMapper"/>

And then your javascript should look something like this:

$(document).ready(function(){

    var obj = {};
    obj.name = "test";
    obj.id = "test";
    obj.type = "test";
    var request = {};
    request.SearchRequest = obj;

    $.ajax({
        url: "${pageContext.servletContext.contextPath}/find",
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify(request),
        contentType: 'application/json'
    }).success(
        function (data) {
            //do something with response
        });
});

This should work if I haven't forgotten something else. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM