springboot项目系列-论坛系统05全局异常处理+日志处理+MD5加密

springboot项目系列-论坛系统05全局异常处理+日志处理使用了spring的AOP

论坛地址:http://www.cywloveyou.top

配置日志

logging:
  level:
    root: info
    com.cyw: debug
  file: log/blog-dev.log

编写异常处理类

package com.cyw.hander;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description: 拦截异常处理
 */
//拦截有Controller注解的控制器
@ControllerAdvice
public class ControllerExceptionHandler {
    
    

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    public ModelAndView exceptionHandler(HttpServletRequest request, Exception e) throws Exception {
    
    
        logger.error("Request URL : {},Exception : {}", request.getRequestURL(),e);

//        当标识了状态码的时候就不拦截
        if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
    
    
            throw e;
        }

        ModelAndView mv = new ModelAndView();
        mv.addObject("url",request.getRequestURL());
        mv.addObject("exception", e);
        mv.setViewName("error/error");
        return mv;
    }
}
package com.cyw;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 *
 */
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
    
    
    public NotFoundException() {
    
    
    }

    public NotFoundException(String message) {
    
    
        super(message);
    }

    public NotFoundException(String message, Throwable cause) {
    
    
        super(message, cause);
    }
}

日志处理类

package com.cyw.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
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.Arrays;

/**
 * @Description: 日志切面处理
 * @Author: Cyw
 */
@Aspect
@Component
public class LogAspect {
    
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    拦截控制器
    @Pointcut("execution(* com.cyw.controller.*.*(..))")
    public void log() {
    
    }


    /**
     * 前置通知
     * @param joinPoint
     */
    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
    
    
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        //获取方法名
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        //获取传入的参数
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Request : {}", requestLog);
    }

    /**
     * 后置通知
     * @param joinPoint
     */
    @After("log()")
    public void doAfter(JoinPoint joinPoint) {
    
    
//        logger.info("--------doAfter--------");
    }

    /**
     * 返回通知,在方法返回结果之后执行
     * @param result
     */
    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result) {
    
    
        logger.info("Result : {}", result);
    }

    private class RequestLog {
    
    
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(String url, String ip, String classMethod, Object[] args) {
    
    
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
    
    
            return "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }
}

MD5盐值加密(工具类而已,不必深究)

package com.cyw.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
    
    

    /**
     * @Description: MD5加密
     * @Date: 10:35 2020/3/27
     * @Param: 要加密的字符串
     * @Return: 加密后的字符串
     */
    public static String code(String str){
    
    
        try {
    
    
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[]byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
    
    
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
    
    
            e.printStackTrace();
            return null;
        }

    }
}

猜你喜欢

转载自blog.csdn.net/weixin_44219219/article/details/111771690