@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
数据即可。
项目创建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;
}
}
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;
}
}
源码地址:github
本文地址:https://blog.csdn.net/jance_hui/article/details/107345864
如对本文有疑问, 点击进行留言回复!!
before社区电量是什么意思 Before社区电量获得方法
RecycleView入门详解(教你全面掌握RecycleView用法)
动态权限请求框架RxPermissions(几行代码搞定权限)
URL路径@PathVariable出现点号“.“时值遭截断问题
网友评论