web 项目脚手架设计及实操

前言

小项目无架构就是最好的架构,项目小,需要快速响应,如果什么都按规范来实践,等真正开始写业务逻辑,已经浪费了很多的时间,往往市场是不会给我们留太多的时间去思考。

这里的架构只是自己对代码结构的约束,通用模块的处理方法

web 项目脚手架设计

本章设计一个前后端分离的脚手架项目,里面有些业界约定成俗的,当然你可以不按照我的设计也能写出很好的 web 项目,在 github 上分析了大多十来个项目,基本都差不多。

Web 服务架构

对于具体选择 SSM/SSH 或者其他什么技术框架,不在我的讨论范畴,仁者见仁智者见智。

服务端

  • 登录权限校验拦截(包括 session 超时)
  • 统一返回值
  • 系统跨域配置
  • 异常(页面和接口)配置

前端

  • 请求拦截器统一处理
  • 前端代理设置
  • 前端统一权限方案

实操

smart-rest-spring-boot

Quickstart

首先在 pom 文件中添加:

<dependencies>
<dependency>
<groupId>top.trumandu</groupId>
<artifactId>smart-rest-spring-boot</artifactId>
<version>0.0.1</version>
</dependency>
</dependencies>

Feature

统一结果

默认所有的返回值都会格式化为以下格式,data 为方法返回数据

//正常结果
{
"code": 200,
"message": "OK",
"data": "hello"
}
//异常结果
{
"code": 500,
"message": "Internal Server Error"
}

如果接口有特殊要求,可以使用注解@IgnoreRestResult取消强制转换。

统一异常

默认拦截部分常见异常:

  • globalExceptionHandler 未知异常使用这个作为兜底方案
  • MethodArgumentNotValidException 参数校验异常
  • BusinessException 自定义业务异常
  • NoHandlerFoundException
  • HttpRequestMethodNotSupportedException
  • HttpMediaTypeNotSupportedException
  • HttpMessageNotReadableException
参数校验

使用参数@Valid

@PostMapping("/hello/info")
public Response info(@RequestBody @Valid Hello hello) {
return Response.ok().message("hello world!");
}
public class Hello {
@NotNull
@Size(min = 1, max = 10, message = "info length must in 1-10")
private String info;
@NotEmpty(message = "name must not be empty.")
private String name;
@NotNull(message = "length 不能为null.")
@Min(1)
@Max(12)
private int length;
}

除此以外还可以通过Assert断言才对于一些参数校验

统一配置

支持跨越

rest api 增加前缀

RestController 类下的 api 默认增加/api前缀

日志
常用工具
  • Assert
  • RestClient
  • EnumCache
  • BeanUtil
  • IpUtils
  • SmartDigestUtils