zoukankan      html  css  js  c++  java
  • 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】03、创建RESTful API,并统一处理返回值

    本节应用Spring对RESTful的支持,使用了如@RestController等注解实现RESTful控制器。

    如果对Spring中的RESTful不太明白,请查看相关书籍

    1、创建一个数据对象,用来统一RESTful API的返回格式

    package com.ltsolution.framework.common.msgmodel;
    
    import java.util.HashMap;
    import java.util.Map;
    
    public class AppResult {
        private String status;
        private String error;
        private String message;
        private Map<String, Object> data = new HashMap<String, Object>();
    
        public String getStatus() {
            return status;
        }
    
        public void setStatus(String status) {
            this.status = status;
        }
    
        public String getError() {
            return error;
        }
    
        public void setError(String error) {
            this.error = error;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public Map<String, Object> getData() {
            return data;
        }
    
        public void setData(Map<String, Object> data) {
            this.data = data;
        }
    
        public AppResult ok(String statusMsg) {
            this.status="200";
            this.message=statusMsg;
            return this;
        }
        public AppResult error(String statusMsg) {
            this.status="500";
            this.message=statusMsg;
            return this;
        }
        public AppResult addData(String key,Object object) {
            this.data.put(key,object);
            return this;
        }
    }
    View Code

    2、创建RESTful控制器

    @RestController
    @RequestMapping(value = "/")
    public class UserController {
    
        @PostMapping("/login")
        public AppResult login(HttpServletRequest request, HttpServletResponse response) throws Exception {
            return new AppResult().ok("登录成功!").addData("token", 1234);
        }
        @PostMapping("/test")
        public AppResult test(HttpServletRequest request, HttpServletResponse response) throws Exception {
            return new AppResult().ok("测试!");
        }
    
    }

    3、测试API

  • 相关阅读:
    二叉树--转换二叉树(leetcode 108,leetcode 109)
    二叉树--层序遍历(leetcode 102
    二叉树--对称二叉树(leetcode 101
    数据库事务隔离
    二叉树--后序遍历的递归和非递归(leetcode 145
    二叉树--中序遍历的递归和非递归(leetcode 94
    二叉树--先序遍历的递归和非递归(leetcode 144
    链表--排序链表(leetcode 148
    接口的调用
    查锁表以及杀进程
  • 原文地址:https://www.cnblogs.com/LiveYourLife/p/9172626.html
Copyright © 2011-2022 走看看