简体   繁体   English

JSON发布到Spring Controller

[英]JSON post to Spring Controller

Hi I am starting with Web Services in Spring, so I am trying to develop small application in Spring + JSON + Hibernate. 嗨,我从Spring的Web Services开始,所以我试图在Spring + JSON + Hibernate中开发小型应用程序。 I have some problem with HTTP-POST. 我对HTTP-POST有问题。 I created a method: 我创建了一个方法:

@RequestMapping(value="/workers/addNewWorker", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
@ResponseBody
public String addNewWorker(@RequestBody Test test) throws Exception {
    String name = test.name;
    return name;
}

And my model Test looks like: 我的模型测试看起来像:

public class Test implements Serializable {

private static final long serialVersionUID = -1764970284520387975L;
public String name;

public Test() {
}
}

By POSTMAN I am sending simply JSON {"name":"testName"} and I always get error; 通过POSTMAN,我仅发送JSON {“ name”:“ testName”},但我总是收到错误;

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

I imported Jackson library. 我导入了杰克逊图书馆。 My GET methods works fine. 我的GET方法工作正常。 I don't know what I'm doing wrong. 我不知道我在做什么错。 I am grateful for any suggestions. 我很感谢任何建议。

Convert your JSON object to JSON String using 使用将您的JSON对象转换为JSON字符串

JSON.stringify({"name":"testName"}) JSON.stringify({“ name”:“ testName”})

or manually. 或手动。 @RequestBody expecting json string instead of json object. @RequestBody需要json字符串而不是json对象。

Note:stringify function having issue with some IE version, firefox it will work 注意:stringify函数在某些IE版本中存在问题,firefox可以使用

verify the syntax of your ajax request for POST request. 验证POST请求的ajax请求的语法。 processData:false property is required in ajax request Ajax请求中需要processData:false属性

$.ajax({ 
    url:urlName,
    type:"POST", 
    contentType: "application/json; charset=utf-8",
    data: jsonString, //Stringified Json Object
    async: false,    //Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation
    cache: false,    //This will force requested pages not to be cached by the browser  
     processData:false, //To avoid making query String instead of JSON
     success: function(resposeJsonObject){
        // Success Action
    }
});

Controller 控制者

@RequestMapping(value = urlPattern , method = RequestMethod.POST)

public @ResponseBody Test addNewWorker(@RequestBody Test jsonString) {

    //do business logic
    return test;
}

@RequestBody -Covert Json object to java @RequestBody RequestBody-将Json对象转换为Java

@ResponseBody - convert Java object to json @ResponseBody将Java对象转换为json

You need to include the getters and setters for all the fields that have been defined in the model Test class -- 您需要为模型Test类中已定义的所有字段包括getter和setter -

public class Test implements Serializable {

    private static final long serialVersionUID = -1764970284520387975L;

    public String name;

    public Test() {

    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Try to using application/* instead. 尝试改用application / *。 And use JSON.maybeJson() to check the data structure in the controller. 并使用JSON.maybeJson()检查控制器中的数据结构。

Do the following thing if you want to use json as a http request and response. 如果要将json用作http请求和响应,请执行以下操作。 So we need to make changes in [context].xml 因此,我们需要在[context] .xml中进行更改

<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>   

MappingJackson2HttpMessageConverter to the RequestMappingHandlerAdapter messageConverters so that Jackson API kicks in and converts JSON to Java Beans and vice versa. 将pingpingJackson2HttpMessageConverter映射到RequestMappingHandlerAdapter messageConverters,以便Jackson API启动并将JSON转换为Java Bean,反之亦然。 By having this configuration, we will be using JSON in request body and we will receive JSON data in the response. 通过进行此配置,我们将在请求正文中使用JSON,并将在响应中接收JSON数据。

I am also providing small code snippet for controller part: 我还为控制器部分提供了一些小代码段:

    @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)

    public @ResponseBody Employee getDummyEmployee() {
    logger.info("Start getDummyEmployee");
    Employee emp = new Employee();
    emp.setId(9999);
    emp.setName("Dummy");
    emp.setCreatedDate(new Date());
    empData.put(9999, emp);
    return emp;
}

So in above code emp object will directly convert into json as a response. 因此,在上面的代码中,emp对象将直接转换为json作为响应。 same will happen for post also. 邮寄也会发生同样的情况。

see here 这里

The consumable media types of the mapped request, narrowing the primary mapping. 映射请求的可消耗媒体类型,从而缩小了主映射的范围。

the producer is used to narrow the primary mapping, you send request should specify the exact header to match it. 生产者用于缩小主映射,您的发送请求应指定与之匹配的确切标头。

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

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