Spring-Custom之spring-custom-web

Spring-Custom之spring-custom-web

  Spring-Custom是基於springboot開發的一些組件,自定義的一些規則規範開發過程.。spring-custom-web主要是對VO、Controller(RestController)做的一些封裝。

版本說明

基於springboot 2.1.4.RELEASE

 	<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

具體代碼可以查看
https://gitee.com/cjx913/spring-custom-web.git

配置文件的配置項

spring:
  custom:
    web:
    #返回的數據帶有msg屬性,默認是msg
      message: message
     #返回的數據帶有code屬性,默認是code
      code: code
      #表示路由,主要是對view的路徑解析
      router:
        views:
          login: login #login.html對應的url是login
          register: register
        children:
        - path: manager
          children:
            - path: user
              views:
                add: user_add,userAdd,user.html  #  manager/user/add.html對應的url是/user_add和/userAdd和/user.html
                delete: user_delete
            - path: order
              views:
                add: order_add
                delete: order_delete

是入口類帶上@EnableCustomWeb註解開啓spring-custom-web功能

@SpringBootApplication
@RestController
@EnableCustomWeb
public class ResultTest {
    @Autowired
    private ResultBuilder resultBuilder;

    public static void main(String[] args) {
        SpringApplication.run(ResultTest.class, args);
    }

    @GetMapping("/test")
    public ResultEntity test(HttpSession session) {
        Result result = resultBuilder.build();
        result.addHeaders("header", "asdsadsda").addHeaders("header", "assafasggq12412")
                .setHeaders("header1", "asasdsadsad").setHeaders("header1", "a124123sasdsadsad")
                .addHeaders("sessionid", session.getId())
                .putBody("key", "asdasf")
                .putBody("name", "nasd");
        return result.resultEntity(StatusCode.SELECT_SUCCESS, "saagasdasd", HttpStatus.OK);
    }

    @PostMapping("/user")
    public ResultEntity user(@RequestBody UserBaseQueryVO userBaseQueryVO) {
        Result result = resultBuilder.build();
        User user = new User();
        user.setUsername("cjx913");
        user.setPassword("cjx913");
        User entity = userBaseQueryVO.getEntity();
        result.putBody("user", entity);
        return result.resultEntity();
    }
}

ResultEntity
public class ResultEntity extends ResponseEntity {…}
Result是Map<String,Object>,做了一些封裝

public class Result extends HashMap <String, Object> {
    protected String DEFAULT_CODE = "code";
    protected String DEFAULT_MSG = "msg";

    Result() {

    }

    private MultiValueMap <String, String> headers = new HttpHeaders();

    public ResultEntity resultEntity() {
        return resultEntity(HttpStatus.OK);
    }

    public ResultEntity resultEntityInternalServerError() {
        return resultEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public ResultEntity resultEntity(HttpStatus status) {
        return resultEntity(null, null, status);
    }

    public ResultEntity resultEntity(Integer code, String msg) {
        return resultEntity(code, msg, HttpStatus.OK);
    }

    public ResultEntity resultEntityInternalServerError(Integer code, String msg) {
        return resultEntity(code, msg, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public ResultEntity resultEntity(Integer code, String msg, HttpStatus status) {
        if (status == null) {
            throw new ResponseException("HttpStatus can not be null");
        }
        if (msg != null) {
            this.putBody(DEFAULT_MSG, msg);
        }
        if (code != null) {
            this.putBody(DEFAULT_CODE, code);
        }
        if (headers == null || headers.isEmpty()) {
            return new ResultEntity(this, status);
        } else {
            return new ResultEntity(this, headers, status);
        }
    }

    public Result setCode(Integer code) {
        putBody(DEFAULT_CODE, code);
        return this;
    }

    public Result setMsg(String msg) {
        putBody(DEFAULT_MSG, msg);
        return this;
    }

    public Result putBody(String key, Object value) {
        this.put(key, value);
        return this;
    }

    public Result removeBody(String key) {
        this.remove(key);
        return this;
    }

    public Result addHeaders(String key, String value) {
        this.headers.add(key, value);
        return this;
    }

    public Result setHeaders(String key, String value) {
        this.headers.set(key, value);
        return this;
    }

    public Result removeHeaders(String key) {
        this.headers.remove(key);
        return this;
    }

    public MultiValueMap <String, String> getHeaders() {
        return headers;
    }

    public Result setHeaders(MultiValueMap <String, String> headers) {
        this.headers = headers;
        return this;
    }

    public Result addHeaders(MultiValueMap <String, String> headers) {
        this.headers.addAll(headers);
        return this;
    }

    public String getDefaultCode() {
        return DEFAULT_CODE;
    }

    public void setDefaultCode(String defaultCode) {
        Integer code = (Integer) this.get(DEFAULT_CODE);
        if (code != null) {
            this.removeBody(DEFAULT_CODE);
            DEFAULT_CODE = defaultCode;
            this.setCode(code);
        } else {
            DEFAULT_CODE = defaultCode;
        }
    }

    public String getDefaultMsg() {
        return DEFAULT_MSG;
    }

    public void setDefaultMsg(String defaultMsg) {
        String msg = (String) this.get(DEFAULT_MSG);
        if (msg != null) {
            this.removeBody(DEFAULT_MSG);
            DEFAULT_MSG = defaultMsg;
            this.setMsg(msg);
        } else {
            DEFAULT_MSG = defaultMsg;
        }
    }
}

自定義了一些狀態碼StatusCode

package cn.cjx913.spring_custom.web;

/**
 * 操作狀態碼
 * @author cjx913
 * @version 1.0
 * @since 2.1.2.RELEASE
 */
public class StatusCode {
    /**
     * 查詢成功
     */
    public static final Integer SELECT_SUCCESS = 101;
    /**
     * 查詢成功,但無數據
     */
    public static final Integer SELECT_SUCCESS_NO_DATA = 102;
    /**
     * 查詢失敗
     */
    public static final Integer SELECT_FAIL = 103;
    /**
     * 插入成功
     */
    public static final Integer INSERT_SUCCESS = 104;
    /**
     * 插入失敗
     */
    public static final Integer INSERT_FAIL = 105;
    /**
     * 更新成功
     */
    public static final Integer UPDATE_SUCCESS = 106;
    /**
     * 更新失敗
     */
    public static final Integer UPDATE_FAIL = 107;
    /**
     * 刪除成功
     */
    public static final Integer DELETE_SUCCESS = 108;
    /**
     * 刪除失敗
     */
    public static final Integer DELETE_FAIL = 109;


    /**
     * 登陸成功
     */
    public static final Integer LOGIN_SUCCESS = 210;
    /**
     * 登陸失敗
     */
    public static final Integer LOGIN_FAIL = 211;
    /**
     * 登陸失敗,用戶不存在
     */
    public static final Integer LOGIN_FAIL_UNREGISTER = 212;
    /**
     * 登陸失敗,無效登錄憑證
     */
    public static final Integer LOGIN_FAIL_INVALID_CERTIFICATE = 213;
    /**
     * 登陸失敗,未知登錄類型
     */
    public static final Integer LOGIN_FAIL_UNKONWN_LOGIN_TYPE = 214;
    /**
     * 註冊成功
     */
    public static final Integer REFISTER_SUCCESS = 220;
    /**
     * 註冊失敗
     */
    public static final Integer REFISTER_FAIL = 221;
    /**
     * 註冊失敗,用戶已存在
     */
    public static final Integer REFISTER_FAIL_EXISTED_USER = 222;
    /**
     * 註冊失敗,保存用戶數據錯誤
     */
    public static final Integer REFISTER_FAIL_ERROR_SAVE_USER_DATA = 223;
    /**
     * 註冊失敗,未知註冊類型
     */
    public static final Integer REGISTER_FAIL_UNKONWN_REGISTER_TYPE = 224;

    /**
     * 有效的session
     */
    public static final Integer SESSION_VALID = 301;
    /**
     * 無效的session
     */
    public static final Integer SESSION_INVALID = 302;
    /**
     * 有效的token
     */
    public static final Integer TOKEN_VALID = 311;
    /**
     * 無效的token
     */
    public static final Integer TOKEN_INVALID = 312;
    /**
     * 有效的驗證碼
     */
    public static final Integer VERIFICATION_CODE_VALID = 321;
    /**
     * 無效的驗證碼
     */
    public static final Integer VERIFICATION_CODE_INVALID = 322;

    /**
     * 未知錯誤
     */
    public static final Integer ERROR_UNKONWN = 900;
    /**
     * 請求錯誤
     */
    public static final Integer ERROR_REQUSET = 910;
    /**
     * 請求參數錯誤
     */
    public static final Integer ERROR_REQUSET_PARAMETER = 911;
    /**
     * 響應錯誤
     */
    public static final Integer ERROR_RESPONSE = 920;

    /**
     * 文件上傳錯誤
     */
    public static final Integer ERROR_FILR_UPLOAD = 970;
    /**
     * 文件下載錯誤
     */
    public static final Integer ERROR_FILR_DOWNLOAD = 980;
    /**
     * 全局異常
     */
    public static final Integer ERROR_GLOBAL_EXCEPTIONS = 999;
}

使用ResultBuilder來創建Result,使用@Autowrite注入的,能夠使它跟配置文件的code,message一致

	@Autowired
    private ResultBuilder resultBuilder;
    
	......
	
	Result result = resultBuilder.build();

Result提供轉換成ResultEntity的方法

	public ResultEntity resultEntity() {
        return resultEntity(HttpStatus.OK);
    }

    public ResultEntity resultEntityInternalServerError() {
        return resultEntity(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public ResultEntity resultEntity(HttpStatus status) {
        return resultEntity(null, null, status);
    }

    public ResultEntity resultEntity(Integer code, String msg) {
        return resultEntity(code, msg, HttpStatus.OK);
    }

    public ResultEntity resultEntityInternalServerError(Integer code, String msg) {
        return resultEntity(code, msg, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    public ResultEntity resultEntity(Integer code, String msg, HttpStatus status) {
        if (status == null) {
            throw new ResponseException("HttpStatus can not be null");
        }
        if (msg != null) {
            this.putBody(DEFAULT_MSG, msg);
        }
        if (code != null) {
            this.putBody(DEFAULT_CODE, code);
        }
        if (headers == null || headers.isEmpty()) {
            return new ResultEntity(this, status);
        } else {
            return new ResultEntity(this, headers, status);
        }
    }

還有對查詢和結果做了一些規定

package cn.cjx913.spring_custom.web.entity;

import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

@Setter
@Getter
/**
 * 查詢參數封裝
 */
public class BaseQueryVO<T>  implements Serializable {


    protected T entity;

    /**
     * 數據有效性
     */
    protected Boolean available;

    /**
     * 搜索文本
     */
    protected String searchText;
    /**
     * 排序
     */
    protected String sortName;
    /**
     * 排序
     */
    protected String sortOrder = "asc";

    //分頁
    /**
     * 分頁查詢的頁碼
     */
    protected Integer pageNumber = 1;
    /**
     * 分頁查詢的每頁的數據
     */
    protected Integer pageSize = 15;

    /**
     * 分頁查詢的每頁的數據
     */
    protected Integer limit = 15;
    /**
     * 分頁查詢的起始號
     */
    protected Integer offset = 0;

    protected Map <String, Object> parameters = new HashMap <>();

    public BaseQueryVO() {

    }

    public BaseQueryVO(T entity) {
        this.entity = entity;
    }
}

package cn.cjx913.spring_custom.web.entity;

import lombok.Getter;
import lombok.Setter;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Setter
@Getter
/**
 * 查詢結果封裝
 */
public class BaseResultVO<T> implements Serializable {
    protected T row;
    protected List <T> rows;

    /**
     * 查詢得到總數據的行數
     */
    protected Long total;

    /**
     * 增刪改受影響的行數
     */
    protected Long count;

    protected Double sum;

    protected Double average;

    protected Map <String, Object> results = new HashMap <>();

    public Boolean hasData() {
        return row != null ? true : false;
    }

    public Boolean hasDatas() {
        if (CollectionUtils.isEmpty(rows)) {
            return false;
        } else {
            return true;
        }
    }

}

WebMvcCustomConfigurer

public class WebMvcCustomConfigurer implements WebMvcConfigurer{}
在這裏處理router的,需要把他注入spring容器

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章