欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot中创建拦截器Interceptor

程序员文章站 2022-05-23 10:51:22
...

一个简单的Demo,仅供学习。

 实现HandlerInterceptor 接口创建一个拦截器类。

preHandle:controller处理前,拦截逻辑

postHandle:controller处理后

@Component
public class MyInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Allow-Methods", "GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, PATCH");
        //从request对象中获取到Auth信息
        String sessionId = request.getHeader("session-id");
        //开始进行业务判断操作
        System.out.println("拦截器处理中...");
        //未登陆,则返回一个未登陆的Result
        if (sessionId == null){
            Result result = Result.fail(ErrorEnum.NOT_AUTH);
            PrintWriter writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
            writer.flush();
            writer.close();
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("拦截器处理后...");
    }
}

 创建了拦截器后,我们需要注册到 InterceptorRegistry 中。

这里注意:

网上很多教程是继承 :WebMvcConfigurerAdapter

本人版本是 spring-webmvc:5.1.2 RELEASE 

这里已经不推荐使用了,改用的是

WebMvcConfigurationSupport

代码如下:

@Configuration
public class InterceptorConfigration extends WebMvcConfigurationSupport {
    /**
     * 不拦截URL
     */
    private static String[] notLoginInterceptPaths = {"/error/**","/swagger-resources/**","/swagger-ui.html/**"};
    @Autowired
    private MyInterceptor myInterceptor;

    /**
     * 将拦截器注册到spring
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(myInterceptor).addPathPatterns("/**").excludePathPatterns(notLoginInterceptPaths);
    }
}

 result类:

public class Result<T>  implements Serializable {
    /**
     * 状态
     */
    private Boolean status;
    /**
     * 消息
     */
    private String message;
    /**
     * 返回错误码
     */
    private Integer responseCode;
    /**
     * 结果对象
     */
    private T entry;
    /**
     * 结果对象的条数
     */
    private Integer count;

    /**
     * 默认成功
     * @return 返回值
     */
    public static <T> Result<T> success(){
        Result result = new Result();
        result.setStatus(true);
        result.setEntry(null);

        return result;
    }
    /**
     * 成功,并把结果返回
     * @return 返回详细值
     */
     public static <T> Result<T> success(T t){
        Result<T> result = new Result<>();
        result.setStatus(true);
        result.setEntry(t);

        return result;
    }
    /**
     * 成功,返回结果以及结果总数
     */
    public static <T> Result<T> success(T t,Integer count){
        Result result = new Result();
        result.setStatus(true);
        result.setCount(count);
        result.setEntry(t);

        return result;
    }
    /**
     * 失败,必须填写错误信息
     */
    public static Result fail(String errorMessage){
        Result result = new Result();
        result.setStatus(false);
        result.setMessage(errorMessage);

        return result;
    }
    /**
     * 失败,使用常用的错误码返回错误信息
     */
    public static Result fail(ErrorEnum errorEnum){
        Result result = new Result();
        result.setStatus(false);
        result.setResponseCode(errorEnum.getErrorCode());
        result.setMessage(errorEnum.getErrorMsg());

        return result;
    }
    /**---------------------get/set-----------------------*/
    public Boolean getStatus() { return status; }

    public void setStatus(Boolean status) { this.status = status; }

    public String getMessage() { return message; }

    public void setMessage(String message) { this.message = message; }

    public Integer getResponseCode() { return responseCode; }

    public void setResponseCode(Integer responseCode) { this.responseCode = responseCode; }

    public T getEntry() { return entry; }

    public void setEntry(T entry) { this.entry = entry; }

    public Integer getCount() { return count; }

    public void setCount(Integer count) { this.count = count; }
}