2017-10-08 48 views
1

这里是我的Ajax请求Spring MVC @RequestBody不能使用jquery ajax?

var dataModel = {name1:"value1", name2:"value2"}; 

$.ajax({ 
       url: "/testURL", 
       type: "POST", 
       async: false, 
       contentType: "application/json", 
       data: dataModel, 
       success: function(response) { 

       } 

    }) 

这是我从Spring的XML相关的片断

<annotation-driven> 
     <!-- Message converters are added to use custom object mapper in MappingJackson2HttpMessageConverter. 
      StringHttpMessageConverter is required to avoid MappingJackson2HttpMessageConverter from converting a string into json. 
     --> 
     <message-converters> 
      <beans:bean 
       class="org.springframework.http.converter.StringHttpMessageConverter"> 
      </beans:bean> 
      <beans:bean 
       class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"> 
       <beans:property name="objectMapper" ref="jacksonObjectMapper"/> 
      </beans:bean> 
     </message-converters> 
    </annotation-driven> 

这里是我的控制器映射

@RequestMapping(value = "/testURL", method = { RequestMethod.POST }) 
    public String add(HttpServletRequest request, @RequestBody CustomObject customObject) throws Exception {} 

但我的要求甚至没有达到控制器。只要我删除@RequestBody CustomObject customObject它的作品。但我想将json请求映射到 CustomObject与@RequestBody这不会发生。 不确定我在这里错过了什么?

事实上,当我检查request.getParameterMap()它显示为空,但只要我删除contentType: "application/json"我看参数图被填充,但仍 然后得到以下错误

`The server refused this request because the request entity is in a format not supported by the requested resource for the requested method` 

这里是我的CustomObject定义

public class CustomObject implements Serializable { 

private static final long serialVersionUID = 1L; 
private String name1; 
private String name2; 

//getters and setters 
} 

已经通过JQuery, Spring MVC @RequestBody and JSON - making it work together但没有帮助

+0

你为什么不张贴同样愚蠢的问题,之前检查的解决方案.. https://stackoverflow.com/questions/ 21124403/jquery-ajax-call-data-param-issue-in-spring-mvc-environment and https://stackoverflow.com/questions/31578206/issue-with-cross-domain-ajax-request-with-spring- restcontroller和https://stackoverflow.com/questions/12301719/spring-mvc-jquery-ajax-response-as-json-encoding-issue – 2017-10-08 15:59:54

回答

0

事实上,当我检查request.getParameterMap()它显示为空,但 只要我删除的contentType:“应用/ JSON”

这是正确的。原因在于jQuery在内部将数据转换为字符串。所以没有请求参数。如果没有contentType: "application/json",默认contentType' is form data . So data sent is converted to request parameters based on delimiters & and =`

也可以尝试data: JSON.stringify(dataModel),它应该工作