SpringMVC回写数据
一、直接回写字符串
@RequestMapping("/quick3")
public void save6(HttpServletResponse response) throws IOException {
response.getWriter().print("hello world!");
}
@RequestMapping("/quick4")
@ResponseBody //告知SpringMVC框架,不进行视图跳转,而是直接进行数据响应
public String save7(HttpServletResponse response) throws IOException {
return "hello java";
}
二、直接返回Json格式
@RequestMapping("/quick5")
@ResponseBody //告知SpringMVC框架,不进行视图跳转,而是直接进行数据响应
public String save5(HttpServletResponse response) throws IOException {
return "{\"uesrname\":\"zhangsan\",\"age\":18}";
}
正式版
@RequestMapping("/quick6")
@ResponseBody //告知SpringMVC框架,不进行视图跳转,而是直接进行数据响应
public String save9(HttpServletResponse response) throws IOException {
User user=new User();
user.setUsername("zhangsan");
user.setAge(18);
//使用json转换工具将对象转换成json格式字符串在进行返回
ObjectMapper objectMapper=new ObjectMapper();
String json = objectMapper.writeValueAsString(user);
return json;
}
导入json依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
创建User文件
package com.atguigu.mvc.domain;
public class User {
private String username;
private int age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", age=" + age +
'}';
}
}
三、返回对象或集合
在SpringMVC.xml文件中添加配置
<!--配置处理器适配器-->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
@RequestMapping("/quick7")
@ResponseBody //告知SpringMVC框架,不进行视图跳转,而是直接进行数据响应
public User save10(){
//SpringMVC自动将User类型转换成json类型
User user=new User();
user.setUsername("lisi");
user.setAge(20);
return user;
}
方法二、
观察第一篇SpringMVC的博客中的配置文件,会发现有一行注释mvc的注解驱动,所以已经配置好了,这篇博客上述的SpringMVC添加的配置可以删去了