繁体   English   中英

尝试使用Ajax请求从Spring控制器返回视图时,出现415不支持的媒体类型错误

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

我有两种控制器方法

@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) {

}

从第一个控制器方法链接,控件将传递给ViewPage.jsp,我们将ModelView对象传递给ViewPage.jsp。 控件应再次查找方法。

$(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!=""){

            }
            )}
    }

我低于错误

“网络错误:415不支持的媒体类型-本地主机:8080 / myreport / find”

在您的Spring XML配置中,您需要指定受支持的媒体类型,如下所示:

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

为了使JSON在您的Spring MVC应用程序中工作,您需要做的第一件事是添加以下依赖项:

    <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>

Spring需要这些依赖关系来管理JSON请求和响应。

接下来的事情是通过注册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>

另外,您还必须在mvc:annotation-driven标签的属性content-negotiation-manager定义此协商管理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>

并创建您的JSON对象映射器或使用默认值。 我更喜欢创建自己的配置,以便可以管理所需的配置。 例如:

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);
    }

}

在Spring上下文中声明它:

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

然后您的JavaScript应该看起来像这样:

$(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
        });
});

如果我没有忘记别的东西,这应该可以工作。 希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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