开发环境:IntelliJ IDEA 2019.2.2
Spring Boot版本:2.1.8
一、发布REST服务
1、IDEA新建一个名称为rest-server的Spring Boot项目
2、新建一个实体类User.java
package com.example.restserver.domain;
public class User {
String name;
Integer age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
3、新建一个控制器类 UserController.java
package com.example.restserver.web;
import com.example.restserver.domain.User;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@RequestMapping(value="/user/{name}", produces = MediaType.APPLICATION_JSON_VALUE)
public User user(@PathVariable String name) {
User u = new User();
u.setName(name);
u.setAge(30);
return u;
}
}
项目结构如下:
访问 http://localhost:8080/user/lc,页面显示:
{"name":"lc","age":30}
二、使用RestTemplae调用服务
1、IDEA新建一个名称为rest-client的Spring Boot项目
2、新建一个含有main方法的普通类 RestTemplateMain.java,调用服务
package com.example.restc