springboot2.0注解拦截器和参数解析器

效果图

参数拦截器:参数存在得情况

springboot2.0注解拦截器和参数解析器_第1张图片

参数拦截器:参数不存在得情况

springboot2.0注解拦截器和参数解析器_第2张图片

方法注解拦截器:控制台日志

springboot2.0注解拦截器和参数解析器_第3张图片

源码

package com.asyf.common;

import com.asyf.annotation.Login;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    public static final Logger log = LoggerFactory.getLogger(MyInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle");
        //如果是SpringMVC请求
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            log.info("当前拦截的方法为:{}", handlerMethod.getMethod().getName());
            log.info("当前拦截的方法参数长度为:{}", handlerMethod.getMethod().getParameters().length);
            log.info("当前拦截的类为:{}", handlerMethod.getBean().getClass().getName());
            String uri = request.getRequestURI();
            log.info("拦截的uri:" + uri);
            //获取方法注解
            Login login = handlerMethod.getMethodAnnotation(Login.class);
            if (login != null) {
                log.info("login.required()---" + String.valueOf(login.required()));
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        log.info("afterCompletion");
    }
}
package com.asyf.common;

import com.asyf.annotation.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

public class TestArgumentResolver implements HandlerMethodArgumentResolver {

    public static final Logger log = LoggerFactory.getLogger(TestArgumentResolver.class);

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        //如果函数包含我们的自定义注解,那就走resolveArgument()函数,可以支持多个注解
        return methodParameter.hasParameterAnnotation(Param.class);
    }

    /**
     * 根据注解得不同操作不同得业务
     */
    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) throws Exception {
        log.info("参数解析器--HandlerMethodArgumentResolver");
        //获取参数名
        String parameterName = methodParameter.getParameterName();
        log.info("parameterName---" + parameterName);
        Class parameterType = methodParameter.getParameterType();
        Param param = methodParameter.getParameterAnnotation(Param.class);
        boolean required = param.required();
        //简单的案例:如果客户端未传值,就设置默认值
        Object res = nativeWebRequest.getNativeRequest(HttpServletRequest.class).getParameter(parameterName);
        log.info("res---" + res);
        //判断参数是否存在
        if (required) {
            if (StringUtils.isEmpty(res)) {
                throw new MissingServletRequestParameterException(parameterName, parameterType.toString());
            }
        }
        //返回值就是controller接收得值
        return res;
    }
}
package com.asyf.common;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //'/**'匹配所有
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**");
    }

    @Override
    public void addArgumentResolvers(List resolvers) {
        resolvers.add(new TestArgumentResolver());
    }
}
    @RequestMapping(value = "demo")
    @Login
    public Map demo(@Param(required = true) String a) {
        Map map = new HashMap<>();
        map.put("time", new Date().toString());
        map.put("a", a);
        return map;
    }
package com.asyf.annotation;

import java.lang.annotation.*;

@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface Param {
    boolean required() default false;
}

 

你可能感兴趣的:(Java)