当前位置: 移动技术网 > IT编程>开发语言>Java > spring boot学习02 - 返回json数据

spring boot学习02 - 返回json数据

2020年07月17日  | 移动技术网IT编程  | 我要评论

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 "";

}

当返回的是jsphtml页面时,可使用@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

本文地址:https://blog.csdn.net/jance_hui/article/details/107345864

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网