Spring REST JSON响应示例

Spring REST JSON示例中,我们将学习编写能够返回资源的JSON表示形式的RESTful Web服务。我们将使用MappingJackson2JsonView将视图解析为JSON主体。

阅读更多:Spring REST XML教程

1。 Spring REST JSON – @ResponseBody注解

第一种技术是简单和容易。我们只需要在应用程序的类路径中包含 Jackson 依赖项,spring就会Jackson2JsonMessageConverter自动将类注册到上下文中。每当我们从REST API请求资源并提供http标头“ accept:application / json ”时,我们都将获取资源的json表示形式。

1.1。运行时JSON依赖性

pom.xml
<!-- Jackson JSON Processor -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.1</version>
</dependency>

1.2。@ResponseBody支持

这里@RestController = @Controller + @ResponseBody

EmployeeRESTController.java
@RestController
public class EmployeeRESTController
{
    @RequestMapping(value = "/employees")
    public EmployeeListVO getAllEmployees()
    {
        EmployeeListVO employees = new EmployeeListVO();
         
        EmployeeVO empOne = new EmployeeVO(1"Lokesh""Gupta""mobtrack_service@163.com");
        EmployeeVO empTwo = new EmployeeVO(2"Amit""Singhal""asinghal@yahoo.com");
        EmployeeVO empThree = new EmployeeVO(3"Kirti""Mishra""kmishra@gmail.com");
         
         
        employees.getEmployees().add(empOne);
        employees.getEmployees().add(empTwo);
        employees.getEmployees().add(empThree);
         
        return employees;
    }
     
    @RequestMapping(value = "/employees/{id}")
    public ResponseEntity<EmployeeVO> getEmployeeById (@PathVariable("id") int id)
    {
        if (id <= 3) {
            EmployeeVO employee = new EmployeeVO(1"Lokesh""Gupta""mobtrack_service@163.com");
            return new ResponseEntity<EmployeeVO>(employee, HttpStatus.OK);
        }
        return new ResponseEntity(HttpStatus.NOT_FOUND);
    }
}

2。 Spring REST JSON – MappingJackson2JsonView支持

这是第二种技术。该MappingJackson2JsonView班还取决于存在 Jackson 在类路径JSON处理器库,所以你不需要添加任何额外的东西做的。完成pom.xml看起来像这样。

2.1。Maven依赖

pom.xml
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.how2codex.demo</groupId>
  <artifactId>springrestexample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springrestexample Maven Webapp</name>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    
    <!-- Spring MVC support -->
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.1.4.RELEASE</version>
    </dependency>
    
    <!-- Jackson JSON Processor -->
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.4.1</version>
    </dependency>
            
  </dependencies>
  <build>
    <finalName>springrestexample</finalName>
  </build>
</project>

2.2。添加MappingJackson2JsonView视图

使用MappingJackson2JsonView类时,您需要返回type的视图名称MappingJackson2JsonView。因此,您将需要更改两个位置。

2.2.1。控制器变更

您将需要从控制器方法返回viewName。在我们的例子中,视图名称是“ jsonTemplate ”。

package com.how2codex.demo.controller;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.how2codex.demo.model.EmployeeListVO;
import com.how2codex.demo.model.EmployeeVO;
@Controller
public class EmployeeRESTController
{
    
    private EmployeeListVO getEmployeesCollection()
    {
        EmployeeListVO employees = new EmployeeListVO();
        
        EmployeeVO empOne = new EmployeeVO(1"Lokesh""Gupta""mobtrack_service@163.com");
        EmployeeVO empTwo = new EmployeeVO(2"Amit""Singhal""asinghal@yahoo.com");
        EmployeeVO empThree = new EmployeeVO(3"Kirti""Mishra""kmishra@gmail.com");
        
        
        employees.getEmployees().add(empOne);
        employees.getEmployees().add(empTwo);
        employees.getEmployees().add(empThree);
        
        return employees;
    }
    
    @RequestMapping(value = "/employees")
    public String getAllEmployeesJSON(Model model)
    {
        model.addAttribute("employees", getEmployeesCollection());
        return "jsonTemplate";
    }
}
2.2.2。配置变更

您将需要将viewName“ jsonTemplate ” 配置为type的bean MappingJackson2JsonView。并且您将需要配置类型的视图解析器BeanNameViewResolver。这样,viewName“ jsonTemplate ”将与之匹配,MappingJackson2JsonView并且将解析的JSON响应返回给客户端。

RESTConfiguration.java
@Configuration
public class RESTConfiguration
{
    @Bean
    public View jsonTemplate() {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setPrettyPrint(true);
        return view;
    }
    
    @Bean
    public ViewResolver viewResolver() {
        return new BeanNameViewResolver();
    }
}

与上述Java配置等效的XML配置如下。

spring-servlet.xml
    <context:component-scan base-package="com.how2codex.demo" />
    <mvc:annotation-driven />
    
    <!-- JSON Support -->
    <bean name="viewResolver" class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
    <bean name="jsonTemplate" class="org.springframework.web.servlet.view.json.MappingJackson2JsonView"/>
</beans>

3。 Spring REST JSON示例–演示

现在,当您点击URL:时http://localhost:8080/springrestexample/employees,您将得到此结果。

Spring REST JSON示例
Spring REST JSON示例

4。 Spring REST JSON示例–项目结构

Spring REST JSON示例-项目结构
Spring REST JSON示例–项目结构

这就是使用spring mvc的快速Spring Restful Web服务json示例的全部内容。将您的问题留在我的评论中。

saigon has written 1445 articles

Leave a Reply