Spring学习(八)——Spring MVC之Restful API返回json数据

在上一篇博客的基础之上,对Spring MVC的使用有了一个基本的了解,而现在基本上都是用的前后端分离,因此需要对上一篇博客的demo进行一些修改,来满足我们的需要。

文章目录

    • 一、引入jackson依赖
    • 二、在Controller类中添加注解
      • 方式一:@RestController
      • 方式二:@ResponseBody

一、引入jackson依赖

jackson方便直接将Controller中的对象转为json对象返回给前端。

    
    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-annotationsartifactId>
      <version>2.9.0version>
    dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.coregroupId>
      <artifactId>jackson-databindartifactId>
      <version>2.9.0version>
    dependency>

二、在Controller类中添加注解

方式一:@RestController

可以在Controller类上直接添加@RestController注解,省去@Controller注解,因为@RestController相当于@ResponseBody@Controller一起的作用效果。在类上添加该注解后,下面的方法默认都将返回的对象转为json字符串。

package cool.gjh.controller;

import cool.gjh.entity.Student;
import cool.gjh.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller层
 * 

* Restful风格,返回json数据 *

* @author ACE_GJH */
@RestController @RequestMapping("/student") public class StudentRestfulController { @Autowired private StudentService studentService; @RequestMapping(value = "/data", method = RequestMethod.GET) public Map<String, Object> showAll(){ List<Student> students = studentService.getAllStudent(); HashMap<String, Object> data = new HashMap<>(4*5/4, 0.8f); data.put("code", 200); data.put("msg", "OK"); data.put("data", students); data.put("date", System.currentTimeMillis()); return null; } }

测试效果:
运行结果

方式二:@ResponseBody

在Controller类的方法上添加@ResponseBody注解,则该方法返回的对象将会以

package cool.gjh.controller;

import cool.gjh.entity.Student;
import cool.gjh.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller层
 * 

* Restful风格,返回json数据 *

* @author ACE_GJH */
@Controller @RequestMapping("/student") public class StudentRestfulController { @Autowired private StudentService studentService; @ResponseBody @RequestMapping(value = "/data", method = RequestMethod.GET) public Map<String, Object> showAll(){ List<Student> students = studentService.getAllStudent(); HashMap<String, Object> data = new HashMap<>(4*5/4, 0.8f); data.put("code", 200); data.put("msg", "OK"); data.put("data", students); data.put("date", System.currentTimeMillis()); return data; } }

测试效果:
测试效果2

你可能感兴趣的:(Spring全家桶,spring,restful,json,java,mvc)