The way of springboot for beginners and the construction of background restfull API

Keywords: Java git github

0. Preface

In the development system, the front and back ends are separated, and the back end generally returns RESTfull API. The front end calls API to build UI, which is separated from each other and completely independent from each other;

In the background API, we generally return the result code, prompt information and data, as shown in the figure:

 

Let's build a complete API to separate the back end from the front end

 

I. construction of RESTfull API

1. Add IErrorCode interface

package com.anson.common.result;
/**
 * @Author anson
 * @Description 1,Result code interface
 * @Date 2019/12/10 10:50
*/
public interface IErrorCode {
    long getCode();
    String getMessage();
}

2. Add result message enumeration ResultCode

package com.anson.common.result;

/**
 * @Author anson
 * @Description Result message enumeration
 * @Date 2019/12/10 22:05
*/
public enum ResultCode  implements IErrorCode
{
    // Data operation message definition
    SUCCESS(200, "success!"),
    BODY_NOT_MATCH(400,"The requested data format does not match!"),
    UNAUTHORIZED(401,"Not logged in or token Expired!"),
    FORBIDDEN(403, "No permission"),
    NOT_FOUND(404, "The resource was not found!"),
    FAILED(500, "Server internal error!"),
    SERVER_BUSY(503,"The server is busy. Please try again later!");

    private long code;
    private String message;

    private ResultCode(long code, String message) {
        this.code = code;
        this.message = message;
    }

    public long getCode() {
        return code;
    }

    public String getMessage() {
        return message;
    }
}

3. Add ResultBody

package com.anson.common.result;

/**
 * @description: API Return result entity
 * @author: anson
 * @Date: 2019/12/10 10:54
 */


public class ResultBody<T>
{
    private long code;
    private String message;
    private T data;

    protected ResultBody() {
    }

    protected ResultBody(long code, String message, T data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    /**
     * Results returned successfully
     *
     * @param data Acquired data
     */
    public static <T> ResultBody<T> success(T data) {
        return new ResultBody<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
    }

    /**
     * Results returned successfully
     *
     * @param data    Acquired data
     * @param message Tips
     */
    public static <T> ResultBody<T> success(T data, String message) {
        return new ResultBody<T>(ResultCode.SUCCESS.getCode(), message, data);
    }

    /**
     * Failure return result
     *
     * @param errorCode Error code
     */
    public static <T> ResultBody<T> failed(IErrorCode errorCode) {
        return new ResultBody<T>(errorCode.getCode(), errorCode.getMessage(), null);
    }

    /**
     * Failure return result
     *
     * @param message Tips
     */
    public static <T> ResultBody<T> failed(String message) {
        return new ResultBody<T>(ResultCode.FAILED.getCode(), message, null);
    }

    /**
     * Failure return result
     */
    public static <T> ResultBody<T> failed() {
        return failed(ResultCode.FAILED);
    }

    /**
     * Parameter validation failure return result
     */
    public static <T> ResultBody<T> validateFailed() {
        return failed(ResultCode.NOT_FOUND);
    }

    /**
     * Parameter validation failure return result
     *
     * @param message Tips
     */
    public static <T> ResultBody<T> validateFailed(String message) {
        return new ResultBody<T>(ResultCode.NOT_FOUND.getCode(), message, null);
    }

    /**
     * No login returned results
     */
    public static <T> ResultBody<T> unauthorized(T data) {
        return new ResultBody<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
    }

    /**
     * Unauthorized return results
     */
    public static <T> ResultBody<T> forbidden(T data) {
        return new ResultBody<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
    }

    public long getCode() {
        return code;
    }

    public void setCode(long code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

4. Add entity class, dao and service

Slightly, see the code specifically, which is consistent with the previous sections

5. Write controller

    //--------------------------------API test-------------------

    //1,according to ID Get a single user
    @ApiOperation(value = "Get users", notes = "according to id Query user information")
    @ApiImplicitParam(name = "id", value = "user id", required=true, dataType="int") //API parameter
    @RequestMapping(value="/user/{id}",method= RequestMethod.GET)
    public ResultBody getUserById(int id)
    {
        User user = userservice.selectByPrimaryKey(id);
        return  ResultBody.success(user,"Single information obtained successfully");
    }

    //2,Get all users
    @ApiOperation(value = "Get all users", notes = "Get all users")
    @RequestMapping(value="/userall",method= RequestMethod.GET)
    public ResultBody getUserAll()
    {
        List<User> users = userservice.getAll();
        return  ResultBody.success(users,"Get all user information successfully");
    }

All right, over

 

2. Run the test and execute the test in swagger. The results are as follows

 

 

 

 

{
  "code": 200,
  "data": [
    {
      "id": 1,
      "password": "123",
      "realname": "Zhang San",
      "username": "anson"
    },
    {
      "id": 2,
      "password": "123",
      "realname": "Li Si",
      "username": "Alex"
    },
    {
      "id": 3,
      "password": "123",
      "realname": "Wang Wu",
      "username": "kks"
    },
    {
      "id": 4,
      "password": "000",
      "realname": "Zhao Liu",
      "username": "eee"
    }
  ],
  "message": "Get all user information successfully"
}

 

GIT source address: https://github.com/anson-yang/cloverDemo.git

Posted by sssphp on Wed, 18 Dec 2019 14:48:56 -0800