上手spring boot项目(四)之springboot如何返回json数据

WebGPU学习(五): 现代图形API技术要点和WebGPU支持情况调研

在springboot整合thymeleaf中,经常会在HTML页面中接收来自服务器的json数据,然后处理json数据并在页面上渲染。那么如何在服务器中返回json类型的数据呢?

1.使用@ResponseBody注解

该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格式的

数据如:json,xml 等,通过 Response 响应给客户端

在controller的方法上增加@RespongBody

@RequestMapping("/findAll.do")
@ResponseBody
public List<SysCategory> findAll(){ //查询分类信息,具体的service层方法略 List<SysCategory> categoryList = categoryService.findAll(); System.out.println(categoryList); return categoryList; } 

Java控制台打印出的结果如下:

上手spring boot项目(四)之springboot如何返回json数据

 接下来是在前端接收服务器返回的json数据

初次在Vue项目使用TypeScript,需要做什么

 $.get("/category/findAll.do",{},function (data) {
            console.log(data);
},"json");

在页面控制台打印出的结果如下:

上手spring boot项目(四)之springboot如何返回json数据

 可以看到 服务器端的返回的确实是json类型的数据

2. 使用@RestController注解

@RestController是@ResponseBody和@Controller两者的结合,使用这个注解后就无需再用那两个注解。
@RestController
@RequestMapping("/category") public class CategoryController { @Autowired private CategoryService categoryService; @RequestMapping("/findAll.do") public List<SysCategory> findAll(){ List<SysCategory> categoryList = categoryService.findAll(); System.out.println(categoryList); return categoryList; } }

发送的请求和在controller层的业务逻辑和第一种方法一样。

在页面控制台打印出的结果如下:

上手spring boot项目(四)之springboot如何返回json数据

3.使用response将数据写回客户端(不推荐)

String obj = "[SysCategory{id=1, name='JavaSe'}, SysCategory{id=2, name='JavaEE'}, SysCategory{id=3, name='前端'}, SysCategory{id=4, name='其他'}]"
ObjectMapper mapper = new ObjectMapper(); response.setContentType("application/json;charset=utf-8"); mapper.writeValue(response.getOutputStream(),obj);

在页面控制台打印出的结果如下:

 上手spring boot项目(四)之springboot如何返回json数据

AI Boot Camp 分享之 ML.NET 机器学习指南

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享