带有jQuery的@RequestBody将json数据映射到RequestBody。在浏览器中显示媒体类型异常

时间:2017-06-28 17:35:06

标签: java spring spring-mvc servlets

我是春天的新手,我尝试过不同的方法来获得解决方案, 我必须使用@RequestBody来获取来自jQuery的json数据。 我读了spring doc但是我没有发现任何事情clear.reg需要添加什么jar以及如何在xml文件中映射。 我试过了

headers={"Accept=application/json"}
produces="application/json", consumes = "application/json"
consumes=MediaType.APPLICATION_FORM_URLENCODED_VALUE
application/x-www-form-urlencoded
MappingJacksonHttpMessageConverter(but i didn't want to used because i think its springBoot class)
@RequestMapping(method = RequestMethod.PUT) headers = "Accept=application/json"

UserController.java

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.evon.model.user.UserModel;
@Controller
public class UserController {
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public void handleXMLPostRequest (@RequestBody UserModel user) {
        System.out.println(user);
        System.out.println(user.getUserId());
        System.out.println(user.getEmailId());
        System.out.println(user.getPassword());
    }
}

UserModel.java

public class UserModel implements Serializable 
{
 private Integer userId;
 private String emailId;
 private String password;   
 public Integer getUserId() {
    return userId;
 }
 public void setUserId(Integer userId) {
    this.userId = userId;
 }
 public String getEmailId() {
    return emailId;
 }
 public void setEmailId(String emailId) {
    this.emailId = emailId;
 }
 public String getPassword() {
    return password;
 }
  public void setPassword(String password) {
        this.password = password;
    }
}

的web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">
    <display-name>withDiffServletName</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name> 
        <param-value>/WEB-INF/demo-servlet.xml</param-value> 
    </context-param> 
    <listener> 
        <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> 
    </listener> 
</web-app>

演示servlet.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:context = "http://www.springframework.org/schema/context"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans     
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd 
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
   <context:component-scan base-package = "com.evon.model.controller,com.evon.model.user" />
   <context:annotation-config/> 
   <mvc:annotation-driven />
</beans>

的index.jsp

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
//Ajax submit create user
    function ajaxSubmitCreateUserForm() {
        alert("==ajaxSubmitCreateUserForm");
         try{
     $.ajax({
            beforeSend: function(xhrObj){
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Accept","application/json");
            },
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            type: "POST",
            url : 'register', 
            data: JSON.stringify({
                userId : "101",
                password : "password",
                emailId : "ankit.bhimjiyani@gmail.com"
            }),               
            dataType: "json",
            contentType: "application/json; charset=utf-8",

            success: function(json){
               console.log(json);
            },
            error : function() {
                alert('System error occured, please try again ...');
            }
        });


 }catch (e) {
    alert(e)
}}
</script>
<div class="buttonBlock">
    <button class="submitBTN" onclick="ajaxSubmitCreateUserForm();">Submit</button>
</div>

directory Structure

3 个答案:

答案 0 :(得分:0)

您可以尝试为控制器添加返回类型,并将方法注释为@ResponseBody。我认为问题是肯定的,因为jquery期望从服务器返回一个响应而你没有发送它。你可以试试吗。

答案 1 :(得分:0)

compile 'com.fasterxml.jackson.core:jackson-databind:2.7.5'
compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.5'
compile 'com.fasterxml.jackson.core:jackson-core:2.7.5' include this jars in classpath

答案 2 :(得分:-1)

您必须将producesconsumes用于RequestMapping。你可以参考下面的代码:

@RestController
@RequestMapping("/city")
public class CityController {
private static final Logger logger = LoggerFactory.getLogger(CityController.class);
@Autowired(required = true)
private CityService cityService;

@RequestMapping(method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public RestResponse save(@RequestBody CityView cityView) {
}