带有嵌套参数的Ajax请求,在函数中使用@requestBody获得415错误

时间:2014-03-31 13:51:19

标签: jquery ajax java-ee spring-mvc

我的应用中存在一个问题:我将为后台提供嵌套参数,并显示该参数已放入HTTP请求的TextView部分。我想使用@RequestBody来获取参数,但是一旦我在参数前面输入@RequestBody注释,我将得到 415 错误〜。

JS

$.ajax({
  url:"maintenance/clientSystem/updatePriceHierarchy.html",
  data: {"post":"515", "person":{"personId":"162"}},
  dataType:"json",
  type:"POST",
  contentType: "application/json"
}).done(function(data){
  console.log("finish");
});

控制器

@RequestMapping("client/updatePerson")
  public final void updatePerson(HttpServletResponse response, Person bean) throws Exception {
    System.out.println(bean.getPersonId());
  }

Spring MVC配置

<!-- for local resources -->
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/js/**" location="/js/"/>   
<mvc:resources mapping="/images/**" location="/images/"/>   
<mvc:resources mapping="/images/deskTopIcon/**" location="/images/deskTopIcon/"/>
<mvc:resources mapping="/images/deskTopImg/**" location="/images/deskTopImg/"/>
<!-- scan package -->
<context:component-scan base-package="com.jesse.controller" />

<!-- add annotation driver -->
<mvc:annotation-driven />   
<!-- define prefix and suffix for view -->
<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    <property name="prefix" value="/pages/" /> <property name="suffix"
    value=".jsp" /> 
</bean>

<bean class ="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
   <property name= "messageConverters" >
         <list>
              <ref bean= "stringHttpMessageConverter" />
              <ref bean="jacksonMessageConverter" />
              <ref bean="jsonHttpMessageConverter" />
          </list>
    </property>
</bean>

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
<bean id = "stringHttpMessageConverter" class = "org.springframework.http.converter.StringHttpMessageConverter" />

<bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="1000000"/>
</bean>

<bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
    <property name="supportedMediaTypes">
        <list>
            <value>application/json;charset=UTF-8</value>
        </list>
    </property>
</bean>

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

有一些错误:

  • 您的控制器updatePerson()映射网址为client/updatePerson,您向maintenance/clientSystem/updatePriceHierarchy.html发送了AJAX请求

  • 您的AJAX请求是POST类型,您还没有提到控制器中的方法类型。

  • 您使用@RequestBody提到了问题,但我无法在您的控制器方法中看到。

纠正所有这些,然后来:

  

在函数

中使用@RequestBody获得415错误

HTTP 415 错误表示不支持的媒体类型:服务器拒绝为请求提供服务,因为请求的实体采用的格式不受请求的资源支持要求的方法。

如何摆脱415错误是: 指定正确的Content-TypeAccept请求标头。像:

$.ajax({
     type: "POST",
     url: "client/updatePerson",
     data: JSON.stringify(jsonStr),
     async: false,
     cache: false,
     processData:false,
     beforeSend: function(xhr) {
        xhr.setRequestHeader("Accept", "application/json"); //Accept request header specified
        xhr.setRequestHeader("Content-Type", "application/json"); //Content-Type request header specified
     },
     success: function(response){
        alert('Success: '+response.name);
     },
     error: function(jqXHR, textStatus, errorThrown) {
        alert(textStatus+' : '+ errorThrown);
     }
});

注意: jsonStr在AJAX数据中指定的内容,该字符串应该是控制器方法中的类的json表示格式,然后只有spring会将其转换回来。 / p>

例如,您的Person课程将如下所示:

class Person {
    private Long pid;
    private String name;
    private Person person;

    public Person(){} //Default constructor is needed

    //getters and setters
}

然后,jsonStr将如下所示:

var jsonStr = {"pid": 515, "name": "Jeese"};

用于嵌套人:

var jsonStr = {"pid": 515, "name": "Jeese", "person" : {"pid": 516, "name": "Jeese sub"}};

然后,在Controller中,方法将如下所示:

@Controller
@RequestMapping("/client/updatePerson")
public class ClientController {

    private final Logger logger = LoggerFactory.getLogger(ClientController.class);

    @RequestMapping(method = RequestMethod.POST,
            produces={MediaType.APPLICATION_JSON_VALUE},
            consumes={MediaType.APPLICATION_JSON_VALUE})
        public @ResponseBody Person updatePerson(@RequestBody Person bean) throws Exception {
        logger.debug("updatePerson() invoked..");
            //do your works here with person..
            logger.debug(bean.toString());
            logger.debug("Sub person: "+bean.getPerson().toString());
            return bean;
        }
}
CLASSPATH中应该有

jackson-mapper-asl jar。

<小时/> 另见:

HTTP Error codes

Spring 3.1.X RequestMapping new features where no need to register RequestMappingHandlerAdapter

RequestMapping