zoukankan      html  css  js  c++  java
  • Spring Boot构建RESTful API

    • @Controller:修饰class,用来创建处理http请求的对象
    • @RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。
    • @RequestMapping:配置url映射
    • RESTful API具体设计如下:
    请求类型URL功能说明
    GET /users 查询用户列表
    POST /users 创建一个用户
    GET /users/id 根据id查询一个用户
    PUT /users/id 根据id更新一个用户
    DELETE /users/id
    1. 根据id删除一个用户

    User实体定义:

         private Long id; 
        private String name; 
        private Integer age; 
    
        // 省略setter和getter

    User  restful接口声明

    @RequestMapping(value = "/users")
    public interface UserRestService {
        @RequestMapping(value = "/", method = RequestMethod.GET)
        List<User> getUserList();
    
        @RequestMapping(value = "/", method = RequestMethod.POST)
        String postUser(@ModelAttribute User user);
    
        @RequestMapping(value = "/{id}", method = RequestMethod.GET)
        User getUser(@PathVariable Long id);
    
        @RequestMapping(value="/{id}", method=RequestMethod.PUT)
         String putUser(@PathVariable Long id, @ModelAttribute User user);
    
        @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
        String deleteUser(@PathVariable Long id);
    }

    接口实现

    @RestController
    public class UserRestServiceImpl implements  UserRestService {
    
        static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());
    
        @Override
        public List<User> getUserList() {
            List<User> r = new ArrayList<User>(users.values());
            return r;
        }
    
        @Override
        public String postUser(@ModelAttribute User user) {
            users.put(user.getId(), user);
            return "success";
        }
    
        @Override
        public User getUser(@PathVariable Long id) {
            return users.get(id);
        }
    
        @Override
        public String putUser(@PathVariable Long id, @ModelAttribute User user) {
            User u = users.get(id);
            u.setName(user.getName());
            u.setAge(user.getAge());
            users.put(id, u);
            return "success";
        }
    
        @Override
        public String deleteUser(@PathVariable Long id) {
            users.remove(id);
            return "success";
        }
    }

    验证:

    以创建用户为例

    response

  • 相关阅读:
    用Delphi创建windows服务程序
    如何把程序手工添加系统服务
    http://www.ebooksearchengine.com/albpmpapiebookall.html
    C语言函数二维数组传递方法
    计算程序运行时间(C语言)
    快排序(递归算法)
    厄拉多塞筛(C语言)
    C语言中实现数组的动态增长
    [转]四种流行的Javascript框架jQuery,Mootools,Dojo,ExtJS的对比
    [存档]使用.Net开发web程序时现在比较流行的前台技术都有什么?
  • 原文地址:https://www.cnblogs.com/ilinuxer/p/6444804.html
Copyright © 2011-2022 走看看