• REDTful风格设计接口


     1.创建实体类

    package com.offcn.po;

    import lombok.AllArgsConstructor;
    import lombok.Data;
    import lombok.NoArgsConstructor;

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {
    private Long id;
    private String name;
    private Integer age;
    }

    2. 创建Controller  UserController

    package com.offcn.controllerold;

    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;

    import org.springframework.web.bind.annotation.DeleteMapping;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.PutMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;

    import com.offcn.po.User;

    @RestController
    @RequestMapping("/users-test")
    public class UserController {

    //这里加同步锁是为了访问安全

    private List<User> listUser=Collections.synchronizedList(new ArrayList<User>());

    /***
    * 获取全部用户信息
    * @return
    */
    @GetMapping("/")
    public List<User> getUserList(){
    return listUser;
    }

    /***
    * 新增用户
    * @param user
    * @return
    */
    @PostMapping("/")
    public String createUser(User user) {
    listUser.add(user);
    return "success";
    }

    /***
    * 获取指定id用户信息
    * @param id
    * @return
    */
    @GetMapping("/{id}")
    public User getUser(@PathVariable("id")Long id) {
    for (User user : listUser) {
    if(user.getId()==id) {
    return user;
    }
    }
    return null;
    }
    /**
    * 更新指定id用户信息
    * @param id
    * @param user
    * @return
    */
    @PutMapping("/{id}")
    public String updateUser(@PathVariable("id") Long id,User user) {
    for (User user2 : listUser) {
    if(user2.getId()==id) {
    user2.setName(user.getName());
    user2.setAge(user.getAge());
    }
    }
    return "success";
    }

    /***
    * 删除指定id用户
    * @param id
    * @return
    */
    @DeleteMapping("/{id}")
    public String deleteUser(@PathVariable("id") Long id) {

    listUser.remove(getUser(id));
    return "success";

    }
    }

  • 相关阅读:
    98. 验证二叉搜索树
    236. 二叉树的最近公共祖先
    leetcode 字符串转换整数 (atoi)
    LeetCode 寻找两个正序数组的中位数 (找第k个数的变种)
    Leetcode 面试题 16.18. 模式匹配(逻辑题)(转)
    深入学习Redis(4):哨兵(转)
    【BAT面试题系列】面试官:你了解乐观锁和悲观锁吗?(转)
    CentOS 7.5 使用 yum 方式安装 MySQL 5.7
    CentOS7 安装 PHP7 完全详细教程
    ubunutu 18.04 编译php7.4.1
  • 原文地址:https://www.cnblogs.com/wycBolg/p/11795725.html
Copyright © 2020-2023  润新知