SpringMVC——REST进行CRUD

一、概述

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);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值