一、概述
REST:Representational State Transfer,资源表现层状态转换,是目前比较主流的一种互联网软件架构
二、使用
REST 具体操作就是 HTTP 协议中四个表示操作方式的动词分别对应 CRUD 基本操作。
- GET 用来表示获取资源。
- POST 用来表示新建资源。
- PUT 用来表示修改资源。
- DELETE 用来表示删除资源。
@RequestMapping(value = "/findAll",method = RequestMethod.GET)
与@GetMapping("/findAll")
相等价
处理中文不正常显示
方法一:设置 @RequestMapping 的 produces = {"text/json;charset=UTF-8"}
方法二:设置 HttpServletResponse, response.setCharacterEncoding("UTF-8");
Handler:
@RestController
@RequestMapping(value = "/rest",produces = {"text/json;charset=UTF-8"})
public class RESTHandler {
@Autowired
private PeopleRepository peopleRepository;
@GetMapping(value = "/findAll")
public Collection<People> findAll(){
return peopleRepository.findAll();
}
@GetMapping("/findById/{id}")
public People findById(@PathVariable("id")Integer id){
return peopleRepository.findById(id);
}
@PostMapping("/save")
public void save(@RequestBody People people){
peopleRepository.saveOrUpdate(people);
}
@PutMapping("/update")
public void update(@RequestBody People people){
peopleRepository.saveOrUpdate(people);
}
@DeleteMapping("/delete/{id}")
public void delete(@PathVariable("id") Integer id){
peopleRepository.deleteById(id);
}
}
repository:
public interface PeopleRepository {
Collection<People> findAll();
People findById(Integer id);
void saveOrUpdate(People people);
void deleteById(Integer id);
}
repositoryImpl:
@Repository
public class PeopleRepositoryImpl implements PeopleRepository {
private static Map<Integer,People> peopleMap;
static {
peopleMap = new HashMap<>();
peopleMap.put(1, new People(1,"张三",20));
peopleMap.put(2, new People(2, "李四", 25));
peopleMap.put(3, new People(3, "王五", 30));
}
@Override
public Collection<People> findAll() {
return peopleMap.values();
}
@Override
public People findById(Integer id) {
return peopleMap.get(id);
}
@Override
public void saveOrUpdate(People people) {
peopleMap.put(people.getId(), people);
}
@Override
public void deleteById(Integer id) {
peopleMap.remove(id);
}
}