308 lines
8.3 KiB
Markdown
308 lines
8.3 KiB
Markdown
---
|
||
title: 毕业设计(3)
|
||
tags:
|
||
- java
|
||
- ssm
|
||
- react
|
||
- ant design
|
||
- typescript
|
||
categories: 毕业设计
|
||
date: 2022-12-10 12:38:32
|
||
summary: 基本工具类创建
|
||
|
||
---
|
||
|
||
## 六、创建Resp返回类
|
||
|
||
实体类分别包含了四个字段,code、data、errot、message
|
||
|
||
Resp.class
|
||
|
||
```java
|
||
package org.gjs.utils;
|
||
|
||
|
||
public class Resp<T> {
|
||
int code;
|
||
T data;
|
||
String error;
|
||
String message;
|
||
|
||
public int getCode() {
|
||
return code;
|
||
}
|
||
|
||
public void setCode(int code) {
|
||
this.code = code;
|
||
}
|
||
|
||
public T getData() {
|
||
return data;
|
||
}
|
||
|
||
public void setData(T data) {
|
||
this.data = data;
|
||
}
|
||
|
||
public String getError() {
|
||
return error;
|
||
}
|
||
|
||
public void setError(String error) {
|
||
this.error = error;
|
||
}
|
||
|
||
public String getMessage() {
|
||
return message;
|
||
}
|
||
|
||
public void setMessage(String message) {
|
||
this.message = message;
|
||
}
|
||
|
||
public Resp() {
|
||
}
|
||
|
||
public Resp(int code, T data, Exception error, String message) {
|
||
this.code = code;
|
||
this.data = data;
|
||
if (error == null){
|
||
this.error = "";
|
||
}else {
|
||
this.error = error.getMessage();
|
||
}
|
||
|
||
this.message = message;
|
||
}
|
||
|
||
public static <K> Resp<K> Ok(){
|
||
return new Resp<K>(200,null,null,"");
|
||
}
|
||
public static <K> Resp<K> Ok(K data){
|
||
return new Resp<K>(200,data,null,"");
|
||
}
|
||
public static <K> Resp<K> Ok(K data,String message){
|
||
return new Resp<K>(200,data,null,message);
|
||
}
|
||
|
||
|
||
public static <K> Resp<Boolean> Err(int code, Exception e){
|
||
return new Resp<Boolean>(code,false,e,"");
|
||
}
|
||
|
||
public static <K> Resp<K> Err(int code, Exception e,K data){
|
||
return new Resp<K>(code,data,e,"");
|
||
}
|
||
|
||
public static <K> Resp<K> Err(int code, Exception e,K data,String message){
|
||
return new Resp<K>(code,data,e,message);
|
||
}
|
||
|
||
public static <K> Resp<Boolean> Err(int code,Exception e,String message){
|
||
return new Resp<Boolean>(code,false,e,message);
|
||
}
|
||
}
|
||
```
|
||
|
||
## 七、全局错误处理
|
||
|
||
通过**RestControllerAdvice**注解和**RestControllerAdvice**注解进行全局异常处理
|
||
|
||
ExceptionController.java
|
||
|
||
```java
|
||
package org.gjs.exception;
|
||
|
||
|
||
import org.apache.log4j.Logger;
|
||
import org.gjs.utils.Resp;
|
||
import org.jetbrains.annotations.NotNull;
|
||
import org.springframework.http.HttpStatus;
|
||
import org.springframework.stereotype.Component;
|
||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||
import org.springframework.web.bind.annotation.ResponseBody;
|
||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||
|
||
import javax.servlet.http.HttpServletResponse;
|
||
|
||
@RestControllerAdvice
|
||
@Component
|
||
public class ExceptionController {
|
||
|
||
|
||
private final Logger logger = Logger.getLogger(this.getClass());
|
||
|
||
|
||
@ExceptionHandler({RuntimeException.class})
|
||
public Object runtime(HttpServletResponse response,RuntimeException e){
|
||
response.setStatus(503);
|
||
e.printStackTrace();
|
||
return Resp.Err(503,e,"服务端异常错误!");
|
||
}
|
||
|
||
@ExceptionHandler({NullPointerException.class})
|
||
@ResponseBody
|
||
@ResponseStatus(code = HttpStatus.SERVICE_UNAVAILABLE)
|
||
public Object nullExc(HttpServletResponse response,Exception e){
|
||
e.printStackTrace();
|
||
return Resp.Err(503,e);
|
||
}
|
||
|
||
@ExceptionHandler({Exception.class})
|
||
@ResponseBody
|
||
@ResponseStatus(code = HttpStatus.SERVICE_UNAVAILABLE)
|
||
public Object my(HttpServletResponse response, @NotNull Exception e){
|
||
e.printStackTrace();
|
||
return Resp.Err(503,e);
|
||
}
|
||
}
|
||
```
|
||
|
||
## 八、Jwt工具类编写
|
||
|
||
首先在maven中导入jwt得依赖
|
||
|
||
```xml
|
||
<!-- https://mvnrepository.com/artifact/com.auth0/java-jwt -->
|
||
<dependency>
|
||
<groupId>com.auth0</groupId>
|
||
<artifactId>java-jwt</artifactId>
|
||
<version>4.2.1</version>
|
||
</dependency>
|
||
```
|
||
|
||
工具类编写
|
||
|
||
Jwt.java
|
||
|
||
```java
|
||
package org.gjs.utils;
|
||
|
||
|
||
import com.auth0.jwt.JWT;
|
||
import com.auth0.jwt.JWTVerifier;
|
||
import com.auth0.jwt.algorithms.Algorithm;
|
||
import com.auth0.jwt.interfaces.DecodedJWT;
|
||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||
|
||
import java.util.Calendar;
|
||
import java.util.Date;
|
||
|
||
public class Jwt {
|
||
|
||
private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";
|
||
|
||
private static final String EXP = "exp";
|
||
|
||
private static final String PAYLOAD = "payload";
|
||
|
||
private static final String ISSUE = "gjs";
|
||
|
||
private static final Integer MAX_AGE = 60 * 60 * 24 * 30;
|
||
|
||
//加密,传入一个对象和有效期
|
||
public static <T> String sign(T object) {
|
||
try {
|
||
|
||
ObjectMapper mapper = new ObjectMapper();
|
||
String jsonString = mapper.writeValueAsString(object);
|
||
Calendar calendar = Calendar.getInstance();
|
||
calendar.setTime(new Date());
|
||
calendar.add(Calendar.MONTH,1);
|
||
return JWT.create()
|
||
.withIssuer(ISSUE)
|
||
.withClaim(PAYLOAD,jsonString)
|
||
.withExpiresAt(calendar.getTime())
|
||
.sign(Algorithm.HMAC256(SECRET));
|
||
} catch(Exception e) {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
//解密,传入一个加密后的token字符串和解密后的类型
|
||
public static<T> T verify(String jwt, Class<T> classT) {
|
||
try {
|
||
JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).withIssuer(ISSUE).build();
|
||
DecodedJWT v = verifier.verify(jwt);
|
||
Date expiresAt = v.getExpiresAt();
|
||
// 检查是否过期
|
||
if (new Date().after(expiresAt) ){
|
||
return null;
|
||
}
|
||
String s = v.getClaim(PAYLOAD).asString();
|
||
ObjectMapper objectMapper = new ObjectMapper();
|
||
return objectMapper.readValue(s, classT);
|
||
} catch (JsonProcessingException e) {
|
||
return null;
|
||
}
|
||
|
||
}
|
||
}
|
||
```
|
||
|
||
## 九、日志中间件实现
|
||
|
||
使用aop进行拦截日志记录
|
||
|
||
LogAop.java
|
||
|
||
```java
|
||
package org.gjs.aop;
|
||
|
||
import org.apache.log4j.Logger;
|
||
import org.aspectj.lang.JoinPoint;
|
||
import org.aspectj.lang.Signature;
|
||
import org.aspectj.lang.annotation.AfterReturning;
|
||
import org.aspectj.lang.annotation.Aspect;
|
||
import org.aspectj.lang.annotation.Before;
|
||
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 javax.servlet.http.HttpServletResponse;
|
||
|
||
|
||
@Aspect
|
||
@Component
|
||
public class LogAop {
|
||
|
||
public LogAop() {
|
||
}
|
||
|
||
private final Logger logger = Logger.getLogger(this.getClass());
|
||
|
||
@Before("execution(* org.gjs.controller.*.*(..))")
|
||
public void before(JoinPoint point){
|
||
|
||
Signature signature = point.getSignature();
|
||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||
logger.info(request.getSession().getId()+" ----------------------------------------------------");
|
||
logger.info(request.getSession().getId() +" - name: "+signature.getName());
|
||
logger.info(request.getSession().getId()+" - ip: "+request.getRemoteAddr());
|
||
logger.info(request.getSession().getId()+" - method: "+request.getMethod());
|
||
logger.info(request.getSession().getId()+" - query: "+request.getQueryString());
|
||
Object[] args = point.getArgs();
|
||
for (Object a : args
|
||
) {
|
||
if (a != null){
|
||
logger.info(request.getSession().getId()+" - args: "+a.toString());
|
||
}
|
||
|
||
}
|
||
}
|
||
@AfterReturning(value = "execution(* org.gjs.controller.*.*(..))",returning = "methodResult")
|
||
public void afterReturning(JoinPoint joinPoint, Object methodResult){
|
||
HttpServletResponse res = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
|
||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
|
||
logger.info(request.getSession().getId()+ " - status: "+res.getStatus());
|
||
logger.info(request.getSession().getId()+ " - return: "+methodResult);
|
||
logger.info(request.getSession().getId()+" ----------------------------------------------------");
|
||
}
|
||
}
|
||
```
|
||
|
||
#
|