Java教程

SpringMVC进阶-01

本文主要是介绍SpringMVC进阶-01,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

SpringMVC进阶-01

1.拦截器

public class LoginInterceptor implements HandlerInterceptor {

    /**
     * 拦截器 拦截没有登录的用户
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        if (request.getSession().getAttribute("user") == null) {
            response.sendRedirect("/admin");
            return false;
        }
        return true;
    }
}

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }
}

2.异常处理

@Slf4j
@ControllerAdvice
public class ControllerExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ModelAndView handlerException(HttpServletRequest request, Exception e) throws Exception {
        log.error("request url {}, error info {}", request.getRequestURL(), e);

        // 如果捕获到的异常上有ResponseStatus注解,说明是页面找不到的异常,这里直接抛出,
        // 交给springboot去处理,来返回error/404.html。
        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.html");
        return mv;
    }
}

3.方法访问日志记录

@Slf4j
@Aspect
@Component
public class LogAspect {

    @Pointcut("execution(* com.my.blog.controller.*.*(..))")
    public void log() {}

    @Before(value = "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 methodName = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestInfo requestInfo = new RequestInfo(url, ip, methodName, args);
    }

    @After(value = "log()")
    public void doAfter() {
    }

    @AfterReturning(value = "log()", returning = "obj")
    public void afterReturning(Object obj) {
        log.info("response result {}", obj);
    }

    @ToString
    @AllArgsConstructor
    static class RequestInfo {
        private final String url;
        private final String ip;
        private final String methodName;
        /**
         * 方法参数
         */
        private final Object[] args;
    }
}
这篇关于SpringMVC进阶-01的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!