springBoot中自定义注解拦截header中的值的工具类

首先引入AOP的依赖


    org.springframework.boot
    spring-boot-starter-aop

其次新建一个注解:

import java.lang.annotation.*;

/**
 * 拦截请求头中的值是否为空 方法注解和类注解
 * 例子拦截user_id: @HeaderChecker(headerNames = {"user_id"})
 * @author wen
 * @date 2019/4/25 15:03
 */
@Documented
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface HeaderChecker {
    /**
     * Without default value means this argument is required
     *
     * @return Header names
     */
    String[] headerNames();
}

 

自己定义AOP切面:

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.Optional;

/**
 * @author wen
 * @date 2019/4/25 16:37
 */
@Slf4j
@Aspect
@Component
public class HeaderCheckerAspect {

    @Before("@within(headerChecker)")
    public void doBeforeForClass(HeaderChecker headerChecker) {
        doBefore(headerChecker);
    }
    @Before("@annotation(headerChecker)")
    public void doBefore(HeaderChecker headerChecker) {
        HttpServletRequest request = currentRequest();
        if (Objects.isNull(request)) {
            log.info("without request, skip");
            return;
        }

        String[] headerNames = headerChecker.headerNames();
        for (String headerName : headerNames) {
            String value = request.getHeader(headerName);
            if (StringUtils.hasText(value)) {
                continue;
            }
            log.error("Header {} is required", headerName);
            throw new IllegalArgumentException("Header " + headerName + " is required");
        }

        log.info("checked");
    }

    /**
     * Return request current thread bound or null if none bound.
     *
     * @return Current request or null
     */
    private HttpServletRequest currentRequest() {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return Optional.ofNullable(servletRequestAttributes).map(ServletRequestAttributes::getRequest).orElse(null);
    }

}

在controller直接引用,该注解可以使用在类上(ElementType.TYPE),和方法上(ElementType.METHOD):

/**
 * 添加用户
 */
@HeaderChecker(headerNames = {"user_id"})
@GetMapping(value = "/testValid")
public String getTestValid(@RequestParam String name) {
        System.out.println(name);
        return "ok";
}

快去验证请求头里的数据吧,自己写拦截器还不如写个注解,注解开发才是主流,貌似跟shior的权限验证类似

引用:https://blog.csdn.net/szj9106/article/details/84071398#commentBox

update:

@RequestHeader(参数级别的注解,可以直接获取header中的值)

 

你可能感兴趣的:(工具总结)