项目中的工具类
TokenVerify(验证token)
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ffyc.newsdemo.common.CommonResult;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
public class AdminTokenVerify implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String token=request.getHeader("token");
CommonResult commonResult=null;
boolean verify=JWTUtil.verify(token);
if(!verify){
commonResult=new CommonResult(202,"验证失败");
PrintWriter out=response.getWriter();
ObjectMapper objectMapper=new ObjectMapper();
out.print(objectMapper.writeValueAsString(commonResult));
out.flush();
out.close();;
}
return verify;
}
}
JWTUtil(生成token)
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class JWTUtil {
public static String token (Integer id, String account,Integer type){
String token = "";
try {
Date expireDate = new Date(new Date().getTime() +60*60*24*1000);
Algorithm algorithm = Algorithm.HMAC256("ZCEQIUBFKSJBFJH2020BQWE");
Map<String,Object> header = new HashMap<>();
header.put("typ","JWT");
header.put("alg","HS256");
token = JWT.create()
.withHeader(header)
.withClaim("id",id)
.withClaim("account",account)
.withClaim("type",type)
.withExpiresAt(expireDate)
.sign(algorithm);
}catch (Exception e){
e.printStackTrace(); return null;
}
return token;
}
public static boolean verify(String token){
try {
Algorithm algorithm = Algorithm.HMAC256("ZCEQIUBFKSJBFJH2020BQWE");
JWTVerifier verifier = JWT.require(algorithm).build();
DecodedJWT jwt = verifier.verify(token);
return true;
} catch (Exception e) {
return false;
}
}
public static DecodedJWT getTokenInfo(String token){
return JWT.require(Algorithm.HMAC256("ZCEQIUBFKSJBFJH2020BQWE")).build().verify(token);
}
}
CommonResult(向前端返回)
import lombok.Data;
import lombok.ToString;
@Data
public class CommonResult {
Object data;
int code;
String message;
public CommonResult(Object data, int code, String message) {
this.data = data;
this.code = code;
this.message = message;
}
public CommonResult(int code, String message) {
this.code = code;
this.message = message;
}
}
CorsConfig(跨域)
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import java.util.Collections;
@Configuration
public class CorsConfig {
@Bean
public CorsFilter corsFilter() {
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.setAllowedOriginPatterns(Collections.singletonList("*"));
corsConfiguration.addAllowedHeader(CorsConfiguration.ALL);
corsConfiguration.addAllowedMethod(CorsConfiguration.ALL);
corsConfiguration.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", corsConfiguration);
return new CorsFilter(source);
}
}
DruidDataSourceConfig(配置德鲁伊数据源)
import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
public class DruidDataSourceConfig {
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druid() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
}
LogAspect(日志)
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.Enumeration;
@Component
@Aspect
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(getClass());
@Pointcut("execution(public * com.ffyc.newsdemo.controller..*.*(..))")
public void webLog() {
}
@Before("webLog()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes)
RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
logger.info("HTTP_METHOD :{} ", request.getMethod());
logger.info("IP : {}", request.getRemoteAddr());
Enumeration<String> enu = request.getParameterNames();
while (enu.hasMoreElements()) {
String name = (String) enu.nextElement();
logger.info("name:{},value:{}", name, request.getParameter(name));
}
}
@AfterReturning(returning = "ret", pointcut = "webLog()")
public void doAfter(Object ret) throws Throwable {
logger.info("RESPONSE : " + ret);
}
}
GlobalExceptionHandler(统一异常处理)
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public CommonResult globalException(Exception e) {
CommonResult commonResult = new CommonResult(500,e.getMessage());
return commonResult;
}
}