springmvc返回json
现在很多项目已经前后端分离了,不再使用jsp或者使用jsp但是数据使用ajax来获取,实现局部刷新的效果,那么springmvc中如何不返回页面而返回页面所需要的数据呢。
前后端数据交互现在大多使用json来表示(当然有一部分还是使用xml的),那如何在springmvc中返回json数据呢。
返回json
依赖
1 2 3 4 5
| <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.11.3</version> </dependency>
|
接口层面的改动
在controller返回时不再返回ModelAndView,而是返回具体的数据对象,在方法上添加@ResponseBody注解
1 2 3 4 5 6 7 8
| @ResponseBody @RequestMapping("/testJson") public User testJson(){ User user = new User(); user.setName("张三"); user.setId(2); return user; }
|
Why?
为什么只是加了一个依赖,加一个注解就可以完成返回json数据呢。
这里用到了一个接口,HttpMessageConverter接口,该接口可以将请求信息转为所对应的入参,将返回结果转为对应类型的响应信息
1 2 3 4 5 6 7 8 9 10 11
| 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作为方法的入参或返回值