通过Spring正确的JSON REST Controller

维克托里奥

我是写弹簧支架控制器的新手。我想创建一个简单的JSON格式的发送,但无法处理,我的代码是否正确?

在我的代码中,有一个RestTemplate,它向REST URL发送一个简单的POJO,而REST控制器则向回发送另一个POJO。

我发现了许多示例,这些示例以JSON的形式发送和接收对象,但是其中一些已经使用了几年。我发现的最多的是,他们通过增加配置调度豆XMLMappingJackson2HttpMessageConverter配置bean来JSON转换成POJO,反之亦然

...
<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>
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean> 
...

并且他们还将其设置为RestTemplate Java代码:

List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();
messageConverters.add(new MappingJackson2HttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
restTemplate.setMessageConverters(messageConverters);

有时他们也设置标题:

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept", "application/json");
HttpEntity<MyObject> entity = new HttpEntity<MyObject>(inputRequest, headers);

有时,他们将对象转换为JSON格式,然后将其作为文本(而不是实例)发送。

而且我还能找到两种发送POST消息的方法:

ResponseEntity<MyObject> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, MyObject.class);

或者

MyObject response = restTemplate.postForObject(url, inputRequest, MyObject.class);

这是REST控制器:

@RequestMapping(value = "/send", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public MyObject send(@RequestBody MyObject requestModel) {
    return //whatever;
}

但是:如果我未在XML中设置任何内容,并且未在RestTemplate中添加任何消息转换器和标头,则看起来工作正常。我用PostMan进行了测试,如果添加MyClass示例的JSON格式,则会收到JSON。

所以我的问题是:我的代码对JSON发送来说真的正确吗?:

mvc-dispatcher.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- Enables the Spring MVC @Controller programming model -->
    <annotation-driven />
    <!-- to reach resources like css and images -->
    <default-servlet-handler/>
    <!-- the REST controllers are here -->
    <context:component-scan base-package="hu.viktor" />
</beans:beans>

RestTemplate Java:

@Controller
public class RequestSender {
    public MyObject send(MyObject inputRequest) {
        RestTemplate restTemplate = new RestTemplate();
        String url = "http://localhost:8080/rest/send";
        MyObject response = restTemplate.postForObject(url, inputRequest, MyObject.class);
        return response;
    }
}

和REST控制器:

@Controller
@RequestMapping("/rest")
public class CalculatorRestController {
    @RequestMapping(value = "/send", method = RequestMethod.POST, consumes=MediaType.APPLICATION_JSON_VALUE, produces=MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public MyObject send(@RequestBody MyObject requestModel) {
        return //whatever;
    }   
}
肯·贝科夫(Ken Bekov)

根据文档 RequestMappingHandlerMappingRequestMappingHandlerAdapter您指定将被自动添加,<mvc:annotation-driven/>(只是在你的情况下,在xml配置<annotation-driven>)。相同的文档包含的列表HttpMessageConverters,由设置<mvc:annotation-driven>'和:

MappingJackson2HttpMessageConverter 转换为JSON,或从JSON转换为JSON —如果classpath中存在Jackson 2,则添加。

这意味着,您无需手动添加json消息转换器,只需<mvc:annotation-driven>在配置文件中指定并在pom.xml中声明依赖项(如果使用的是Maven):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.6</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.6.1</version>
</dependency>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Spring Log for Rest Controller

Spring Rest Controller继承

Spring Rest Controller通过ID / ID方法查找

通过XML将属性注入Spring Rest Controller

Spring Boot Rest Controller:返回默认错误JSON

在Spring Boot Rest Controller中处理压缩的json请求

在Spring Rest Controller中获取JSON解析错误(MismatchedInputException)

Spring Boot Rest Controller API未返回JSON

Spring Rest Controller返回特定字段

Spring Rest`@ Controller`的行为更加糟糕

Spring Boot Rest Controller非常慢的响应

用于Spring Boot Rest Controller的Junit

Spring Rest Controller跟踪实体视图计数

在Spring Boot中未调用Rest Controller方法

如何使用Spring Rest Controller解决歧义映射?

Spring REST Controller没有响应Angular请求

Spring Boot Rest Controller如何返回不同的HTTP状态代码?

执行Pre Handle方法后未调用Spring Rest Controller

AngularJS $ http Spring Rest Controller-404错误

Spring Rest Controller:如何有选择地关闭验证

Spring Rest Controller测试中的NullPointer异常-Java

如何在Spring Rest Controller中测试异常?

Spring Boot REST Controller Integration Test返回406而不是500

Rest Controller无法在Spring Boot App中识别GET请求

Spring Boot:无法访问localhost上的REST Controller(404)

Spring REST Controller的单元测试“ Location”标头

使用Kotlin解决Spring Boot Rest Controller中的单例

如何从Spring Boot Rest Controller获取状态描述

Spring-addResourceHandlers无法使用Rest Controller解决静态资源