开发rest风格接口的时候,需要给前端返回Json格式的数据。
步骤:
1.在maven中加入json转换相关依赖(编辑pom.xml)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.8</version>
</dependency>
2.在springmvc的xml配置文件中加入注解驱动配置:
<mvc:annotation-driven/>
3.修改Controller的注解,在类上注解@RestController或在类上注解@Controller,在方法上注解@ResponseBody
@RestController
@RequestMapping("/user")
public class UserController {
//...
@RequestMapping("/hello")
public UserPojo index() {
UserPojo user = new UserPojo();
user.setUsername("hello");
user.setPassword("world");
return user;
}
}
@Controller
@RequestMapping("/user")
public class UserController {
//...
@ResponseBody
@RequestMapping("/hello")
public UserPojo index() {
UserPojo user = new UserPojo();
user.setUsername("hello");
user.setPassword("world");
return user;
}
}