From 9edb2a4a6f39b24ce4b7003a1f07013643b0ee46 Mon Sep 17 00:00:00 2001 From: hz21056617 <1IB76X4g7T> Date: Fri, 31 Dec 2021 17:53:39 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E9=83=A8=E5=88=86=E9=80=9A?= =?UTF-8?q?=E7=94=A8=E5=8A=9F=E8=83=BD=20tmp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 1 + pom.xml | 41 ++++ .../com/aos/common/annotation/CostTime.java | 19 ++ .../com/aos/common/aop/CostTimeAspect.java | 41 ++++ .../common/aop/GlobalExceptionHandler.java | 89 ++++++++ .../java/com/aos/common/aop/WebLogAspect.java | 137 +++++++++++ .../common/domain/exception/BizException.java | 70 ++++++ .../aos/common/domain/result/ResultCode.java | 22 ++ .../domain/result/ResultCodeInterface.java | 27 +++ .../aos/common/domain/result/WebResponse.java | 52 +++++ .../aos/common/domain/result/WebResult.java | 48 ++++ .../common/interceptor/LogInterceptor.java | 65 ++++++ .../com/aos/common/utils/ColaBeanUtils.java | 53 +++++ .../common/utils/ColaBeanUtilsCallBack.java | 13 ++ .../aos/common/utils/IsChineseOrEnglish.java | 34 +++ .../com/aos/common/utils/RequestUtils.java | 212 ++++++++++++++++++ 16 files changed, 924 insertions(+) create mode 100644 src/main/java/com/aos/common/annotation/CostTime.java create mode 100644 src/main/java/com/aos/common/aop/CostTimeAspect.java create mode 100644 src/main/java/com/aos/common/aop/GlobalExceptionHandler.java create mode 100644 src/main/java/com/aos/common/aop/WebLogAspect.java create mode 100644 src/main/java/com/aos/common/domain/exception/BizException.java create mode 100644 src/main/java/com/aos/common/domain/result/ResultCode.java create mode 100644 src/main/java/com/aos/common/domain/result/ResultCodeInterface.java create mode 100644 src/main/java/com/aos/common/domain/result/WebResponse.java create mode 100644 src/main/java/com/aos/common/domain/result/WebResult.java create mode 100644 src/main/java/com/aos/common/interceptor/LogInterceptor.java create mode 100644 src/main/java/com/aos/common/utils/ColaBeanUtils.java create mode 100644 src/main/java/com/aos/common/utils/ColaBeanUtilsCallBack.java create mode 100644 src/main/java/com/aos/common/utils/IsChineseOrEnglish.java create mode 100644 src/main/java/com/aos/common/utils/RequestUtils.java diff --git a/.gitignore b/.gitignore index 85e7c1d..5e07a71 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ /.idea/ +/aos-common-spring-boot-starter.iml diff --git a/pom.xml b/pom.xml index b84993f..7107a6c 100644 --- a/pom.xml +++ b/pom.xml @@ -19,6 +19,47 @@ 2.6.2 provided + + org.projectlombok + lombok + 1.18.22 + provided + + + org.aspectj + aspectjweaver + 1.9.6 + + + org.springframework + spring-webmvc + 5.3.9 + provided + + + io.github.openfeign + feign-core + 10.7.4 + provided + + + org.apache.tomcat.embed + tomcat-embed-core + 9.0.52 + provided + + + org.jboss.logging + jboss-logging + 3.4.1.Final + provided + + + ch.qos.logback + logback-classic + 1.2.3 + provided + \ No newline at end of file diff --git a/src/main/java/com/aos/common/annotation/CostTime.java b/src/main/java/com/aos/common/annotation/CostTime.java new file mode 100644 index 0000000..bc0b39f --- /dev/null +++ b/src/main/java/com/aos/common/annotation/CostTime.java @@ -0,0 +1,19 @@ +package com.aos.common.annotation; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * 获取方法运行时间的注解 + * @ClassName: CostTime + * @Date: 2021/12/6 13:25 + * @author wangyl + * @version V1.0 + */ +@Target({ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +public @interface CostTime { + +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/aop/CostTimeAspect.java b/src/main/java/com/aos/common/aop/CostTimeAspect.java new file mode 100644 index 0000000..8f1cce5 --- /dev/null +++ b/src/main/java/com/aos/common/aop/CostTimeAspect.java @@ -0,0 +1,41 @@ +package com.aos.common.aop; + +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.springframework.stereotype.Component; + +/** + * 打印运行耗时 + * @ClassName: CostTimeAspect + * @Date: 2021/12/6 13:23 + * @author wangyl + * @version V1.0 + */ +@Aspect +@Component +@Slf4j +public class CostTimeAspect { + /** + * 首先定义一个切点 + */ + @Pointcut("@annotation(com.hzins.features.common.service.CostTime)") + public void countTime() { + } + + @Around("countTime()") + public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable { + long beginTime = System.currentTimeMillis(); + Object obj = joinPoint.proceed(); + //获取方法名称 + String methodName = joinPoint.getSignature() + .getName(); + //获取类名称 + String className = joinPoint.getSignature() + .getDeclaringTypeName(); + log.info("\n类:[{}]\n方法:[{}]\n耗时时间为:[{}]", className, methodName, (System.currentTimeMillis() - beginTime)); + return obj; + } +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/aop/GlobalExceptionHandler.java b/src/main/java/com/aos/common/aop/GlobalExceptionHandler.java new file mode 100644 index 0000000..b7c2eb9 --- /dev/null +++ b/src/main/java/com/aos/common/aop/GlobalExceptionHandler.java @@ -0,0 +1,89 @@ +package com.aos.common.aop; + +import com.aos.common.domain.exception.BizException; +import com.aos.common.domain.result.ResultCode; +import com.aos.common.domain.result.WebResponse; +import com.aos.common.domain.result.WebResult; +import lombok.extern.slf4j.Slf4j; +import org.springframework.validation.BindingResult; +import org.springframework.web.HttpRequestMethodNotSupportedException; +import org.springframework.web.bind.MethodArgumentNotValidException; +import org.springframework.web.bind.annotation.ControllerAdvice; +import org.springframework.web.bind.annotation.ExceptionHandler; +import org.springframework.web.bind.annotation.ResponseBody; + +import javax.servlet.http.HttpServletRequest; +import java.util.Objects; + +/** + * @ClassName: GlobalExceptionHandler + * @Function: 全局返回异常 + * @Date: 2020/4/12 20:22 + * @author wangyl + * @version V1.0 + */ +@ControllerAdvice +@Slf4j +@ResponseBody +public class GlobalExceptionHandler { + + @ExceptionHandler({MethodArgumentNotValidException.class}) + public WebResult bindException(MethodArgumentNotValidException e) { + BindingResult bindingResult = e.getBindingResult(); + String msg = Objects.requireNonNull(bindingResult.getFieldError()) + .getDefaultMessage(); + log.error("参数校验异常拦截:{}", msg); + return WebResponse.WebResponse.error(msg); + } + + /** + * 处理自定义的业务异常 + * @param req + * @param e + * @return + */ + @ExceptionHandler(value = BizException.class) + public WebResult bizExceptionHandler(HttpServletRequest req, BizException e) { + log.error("异常为[{}]", e.getErrorMsg()); + return WebResponse.WebResponse.error(Objects.isNull(e.getErrorCode()) ? 500 : e.getErrorCode(), e.getErrorMsg()); + } + + + /** + * 处理空指针的异常 + * @param req + * @param e + * @return + */ + @ExceptionHandler(value = NullPointerException.class) + public WebResult exceptionHandler(HttpServletRequest req, NullPointerException e) { + log.error("发生空指针异常!原因是:", e); + return WebResponse.WebResponse.error(ResultCode.FAILED); + } + + /** + * 处理请求方法不支持的异常 + * @param req + * @param e + * @return + */ + @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class) + public WebResult exceptionHandler(HttpServletRequest req, HttpRequestMethodNotSupportedException e) { + log.error("发生请求方法不支持异常!原因是:", e); + return WebResponse.WebResponse.error(ResultCode.FAILED); + } + + /** + * 处理其他异常 + * @param req + * @param e + * @return + */ + @ExceptionHandler(value = Exception.class) + public WebResult exceptionHandler(HttpServletRequest req, Exception e) { + log.error("未知异常!原因是:", e); + return WebResponse.WebResponse.error(-1, e.getMessage()); + } + +} + \ No newline at end of file diff --git a/src/main/java/com/aos/common/aop/WebLogAspect.java b/src/main/java/com/aos/common/aop/WebLogAspect.java new file mode 100644 index 0000000..1d3c620 --- /dev/null +++ b/src/main/java/com/aos/common/aop/WebLogAspect.java @@ -0,0 +1,137 @@ +package com.aos.common.aop; + +import com.alibaba.fastjson.JSON; +import com.alibaba.fastjson.JSONObject; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.aspectj.lang.JoinPoint; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.*; +import org.springframework.stereotype.Component; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.HttpServletRequest; +import java.lang.reflect.Method; + +/** + * @author 犬小哈 (微信号:小哈学Java) + * @site www.exception.site + * @date 2019/2/12 + * @time 下午9:19 + * @discription + **/ +@Aspect +@Component +@Slf4j +public class WebLogAspect { + private static final String LINE_SEPARATOR = System.lineSeparator(); + + /** 以自定义 @WebLog 注解为切点 */ + @Pointcut("@annotation(io.swagger.annotations.ApiOperation)") + public void webLog() {} + + /** + * 在切点之前织入 + * @param joinPoint + * @throws Throwable + */ + @Before("webLog()") + public void doBefore(JoinPoint joinPoint) { + + // 开始打印请求日志 + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + HttpServletRequest request = attributes.getRequest(); + String methodDescription = getAspectLogDescription(joinPoint); + + // 打印请求相关参数 + log.info("========================================== Start =========================================="); + // 打印请求 url + log.info("URL : {}", request.getRequestURL() + .toString()); + // 打印描述信息 + log.info("Description : {}", methodDescription); + // 打印 Http method + log.info("HTTP Method : {}", request.getMethod()); + // 打印调用 controller 的全路径以及执行方法 + log.info("Class Method : {}.{}", joinPoint.getSignature() + .getDeclaringTypeName(), joinPoint.getSignature() + .getName()); + // 打印请求的 IP + log.info("IP : {}", request.getRemoteAddr()); + // 打印请求入参 + log.info("Request Args : {}", JSONObject.toJSONString(joinPoint.getArgs())); + } + + /** + * 在切点之后织入 + * @throws Throwable + */ + @After("webLog()") + public void doAfter() throws Throwable { + log.info("=========================================== End ===========================================" + LINE_SEPARATOR); + } + + /** + * 环绕 + * @param proceedingJoinPoint + * @return + * @throws Throwable + */ + @Around("webLog()") + public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable { + long startTime = System.currentTimeMillis(); + Object result = null; + result = proceedingJoinPoint.proceed(); + + // 打印出参 + try { + log.info("Response Args : {}", JSON.toJSONString(result)); + } + catch (Exception e) { + log.warn("返回结果类型转换异常", e); + } + // 执行耗时 + log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime); + return result; + } + + + /** + * 获取切面注解的描述 + * + * @param joinPoint 切点 + * @return 描述信息 + * @throws Exception + */ + public String getAspectLogDescription(JoinPoint joinPoint) { + String targetName = joinPoint.getTarget() + .getClass() + .getName(); + String methodName = joinPoint.getSignature() + .getName(); + Object[] arguments = joinPoint.getArgs(); + Class targetClass = null; + try { + targetClass = Class.forName(targetName); + } + catch (ClassNotFoundException e) { + e.printStackTrace(); + } + Method[] methods = targetClass.getMethods(); + StringBuilder description = new StringBuilder(); + for (Method method : methods){ + if (method.getName() + .equals(methodName)) { + Class[] clazzs = method.getParameterTypes(); + if (clazzs.length == arguments.length) { + description.append(method.getAnnotation(ApiOperation.class) + .value()); + break; + } + } + } + return description.toString(); + } + +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/domain/exception/BizException.java b/src/main/java/com/aos/common/domain/exception/BizException.java new file mode 100644 index 0000000..6a43904 --- /dev/null +++ b/src/main/java/com/aos/common/domain/exception/BizException.java @@ -0,0 +1,70 @@ +package com.aos.common.domain.exception; + +import com.aos.common.domain.result.ResultCodeInterface; +import lombok.Data; + +/** + * @ClassName: BizException + * @Function: 统一异常 + * @Date: 2020/4/12 20:13 + * @author wyl + * @version V1.0 + */ +@Data +public class BizException extends RuntimeException { + private static final long serialVersionUID = 1L; + + /** + * 错误码 + */ + protected Integer errorCode; + /** + * 错误信息 + */ + protected String errorMsg; + + public BizException() { + super(); + } + + public BizException(ResultCodeInterface resultCode) { + super(resultCode.getCode() + .toString()); + this.errorCode = resultCode.getCode(); + this.errorMsg = resultCode.getMsg(); + } + + public BizException(ResultCodeInterface resultCode, Throwable cause) { + super(resultCode.getCode() + .toString(), cause); + this.errorCode = resultCode.getCode(); + this.errorMsg = resultCode.getMsg(); + } + + public BizException(String errorMsg) { + super(errorMsg); + this.errorMsg = errorMsg; + } + + public BizException(Integer errorCode, String errorMsg) { + super(errorCode.toString()); + this.errorCode = errorCode; + this.errorMsg = errorMsg; + } + + public BizException(Integer errorCode, String errorMsg, Throwable cause) { + super(errorCode.toString(), cause); + this.errorCode = errorCode; + this.errorMsg = errorMsg; + } + + @Override + public String getMessage() { + return errorMsg; + } + + @Override + public Throwable fillInStackTrace() { + return this; + } +} diff --git a/src/main/java/com/aos/common/domain/result/ResultCode.java b/src/main/java/com/aos/common/domain/result/ResultCode.java new file mode 100644 index 0000000..79e894a --- /dev/null +++ b/src/main/java/com/aos/common/domain/result/ResultCode.java @@ -0,0 +1,22 @@ +package com.aos.common.domain.result; + +public enum ResultCode implements ResultCodeInterface { + SUCCEED(200, "成功"), FAILED(-1, "系统异常"); + private Integer code; + private String msg; + + ResultCode(Integer code, String msg) { + this.code = code; + this.msg = msg; + } + + @Override + public Integer getCode() { + return code; + } + + @Override + public String getMsg() { + return msg; + } +} diff --git a/src/main/java/com/aos/common/domain/result/ResultCodeInterface.java b/src/main/java/com/aos/common/domain/result/ResultCodeInterface.java new file mode 100644 index 0000000..b98aeb8 --- /dev/null +++ b/src/main/java/com/aos/common/domain/result/ResultCodeInterface.java @@ -0,0 +1,27 @@ +/** + * @Author wangyl + * @E-mail wangyl0629@foxmail.com + **/ +package com.aos.common.domain.result; + +public interface ResultCodeInterface { + /** + * @Description 获取错误码 + * @param + * @return java.lang.Integer + * @Date 2020/11/8 15:37 + * @Author wangyl + * @Version V1.0 + */ + Integer getCode(); + + /** + * @Description 获取错误信息 + * @param + * @return java.lang.String + * @Date 2020/11/8 15:38 + * @Author wangyl + * @Version V1.0 + */ + String getMsg(); +} diff --git a/src/main/java/com/aos/common/domain/result/WebResponse.java b/src/main/java/com/aos/common/domain/result/WebResponse.java new file mode 100644 index 0000000..e48702a --- /dev/null +++ b/src/main/java/com/aos/common/domain/result/WebResponse.java @@ -0,0 +1,52 @@ +package com.aos.common.domain.result; + +/** + * @ClassName: WebResponse + * @Function: 返回结果工具 + * @Date: 2020/4/12 19:58 + * @author wangyl + * @version V1.0 + */ +public enum WebResponse { + WebResponse; + + public WebResult ok() { + return new WebResult(ResultCode.SUCCEED); + } + + public WebResult ok(ResultCode resultCode, T data) { + return new WebResult(resultCode, data); + } + + public WebResult ok(T data) { + return new WebResult(ResultCode.SUCCEED, data); + } + + public WebResult error() { + return new WebResult(ResultCode.FAILED); + } + + public WebResult error(T data) { + return new WebResult(ResultCode.FAILED, data); + } + + public WebResult error(ResultCode resultCode, T data) { + return new WebResult(resultCode, data); + } + + public WebResult error(ResultCode resultCode) { + return new WebResult(resultCode); + } + + public WebResult error(Integer code, String msg) { + return new WebResult(code, msg); + } + + private WebResult WebResponse(Integer code, String msg, T data) { + return new WebResult(code, msg, data); + } + + private WebResult WebResponse(Integer code, String msg) { + return new WebResult(code, msg); + } +} diff --git a/src/main/java/com/aos/common/domain/result/WebResult.java b/src/main/java/com/aos/common/domain/result/WebResult.java new file mode 100644 index 0000000..372deb3 --- /dev/null +++ b/src/main/java/com/aos/common/domain/result/WebResult.java @@ -0,0 +1,48 @@ +package com.aos.common.domain.result; + +import lombok.Data; + +/** + * @ClassName: WebResult + * @Function: 返回对象 + * @Date: 2020/3/27 10:49 + * @author wangyl + * @version V1.0 + */ +@Data +public class WebResult { + /** + * 返回码 + */ + private Integer code; + /** + * 描述信息 + */ + private String msg; + /** + * 返回数据 + */ + private T data; + + public WebResult() { + + } + + public WebResult(Integer code, String msg, T data) { + this.code = code; + this.msg = msg; + this.data = data; + } + + public WebResult(R resultCode) { + this(resultCode, null); + } + + public WebResult(R resultCode, T data) { + this(resultCode.getCode(), resultCode.getMsg(), data); + } + + public WebResult(Integer code, String msg) { + this(code, msg, null); + } +} diff --git a/src/main/java/com/aos/common/interceptor/LogInterceptor.java b/src/main/java/com/aos/common/interceptor/LogInterceptor.java new file mode 100644 index 0000000..74fb405 --- /dev/null +++ b/src/main/java/com/aos/common/interceptor/LogInterceptor.java @@ -0,0 +1,65 @@ +package com.aos.common.interceptor; + +import feign.RequestInterceptor; +import feign.RequestTemplate; +import lombok.extern.slf4j.Slf4j; +import org.jboss.logging.MDC; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.HandlerInterceptor; +import org.springframework.web.servlet.ModelAndView; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.UUID; + +/** + * 请求增加trace.id 便于追踪 + * @ClassName: LogInterceptor + * @Date: 2021/8/29 13:58 + * @author hz21056617 + * @version V1.0 + */ +@Component +@Slf4j +public class LogInterceptor implements HandlerInterceptor, WebMvcConfigurer, RequestInterceptor { + + private final static String TRACE_ID = "trace.id"; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + registry.addInterceptor(this); + WebMvcConfigurer.super.addInterceptors(registry); + } + + @Override + public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { + String tracId = httpServletRequest.getHeader(TRACE_ID); + if (StringUtils.isEmpty(tracId)) { + tracId = UUID.randomUUID() + .toString(); + } + MDC.put(TRACE_ID, tracId); + return true; + } + + @Override + public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { + MDC.remove(TRACE_ID); + } + + @Override + public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { + + } + + @Override + public void apply(RequestTemplate requestTemplate) { + String traceId = String.valueOf(MDC.get(TRACE_ID)); + if (traceId != null) { + requestTemplate.header(TRACE_ID, traceId); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/utils/ColaBeanUtils.java b/src/main/java/com/aos/common/utils/ColaBeanUtils.java new file mode 100644 index 0000000..7072d39 --- /dev/null +++ b/src/main/java/com/aos/common/utils/ColaBeanUtils.java @@ -0,0 +1,53 @@ +package com.aos.common.utils; + +import org.springframework.beans.BeanUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Supplier; + +/** + * list拷贝 + * @ClassName: ColaBeanUtils + * @Date: 2021/8/31 10:22 + * @author hz21056617 + * @version V1.0 + */ +public class ColaBeanUtils extends BeanUtils { + + /** + * list拷贝 + * @param sources 源列表 + * @param target 拷贝到的目标列表类 + * @return java.util.List + * @Date 2021/8/16 0:11 + * @Author hz21056617 + * @Version V1.0 + */ + public static List copyListProperties(List sources, Supplier target) { + return copyListProperties(sources, target, null); + } + + /** + * list拷贝 可处理数据 + * @param sources 源列表 + * @param target 拷贝到的目标列表类 + * @param callBack 数据处理方式 + * @return java.util.List + * @Date 2021/8/16 0:11 + * @Author hz21056617 + * @Version V1.0 + */ + public static List copyListProperties(List sources, Supplier target, ColaBeanUtilsCallBack callBack) { + List list = new ArrayList<>(sources.size()); + for (S source : sources){ + T t = target.get(); + copyProperties(source, t); + if (callBack != null) { + callBack.callBack(source, t); + } + list.add(t); + } + return list; + } +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/utils/ColaBeanUtilsCallBack.java b/src/main/java/com/aos/common/utils/ColaBeanUtilsCallBack.java new file mode 100644 index 0000000..5bcb0f7 --- /dev/null +++ b/src/main/java/com/aos/common/utils/ColaBeanUtilsCallBack.java @@ -0,0 +1,13 @@ +package com.aos.common.utils; + +/** + * @ClassName: ColaBeanUtilsCallBack + * @Function: list拷贝的回调方法 + * @Date: 2021/8/31 10:21 + * @author hz21056617 + * @version V1.0 + */ +@FunctionalInterface +public interface ColaBeanUtilsCallBack { + void callBack(S t, T s); +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/utils/IsChineseOrEnglish.java b/src/main/java/com/aos/common/utils/IsChineseOrEnglish.java new file mode 100644 index 0000000..1f80478 --- /dev/null +++ b/src/main/java/com/aos/common/utils/IsChineseOrEnglish.java @@ -0,0 +1,34 @@ +package com.aos.common.utils; + +public class IsChineseOrEnglish { + // GENERAL_PUNCTUATION 判断中文的“号 + // CJK_SYMBOLS_AND_PUNCTUATION 判断中文的。号 + // HALFWIDTH_AND_FULLWIDTH_FORMS 判断中文的,号 + + public static boolean isChinese(char c) { + Character.UnicodeBlock ub = Character.UnicodeBlock.of(c); + if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) { + return true; + } + return false; + } + + public static Boolean isChinese(String strName) { + char[] ch = strName.toCharArray(); + for (int i = 0; i < ch.length; i++){ + char c = ch[i]; + if (isChinese(c) == true) { + return true; + } + } + return false; + } + + public static void main(String[] args) { +// Random r = new Random(); +// for (int i = 0; i < 20; i++) +// System.out.println(r.nextInt(10) + 1); + System.out.println(isChinese("123")); + System.out.println(isChinese("中国")); + } +} \ No newline at end of file diff --git a/src/main/java/com/aos/common/utils/RequestUtils.java b/src/main/java/com/aos/common/utils/RequestUtils.java new file mode 100644 index 0000000..46cb3da --- /dev/null +++ b/src/main/java/com/aos/common/utils/RequestUtils.java @@ -0,0 +1,212 @@ +package com.aos.common.utils; + +import com.aos.common.domain.exception.BizException; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.ServletRequestBindingException; +import org.springframework.web.bind.ServletRequestUtils; +import org.springframework.web.context.request.RequestAttributes; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; + +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.net.URLDecoder; +import java.util.Objects; + +/** + * 请求参数获取 + * @ClassName: RequestUtils + * @Date: 2021/8/31 10:26 + * @author hz21056617 + * @version V1.0 + */ +public class RequestUtils { + + public final static String tenantCode = "tenantCode"; + + public final static String employeeWorkCode = "employeeWorkCode"; + + public final static String employeeJobCode = "employeeJobCode"; + + public final static String employeeName = "employeeName"; + + public final static String employeeDepartmentId = "employeeDepartmentId"; + + public final static String terminal = "terminal"; + + public final static String employeeRole = "employeeRole"; + + /** + * cookie所在域 + */ + public final static String COOKIE_DOMAIN = "hzins.com"; + /** + * cookie path + */ + public final static String COOKIE_PATH = "/"; + + + /** + * 获取Request + * @param + * @return javax.servlet.http.HttpServletRequest + * @Date 2021/8/12 14:22 + * @Author hz21056617 + * @Version V1.0 + */ + public static HttpServletRequest getRequest() { + RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); + HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest(); + return request; + } + + /** + * 获取Response + * @param + * @return javax.servlet.http.HttpServletResponse + * @Date 2021/8/12 14:22 + * @Author hz21056617 + * @Version V1.0 + */ + public static HttpServletResponse getResponse() { + RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes(); + HttpServletResponse response = ((ServletRequestAttributes) requestAttributes).getResponse(); + return response; + } + + /** + * 获取顾问工号 + * + * @return + * @throws ServletRequestBindingException + */ + public static String getEmployeeWorkCode() throws Exception { + HttpServletRequest request = getRequest(); + String employeeWorkCode = getValue(request, RequestUtils.employeeWorkCode); + if (employeeWorkCode == null) { + throw new BizException("获取工号失败"); + } + return employeeWorkCode; + } + + /** + * 获取顾问角色 + * + * @return + * @throws ServletRequestBindingException + */ + public static Integer getEmployeeJobCode() throws Exception { + HttpServletRequest request = getRequest(); + String employeeJobCode = getValue(request, RequestUtils.employeeJobCode); + if (employeeJobCode == null) { + return null; + } + return Integer.valueOf(employeeJobCode); + } + + /** + * 获取顾问名 + * @return + * @throws ServletRequestBindingException + */ + public static String getEmployeeName() throws Exception { + HttpServletRequest request = getRequest(); + String employeeName = getValue(request, RequestUtils.employeeName); + employeeName = URLDecoder.decode(employeeName, "UTF-8"); + return employeeName; + } + + /** + * 获取顾问角色 + * + * @return + * @throws ServletRequestBindingException + */ + public static Integer getEmployeeDepartmentId() throws Exception { + HttpServletRequest request = getRequest(); + String employeeDepartmentId = getValue(request, RequestUtils.employeeDepartmentId); + if (employeeDepartmentId == null) { + return null; + } + return Integer.valueOf(employeeDepartmentId); + } + + /** + * 获取登陆终端 + * + * @return + * @throws Exception + */ + public static Integer getClientType() throws Exception { + HttpServletRequest request = getRequest(); + String clientType = getValue(request, RequestUtils.terminal); + if (clientType == null) { + clientType = "0"; + } + return Integer.valueOf(clientType); + } + + /** + * 获取角色 + * @param + * @return java.lang.Integer + * @Date 2021/8/12 14:26 + * @Author hz21056617 + * @Version V1.0 + */ + public static Integer getEmployeeRole() throws Exception { + HttpServletRequest request = getRequest(); + String employeeRole = getValue(request, RequestUtils.employeeRole); + return Integer.valueOf(employeeRole); + } + + /** + * 从请求中获取值 + * @param request + * @param key + * @return java.lang.String + * @Date 2021/8/12 14:25 + * @Author hz21056617 + * @Version V1.0 + */ + private static String getValue(HttpServletRequest request, String key) throws Exception { + String value = null; + try { + value = ServletRequestUtils.getStringParameter(request, key); + } + catch (ServletRequestBindingException e) { + } + if (StringUtils.isEmpty(value)) { + value = request.getHeader(key); + } + if (StringUtils.isEmpty(value)) { + value = getValueFromCookie(request, key); + } + return value; + } + + /** + * 从cookie中获取值 + * + * @param request + * @param key + * @return + * @throws Exception + */ + private static String getValueFromCookie(HttpServletRequest request, String key) throws Exception { + String value = null; + Cookie[] cookies = request.getCookies(); + if (!Objects.isNull(cookies)) { + for (Cookie cookie : cookies){ + if (cookie.getName() + .equals(key)) { + value = cookie.getValue(); + break; + } + } + } + return value; + } + +}