非空验证代码:
public class StringUtils {
public class StringUtils {
/**
* 对字符串进行非空校验*/
public static boolean isNotEmpty(String... strs){
boolean r=true;
for(String s:strs){
if(s==null || s.length()==0){
r=false;
break;
}
}
return r;
}
}
随机生成指定位数的数字:
public class NumUtils {
/**
* 随机生成指定位数的数字*/
public static int createNum(int len){
Random random=new Random();
return random.nextInt((int)(Math.pow(10,len)-Math.pow(10,len-1)))
+(int)Math.pow(10,len-1);
}
}
JWT算法生成令牌:
public class JwtUtils {
/**
* 生成令牌
* @param msg 内容,令牌携带的数据*/
public static String createToken(String msg){
return Jwts.builder().
signWith(SignatureAlgorithm.HS256,"studyquestion_"+System.currentTimeMillis()).
setSubject(msg).compact();
}
public static void main(String[] args) {
System.err.println(createToken("测试"));
}
}
文件名的重命名:保证唯一
public class FileUtils {
/**
* 实现文件名的重命名,保证唯一性*/
public static String reName(String name){
if(name.length()> SystemConfig.FILE_LENGTH){
name=name.substring(name.length()-SystemConfig.FILE_LENGTH);
}
return UUID.randomUUID().toString().replaceAll("-","")+"_"+name;
}
}
密钥模板:实现常用加解密(SHA,AES,RSA,Base64)
public class EncryptUtil {
public static final String SHA1 = "SHA-1";
public static final String SHA256 = "SHA-256";
public static final String SHA384 = "SHA-384";
public static final String SHA512 = "SHA-512";
public static final String PUBKEY = "public_key";
public static final String PRIKEY = "private_key";
//1、编码格式
//base64 编码
public static String base64enc(String msg) {
return Base64.getEncoder ().encodeToString (msg.getBytes ());
}
private static String base64encByte(byte[] msg) {
return Base64.getEncoder ().encodeToString (msg);
}
private static byte[] base64decByte(String msg) {
return Base64.getDecoder ().decode (msg);
}
//
// base64 解码
public static String base64dec(String msg) {
return new String (Base64.getDecoder ().decode (msg));
}
//MD5 摘要
public static String md5(String msg) {
try {
//创建摘要算法对象
MessageDigest messageDigest = MessageDigest.getInstance ("MD5");
messageDigest.update (msg.getBytes ());
return base64encByte (messageDigest.digest ());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace ();
}
return null;
}
//SHA 摘要 SHA-1 SHA-256 SHA-384 SHA-512
public static String sha(String type, String msg) {
try {
//创建摘要算法对象
MessageDigest messageDigest = MessageDigest.getInstance (type);
messageDigest.update (msg.getBytes ());
return base64encByte (messageDigest.digest ());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace ();
}
return null;
}
//创建 对称加密---密钥
public static String createAESKey() {
try {
//1、创建随机key
KeyGenerator generator = KeyGenerator.getInstance ("AES");
generator.init (128);
SecretKey key = generator.generateKey ();
return base64encByte (key.getEncoded ());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace ();
}
return null;
}
//AES 加密 返回的是base64格式
public static String aesenc(String key, String msg) {
SecretKeySpec secretKeySpec = new SecretKeySpec (base64decByte (key), "AES");
try {
Cipher cipher = Cipher.getInstance ("AES");
cipher.init (Cipher.ENCRYPT_MODE, secretKeySpec);
return base64encByte (cipher.doFinal (msg.getBytes ()));
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
//AES 解密 返回的是base64格式
public static String aesdec(String key, String msg) {
SecretKeySpec secretKeySpec = new SecretKeySpec (base64decByte (key), "AES");
try {
Cipher cipher = Cipher.getInstance ("AES");
cipher.init (Cipher.DECRYPT_MODE, secretKeySpec);
return new String (cipher.doFinal (base64decByte (msg)));
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
//创建-RSA 密钥 一对儿 公私钥
public static HashMap<String, String> createRSAKey() {
try {
KeyPairGenerator generator = KeyPairGenerator.getInstance ("RSA");
KeyPair keyPair = generator.generateKeyPair ();
//创建使用私钥
RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate ();
//创建使用公钥
RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic ();
HashMap<String, String> keys = new HashMap<> ();
keys.put (PUBKEY, base64encByte (publicKey.getEncoded ()));
keys.put (PRIKEY, base64encByte (privateKey.getEncoded ()));
return keys;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace ();
}
return null;
}
/**
* rsa 公钥-加密*/
public static String rsaEncPub(String key,String msg){
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(base64decByte(key));
try {
KeyFactory keyFactory = KeyFactory.getInstance ("RSA");
PublicKey publicKey = keyFactory.generatePublic (keySpec);
Cipher cipher = Cipher.getInstance ("RSA");
cipher.init (Cipher.ENCRYPT_MODE, publicKey);
return base64encByte(cipher.doFinal(msg.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//RSA 私钥-加密
public static String rsaEnc(String key, String msg) {
try {
//转换私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec (base64decByte (key));
KeyFactory keyFactory = KeyFactory.getInstance ("RSA");
PrivateKey privateKey = keyFactory.generatePrivate (keySpec);
Cipher cipher = Cipher.getInstance ("RSA");
cipher.init (Cipher.ENCRYPT_MODE, privateKey);
return base64encByte(cipher.doFinal(msg.getBytes()));
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
//RSA 公钥-解密
public static String rsaDec(String key, String msg) {
try {
//转换公钥
X509EncodedKeySpec keySpec = new X509EncodedKeySpec (base64decByte (key));
KeyFactory keyFactory = KeyFactory.getInstance ("RSA");
PublicKey publicKey = keyFactory.generatePublic (keySpec);
Cipher cipher = Cipher.getInstance ("RSA");
cipher.init (Cipher.DECRYPT_MODE, publicKey);
return new String (cipher.doFinal (base64decByte (msg)), "UTF-8");
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
/**
* RSA 私钥-解密
*/
public static String rsaDecPri(String key, String msg) {
try {
//转换私钥
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec (base64decByte (key));
KeyFactory keyFactory = KeyFactory.getInstance ("RSA");
PrivateKey privateKey = keyFactory.generatePrivate (keySpec);
Cipher cipher = Cipher.getInstance ("RSA");
cipher.init (Cipher.DECRYPT_MODE, privateKey);
return new String(cipher.doFinal(base64decByte(msg)),"UTF-8");
} catch (Exception e) {
e.printStackTrace ();
}
return null;
}
}
时间比较类:
(获取指定年的日期,比较日期是否相同,获取指定日的日期)
public class DateUtils {
/**
* 获取指定年的日期*/
public static Date getYear(int year){
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.YEAR,year);
return calendar.getTime();
}
/**
* 比如日期是否相同*/
public static boolean dateEq(Date sdate,Date edate){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(sdate).equals(sdf.format(edate));
}
/**
* 获取指定日的日期*/
public static Date getDateByDay(int day){
Calendar calendar=Calendar.getInstance();
calendar.add(Calendar.DAY_OF_MONTH,day);
return calendar.getTime();
}
}
基于反射来创建对象:
public class BeanUtils {
/**
* 基于反射实现对象的创建*/
public static <T> T copyBean(Class<T> clz, Object obj, Field[] fields){
T t= null;
try {
//实例化对象
t = clz.newInstance();
//遍历属性
for(Field f:fields){
//获取属性对象
Field field=clz.getDeclaredField(f.getName());
if(field!=null){
//设置忽略访问修饰符的校验
field.setAccessible(true);
f.setAccessible(true);
//为属性赋值
field.set(t,f.get(obj));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return t;
}
}
百度审核模板:
public class BaiduContentUtils {
//内容审核对象
public static final AipContentCensor censor=new AipContentCensor(SystemConfig.BAIDU_APPID,
SystemConfig.BAIDU_KEY,SystemConfig.BAIDU_SEC);
/**
* 图片审核*/
public static boolean imgCensor(byte[] data){
//进行图片审核
JSONObject response = censor.imageCensorUserDefined(data,null);
System.err.println(response);
//返回审核结果
return response.getInt("conclusionType")==1;
}
/**
* 文本审核*/
public static boolean textCensor(String txt){
//文本审核
JSONObject response =censor.textCensorUserDefined(txt);
//返回审核结果
return response.getInt("conclusionType")==1;
}
}
调用短信验证码:
public class AliSmsUtils {
private static Client client;
//完成初始化
static {
Config config = new Config()
// 您的AccessKey ID
.setAccessKeyId(SystemConfig.ALI_KEY)
// 您的AccessKey Secret
.setAccessKeySecret(SystemConfig.ALI_SEC);
// 访问的域名
config.endpoint = "dysmsapi.aliyuncs.com";
try {
client=new Client(config);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 发送验证码
* @param code 验证码
* @param phone 手机号
* @param temcode 模板code*/
public static boolean sendCode(String temcode,String phone,int code){
//1.准备请求参数
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)
.setSignName("来自邢朋辉的短信")
.setTemplateCode(temcode)
.setTemplateParam("{\"code\":"+code+"}");
try {
//2.发送短信,获取响应结果
SendSmsResponse response=client.sendSms(sendSmsRequest);
//3.返回结果
return response.getBody().code.equals("OK");
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
}
云存储模板(阿里云OSS):
public class AliOssUtils {
// yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1(杭州)为例,Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
static String endpoint = "oss-cn-beijing.aliyuncs.com";
public static final String bucket="data2112";
// 创建OSSClient实例。
public static OSS ossClient ;
static {
ossClient= new OSSClientBuilder().build(endpoint, SystemConfig.ALI_KEY, SystemConfig.ALI_SEC);
}
/**
* 实现资源上传,并获取访问路径*/
public static String upload(String obj, byte[] data, Date date){
//1.实现资源上传
ossClient.putObject(bucket,obj,new ByteArrayInputStream(data));
//2.生成访问路径
return ossClient.generatePresignedUrl(bucket,obj,date).toString();
}
/**
* 实现资源的删除*/
public static boolean delete(String obj){
try{
ossClient.deleteObject(bucket,obj);
return true;
}catch (Exception e){
return false;
}
}
/**
* 验证资源是否存在*/
public static boolean exists(String obj){
return ossClient.doesObjectExist(bucket,obj);
}
/**
* 创建对象的访问链接*/
public static String createUrl(String obj,Date date){
return ossClient.generatePresignedUrl(bucket,obj,date).toString();
}
}
线程池单例化:
创建一个单线程的线程池。这个线程池只有一个核心线程在工作,也就是相当于单线程串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。
//保证类是唯一实例,用单例模式
public class ThreadPoolSingle {
public ThreadPoolExecutor poolExecutor;//原生的线程池对象
//私有构造器 这是核心
private ThreadPoolSingle(){
poolExecutor=new ThreadPoolExecutor(4,10,
3, TimeUnit.SECONDS,
new ArrayBlockingQueue<>(20),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());
}
//静态内部类 里面有一个静态的属性 属性类的对象一定是一个外部类的对象
static class ThreadPoolSingleFactory{
public static ThreadPoolSingle single=new ThreadPoolSingle();
}
//公有静态方法 (作用:获取本来对象)
public static ThreadPoolSingle getInstance(){
return ThreadPoolSingleFactory.single;
}
//新增任务
public void addTask(Runnable runnable){
poolExecutor.submit(runnable);
}
}
去魔法值配置类:
public class SystemConfig {
//阿里云账号的key和密钥
public static final String ALI_KEY="LTAI5tKz7sP4xaaRsTuxoTjx";
public static final String ALI_SEC="mFCyf0QxVmB6kGAacAxdtMqmQwcRIx";
//阿里云短信模板
public static final String ALI_SMS_RCODE="SMS_114390520";//注册
public static final String ALI_SMS_LCODE="SMS_115250125";//登录
public static final String ALI_SMS_FCODE="SMS_181545700";//密码找回
//验证码的长度
public static final int CODE_LEN=6;
//接口统一结果码
public static final int R_OK=200;
public static final int R_FAIL=400;
//正则表达式
public static final String REG_PHONE="1[3-9]{1}[0-9]{9}";
//密码的密钥
public static final String PASS_KEY="RAHW4pSvPJKOpuGGdbU+pw==";
//标记位 1有效 2无效
public static final int FLAG_OK=1;
public static final int FLAG_ERROR=2;
//自定义请求消息头
public static final String REQ_HEADER_TOKEN="sqtoken";//传输令牌
//文件名的长度
public static final int FILE_LENGTH=50;
//Oss 访问地址默认3年
public static final int OSS_URL_TIME=3;
//百度秘钥
public static final String BAIDU_APPID="17214730";
public static final String BAIDU_KEY="WnrcZnQNbveI7UG7sDroOm1K";
public static final String BAIDU_SEC="FUui3jN440l9eLN8B335C3VS62HvtafU";
//积分奖励
public static final int SIGN_SCORE_F=20;//首次签到
public static final int SIGN_SCORE_W=5;//连续1星期
public static final int SIGN_SCORE_M=20;//连续1个月
public static final int SIGN_SCORE_Y=100;//连续1年
public static final int SCORE_R=50;//注册好礼,赠送50积分
public static final int SCORE_L=1;//登陆,赠送1积分
public static final int SIGN_DAY_3=3;//
public static final int SIGN_DAY_7=7;//
public static final int SIGN_DAY_30=30;//
public static final int SIGN_DAY_365=365;//
}
SwaggerConfig配置类:
@Configuration //标记这是配置类,beans
@EnableSwagger2 //启用Swagger
public class SwaggerConfig {
/**
* 构建文档的基本信息
*/
public ApiInfo createApi(){
return new ApiInfoBuilder().description("StudyQuestion项目的接口在线文档,可以对接口进行测试等操作")
.title("StudyQuestion的在线接口文档").contact(new Contact("Java2112","http://www.qfedu.com","xingfei_work@163.com"))
.version("1.0.0").build();
}
/**
* 就是ioc创建实例 修饰方法 方法必须返回对象
*/
@Bean
public Docket createDocket(){
return new Docket(DocumentationType.SWAGGER_2).apiInfo(createApi())
.select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
.build();
}
}
RedisKeyConfig(redis配置类)
public class RedisKeyConfig {
//验证码
//String类型 有效期 value 存储验证码
public static final String SMS_RCODE="sq:sms:rcode:";//追加手机号
public static final int SMS_RCODE_TIME=600;//对应的有效期
public static final String SMS_LCODE="sq:sms:lcode:";//追加手机号
public static final String SMS_FCODE="sq:sms:fcode:";//追加手机号
//登陆 存储 String 类型 存储什么内容
//用于通过令牌获取在线的用户信息的
public static final String USER_TOKEN="sq:auth:token:";//追加令牌,值存储对应的用户id
//用于校验手机号是不是唯一登陆的
public static final String USER_PHONE="sq:auth:phone:";//追加手机号,值存储对应的令牌
public static final int USER_TOKEN_TIME=1800;//对应的有效期
//Hash类型,记录uid对应的手机号,永久有效
public static final String USER_UIDS="sq:user:ids";
}
SpringBoot项目(用于扫描Dao层配置类)
@Configuration
@MapperScan(basePackages = "com.feri.sq.dao")
public class MybatisConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
过滤器(:令牌续命)
@Component
@WebFilter("*.do")
public class TokenTimeFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
Filter.super.init(filterConfig);
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//实现令牌的自动延期,如果当前请求携带的有令牌,那么就自动续命30分钟
HttpServletRequest request=(HttpServletRequest) servletRequest;
//获取令牌
String token=request.getHeader(SystemConfig.REQ_HEADER_TOKEN);
//校验是否传递令牌
if(StringUtils.isNotEmpty(token)){
//验证令牌是否存在
if(JedisUtils.exists(RedisKeyConfig.USER_TOKEN+token)){
//存在令牌,则续命
JedisUtils.expire(RedisKeyConfig.USER_TOKEN+token,RedisKeyConfig.USER_TOKEN_TIME);
//原则上查询数据库,直接使用Redis
String phone=JedisUtils.getHash(RedisKeyConfig.USER_UIDS,
JedisUtils.getString(RedisKeyConfig.USER_TOKEN+token));
//手机号那个key也需要续命
JedisUtils.expire(RedisKeyConfig.USER_PHONE+phone,RedisKeyConfig.USER_TOKEN_TIME);
//对应的uid,新增到请求消息头中
request.newPushBuilder().addHeader("uid",JedisUtils.getString(RedisKeyConfig.USER_TOKEN+token));
}
}
//放行
filterChain.doFilter(request, servletResponse);
}
@Override
public void destroy() {
Filter.super.destroy();
}
}
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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.feri.sq</groupId>
<artifactId>StudyQuestion</artifactId>
<version>1.0.0</version>
<!-- SpringBoot项目的标识-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.8</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<!-- springmvc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- 数据库连接池:Druid-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
<!-- Mybatis-Plus简化JDBC,实现数据库操作-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.4</version>
</dependency>
<!-- 简化实体类,通过注解实现getter和setter等方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- 接口在线文档-->
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<!-- Jedis 操作Redis的框架-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
<!-- 阿里云对象存储-OSS -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.10.2</version>
</dependency>
<!-- 阿里云-短信服务SMS -->
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.8</version>
</dependency>
<!-- Jwt-->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<!-- 百度内容审核-人工智能 -->
<dependency>
<groupId>com.baidu.aip</groupId>
<artifactId>java-sdk</artifactId>
<version>4.16.5</version>
</dependency>
<!-- 单元测试-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>