原文链接http://zhhll.icu/2021/01/09/%E6%A1%86%E6%9E%B6/springmvc/springmvc%E8%BF%94%E5%9B%9Ejson/

springmvc返回json

现在很多项目已经前后端分离了,不再使用jsp或者使用jsp但是数据使用ajax来获取,实现局部刷新的效果,那么springmvc中如何不返回页面而返回页面所需要的数据呢。

前后端数据交互现在大多使用json来表示(当然有一部分还是使用xml的),那如何在springmvc中返回json数据呢。

返回json

依赖

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

接口层面的改动

在controller返回时不再返回ModelAndView,而是返回具体的数据对象,在方法上添加@ResponseBody注解

@ResponseBody
@RequestMapping("/testJson")
public User testJson(){
    User user = new User();
    user.setName("张三");
    user.setId(2);
    return user;
}

Why?

为什么只是加了一个依赖,加一个注解就可以完成返回json数据呢。

这里用到了一个接口,HttpMessageConverter接口,该接口可以将请求信息转为所对应的入参,将返回结果转为对应类型的响应信息

public interface HttpMessageConverter<T> {
    boolean canRead(Class<?> var1, MediaType var2);

    boolean canWrite(Class<?> var1, MediaType var2);

    List<MediaType> getSupportedMediaTypes();

    T read(Class<? extends T> var1, HttpInputMessage var2) throws IOException, HttpMessageNotReadableException;

    void write(T var1, MediaType var2, HttpOutputMessage var3) throws IOException, HttpMessageNotWritableException;
}

spring提供了两种方式

  • 使用@RequestBody或@ResponseBody对处理的方法进行处理
  • 使用HttpEntity/ResponseEntity作为方法的入参或返回值

由于本身的博客百度没有收录,博客地址http://zhhll.icu

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/life-time/p/14478340.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!