spring boot学习02 - 返回json数据
1.@Controller
与@RestController
区别
@RestController
相当于 @Controller
+ @ResponseBody
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
/**
* The value may indicate a suggestion for a logical component name,
* to be turned into a Spring bean in case of an autodetected component.
* @return the suggested component name, if any (or empty String otherwise)
* @since 4.0.1
*/
@AliasFor(annotation = Controller.class)
String value() default "";
}
当返回的是jsp
,html
页面时,可使用@Controller
注解,返回return
中的相关页面;
@Controller
@RequestMapping("/demo")
public class LoginController {
@RequestMapping("/login")
public String login(UserInfo info){
// 数据库检查登录用户名、密码是否正确
// ...
return "index"; // 登陆成功,返回index页面
}
}
若需要返回的数据是json
串时,在使用@Controller
的前提下还需添加@ResponseBody
注解,这种情况下就可直接使用@RestController
注解完成操作。
@RestController
@RequestMapping("/demo")
public class LoginController {
@RequestMapping("/getInfo")
public UserInfo getInfo(String userName){
UserInfo info = new UserInfo();
// 数据库查询用户信息
// ...
return info; // 直接返回json数据
}
}
在当前流行的前后端分离的环境下,即可使用@RestController
来代替@Controller
与@ResponseBody
,前台只需获取json
数据即可。
2.代码实现
2.1.创建返回实体
项目创建entity
存放实体类
public class StudentEntity {
private String name;
private int age;
private String sex;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
2.2.创建controller
,并返回数据
@RestController
@RequestMapping("/learn2")
public class JsonController {
@RequestMapping("/returnJson")
public StudentEntity returnJson(){
StudentEntity studentEntity = new StudentEntity();
studentEntity.setName("张三");
studentEntity.setAge(21);
studentEntity.setSex("男");
return studentEntity;
}
}
2.3.返回结果
源码地址:github