原文链接:http://www.jianshu.com/p/7097fea8ce3f
@ResponseBody用法
作用:
该注解用于将Controller的方法返回的对象,根据HTTP Request Header的Accept的内容,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
使用时机:
返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用.
配置返回JSON和XML数据
1.添加jackson依赖
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.4</version> </dependency>
2.开启<mvc:annotation-driven />
3.代码
@Controller @RequestMapping("/user") public class UserController { @RequestMapping(value = "/query", method = RequestMethod.GET) @ResponseBody public User queryBasic() { User user = new User(); user.setId(10); user.setUserName("zhangsan"); user.setPassword("123456"); user.setSex(10); user.setCreated(new Date()); return user; } }
User.java
public class User { private Integer id; // 用户名 private String userName; // 密码 private String password; // 性别,1男性,2女性 private Integer sex; // 创建时间 private Date created; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getSex() { return sex; } public void setSex(Integer sex) { this.sex = sex; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } @Override public String toString() { return "User{" + "id=" + id + ", userName=‘" + userName + ‘\‘‘ + ", password=‘" + password + ‘\‘‘ + ", sex=" + sex + ", created=" + created + ‘}‘; } }
测试
---------------------------------------------------------
总结:
可以看到,想要返回json数据只要配置三个地方就可以了
1.jackson依赖 2.SpringMVC配置文件中加上<mvc:annotation-driven/>注解 3.Controller中的@ResponseBody注解
除此之外并不需要配置转换器什么的,当然这只是使用,其中的原理还是要去了解的
时间: 2024-10-11 04:00:17