作用:
存放一些常用的工具类,以便提供给其他工程调用
整体结构
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.yzm</groupId>
<artifactId>security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<relativePath>../pom.xml</relativePath> <!-- lookup parent from repository -->
</parent>
<artifactId>common</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>common</name>
<description>Demo project for Spring Boot</description>
</project>
代码自动生成器
package com.yzm.common.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Generator {
//创建人
private static final String author = "Yzm";
//需要生成实体类等基础信息的表名,多个用逗号隔开
private static final String[] tables = {"user", "role", "permissions"};
//生成文件指定在哪个目录下
private static final String baoPath = "com.yzm.security01";
private static final String module = "security01";
//数据源连接
private static final String driverName = "com.mysql.cj.jdbc.Driver";
private static final String url = "jdbc:mysql://localhost:3306/test04?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
private static final String username = "root";
private static final String password = "root";
public static void main(String[] args) {
//全局配置(必须)
GlobalConfig globalConfig = globalConfig();
//数据源配置(必须)
DataSourceConfig dataSourceConfig = dataSourceConfig();
//策略配置(必须)
StrategyConfig strategyConfig = strategyConfig();
//包名策略配置(必须)
PackageConfig packageConfig = packageConfig();
//自定义配置(可无)
InjectionConfig injectionConfig = injectionConfig();
//模板配置(可无)
TemplateConfig templateConfig = templateConfig();
//整合配置
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(globalConfig)
.setDataSource(dataSourceConfig)
.setStrategy(strategyConfig)
.setPackageInfo(packageConfig)
.setCfg(injectionConfig)
.setTemplate(templateConfig)
.setTemplateEngine(new FreemarkerTemplateEngine());
autoGenerator.execute();
}
/**
* 全局配置
*/
private static GlobalConfig globalConfig() {
String path = StringUtils.hasLength(module) ? "/" + module + "/src/main/java" : "/src/main/java";
return new GlobalConfig()
//是否开启 ActiveRecord 模式
.setActiveRecord(false)
//是否开启 Kotlin 模式
.setKotlin(false)
.setAuthor(author)
//生成文件的输出目录
.setOutputDir(System.getProperty("user.dir") + path)
//是否打开输出目录
.setOpen(false)
//文件是否覆盖
.setFileOverride(false)
//主键策略
.setIdType(IdType.AUTO)
//默认情况下生成的Service接口的名字首字母都带有I
.setServiceName("%sService")
//是否生成基本的sql中的ResultMap
.setBaseResultMap(true)
//是否生成基本的sql列
.setBaseColumnList(true)
//实体类是否使用swagger注解
.setSwagger2(false)
//是否在xml中添加二级缓存配置
.setEnableCache(false);
}
/**
* 数据源配置
*/
private static DataSourceConfig dataSourceConfig() {
return new DataSourceConfig()
.setDbType(DbType.MYSQL)
.setDriverName(driverName)
.setUrl(url)
.setUsername(username)
.setPassword(password);
}
/**
* 策略配置(数据库表<-->实体类,表字段<-->类属性)
*/
private static StrategyConfig strategyConfig() {
return new StrategyConfig()
//实体是否链式模型
.setChainModel(true)
//controller层使用@RestController注解
.setRestControllerStyle(true)
//实体是否使用Lombok工具
.setEntityLombokModel(true)
//实体是否生成字段注释
.setEntityTableFieldAnnotationEnable(true)
//指定实体类需要继承的父类
//.setSuperEntityClass(BaseEntity.class)
//逻辑删除属性名称
.setLogicDeleteFieldName("deleted")
//数据库表名,有多个用逗号隔开
.setInclude(tables)
//表前缀、字段前缀
//.setTablePrefix("")
//.setFieldPrefix("")
//数据库表名跟实体类名映射的命名策略
.setNaming(NamingStrategy.underline_to_camel)
//数据库表字段名跟实体类属性名映射的命名策略
.setColumnNaming(NamingStrategy.underline_to_camel);
}
/**
* 包名策略配置
*/
private static PackageConfig packageConfig() {
return new PackageConfig()
.setModuleName("")
.setParent(baoPath)
.setEntity("entity")
.setMapper("mapper")
.setService("service")
.setServiceImpl("service.impl")
.setController("controller")
.setXml("mapper.xml");
}
/**
* 模板配置
*/
private static TemplateConfig templateConfig() {
//配置模板
return new TemplateConfig()
//配置自定义输出模板
//指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
//.setEntity("templates/entity2.java");
//.setService();
//.setController();
.setXml(null);
}
/**
* 自定义配置
*/
private static InjectionConfig injectionConfig() {
//自定义配置,该对象可以传递到模板引擎通过 cfg.xxx 引用
InjectionConfig injectionConfig = new InjectionConfig() {
@Override
public void initMap() {
Map<String, Object> map = new HashMap<>();
map.put("abc", this.getConfig().getGlobalConfig().getAuthor() + "-mp");
this.setMap(map);
}
};
/* 如果模板引擎是 freemarker
String templatePath = "/templates/mapper.xml.ftl";
//如果模板引擎是 velocity
String templatePath = "/templates/mapper.xml.vm";*/
//自定义输出配置
List<FileOutConfig> focList = new ArrayList<>();
//自定义配置会被优先输出
String path = StringUtils.hasLength(module) ? "/" + module + "/src/main/resources/mapper/" : "/src/main/resources/mapper/";
focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
@Override
public String outputFile(TableInfo tableInfo) {
//自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
return System.getProperty("user.dir") + path + "/" + tableInfo.getEntityName() + "Mapper.xml";
}
});
injectionConfig.setFileOutConfigList(focList);
return injectionConfig;
}
}
页面响应对象
package com.yzm.common.entity;
import lombok.Data;
import java.io.Serializable;
/**
* HTTP结果封装
*/
@Data
public class HttpResult implements Serializable {
private static final long serialVersionUID = -4661003546224340096L;
private int code;
private String msg;
private Object data;
public HttpResult(int code, String msg) {
this(code, msg, null);
}
public HttpResult(MessageEnum message) {
this(message.code(), message.message(), null);
}
public HttpResult(MessageEnum message, Object data) {
this(message.code(), message.message(), data);
}
public HttpResult(int code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public static HttpResult error() {
return new HttpResult(MessageEnum.INTERNAL_SERVER_ERROR);
}
public static HttpResult error(String msg) {
return new HttpResult(500, msg);
}
public static HttpResult error(int code, String msg) {
return new HttpResult(code, msg);
}
public static HttpResult ok() {
return new HttpResult(MessageEnum.SUCCESS);
}
public static HttpResult ok(String msg) {
return new HttpResult(200, msg);
}
public static HttpResult ok(Object data) {
return new HttpResult(MessageEnum.SUCCESS, data);
}
}
响应信息枚举对象
package com.yzm.common.entity;
public enum MessageEnum {
SUCCESS(200, "操作成功"),
BAD_REQUEST(400, "请求参数错误"),
NO_ACCESS(403, "无权访问"),
NOT_FOUNT(404, "请求路径错误"),
INTERNAL_SERVER_ERROR(500, "操作失败");
private final int code;
private final String message;
MessageEnum(int code, String message) {
this.code = code;
this.message = message;
}
public int code() {
return this.code;
}
public String message() {
return this.message;
}
}
分页响应对象
package com.yzm.common.entity;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class PageResult<T> implements Serializable {
private static final long serialVersionUID = -7016165505111217188L;
// 显示数量
private long count;
// 当前页
private long current;
// 总数量
private long total;
// 总页数
private long pages;
// 数据
private List<T> list;
public PageResult() {
}
public PageResult(IPage<?> page, List<T> list) {
this.count = page.getSize();
this.current = page.getCurrent();
this.total = page.getTotal();
this.pages = page.getPages();
this.list = list;
}
}
分页搜索对象
package com.yzm.common.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
public class PageSearch<T> implements Serializable {
private static final long serialVersionUID = 2083993467648559840L;
private Integer page = 1;
private Integer size = 10;
private T where;
public PageSearch(Integer page, Integer size, T t) {
this.page = page;
this.size = size;
this.where = t;
}
}
Http工具类
package com.yzm.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.yzm.common.entity.HttpResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
/**
* HTTP工具类
*/
public class HttpUtils {
/**
* 获取HttpServletRequest对象
*/
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
}
/**
* 获取HttpServletResponse对象
*/
public static HttpServletResponse getHttpServletResponse() {
return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getResponse();
}
/**
* 输出信息到浏览器
*/
public static void successWrite(HttpServletResponse response, Object data) throws IOException {
write(response, 200, "操作成功", data);
}
public static void errorWrite(HttpServletResponse response, String msg) throws IOException {
write(response, 500, msg, null);
}
public static void errorWrite(HttpServletResponse response, int code, String msg) throws IOException {
write(response, code, msg, null);
}
private static void write(HttpServletResponse response, int code, String msg, Object data) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
HttpResult result = new HttpResult(code, msg, data);
response.getWriter().print(JSONObject.toJSONString(result, true));
response.getWriter().flush();
response.getWriter().close();
}
}