本节内容
- 请求http://localhost:8080/hello/getUser返回json
{"name":"叶敬轩","age":12}
整体步骤
- 新建SpringBoot项目
- 修改pom.xml,引入相关依赖
spring-boot-starter-web
- 新建
User.java
类,用于返回Json - 新建
HelloController.java
提供接口方法 - 测试,浏览器访问接口
具体步骤
- 修改pom.xml,添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 新建User.java
package com.yejx.pojo;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
public class User {
private String name;
private int age;
public User() {
}
public User(String name, int age) {
this.name = name;
this.age = age;
}
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;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
- 新建HelloController.java,
使用@RestController,@RequestMapping注解
@RestController由@Controller和@ResponseBody组成,省略写法
package com.yejx.controller;
import com.yejx.pojo.User;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author yejx
* @date 2021-05-25 0:12
*/
@RestController
@RequestMapping("/hello")
public class HelloController {
@RequestMapping("/getUser")
public User getUser(){
return new User("叶敬轩",12);
}
}
- 浏览器访问http://localhost:8080/hello/getUser
本文对应demo在仓库中tigerkin02-01目录中:gitee仓库地址