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

SpringBoot的URL拦截器

程序员文章站 2022-03-26 15:15:13
1、数据验证拦截器类package com.yt.interceptor;import lombok.extern.log4j.Log4j2;import org.springframework.http.MediaType;import org.springframework.lang.Nullable;import org.springframework.stereotype.Component;import org.springframework.web.servlet.ModelAnd...

1、数据验证拦截器类

package com.yt.interceptor;

import lombok.extern.log4j.Log4j2;
import org.springframework.http.MediaType;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器数据验证
 * @author tyg
 * @date   2020年8月5日下午3:46:09
 */
@Log4j2
@Component
public class AuthHandlerInterceptor extends HandlerInterceptorAdapter {

	private long startTime = 0;

	/**
	 * 请求处理前调用
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		startTime = System.currentTimeMillis();
		return super.preHandle(request, response, handler);
	}

	/**
	 * 请求处理完后渲染视图前调用
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
		log.info("\n======请求地址:{},耗时:{}ms", request.getServletPath(), System.currentTimeMillis() - startTime);
		super.postHandle(request, response, handler, modelAndView);
	}

	/**
	 * 渲染视图后调用
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 响应未授权信息
	 * @param response 响应
	 * @return void
	 * @author tyg
	 * @date   2018年12月7日下午2:01:59
	 */
	private void writeUnAuth(HttpServletResponse response) {
		Result<?> result = ResultUtil.unAuth();
		response.setContentType(MediaType.APPLICATION_JSON_VALUE);
		response.setCharacterEncoding(WechatConstant.UTF8);
		response.setStatus(HttpServletResponse.SC_OK);
		try {
			response.getWriter().print(JSONObject.toJSONString(result));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

2、将数据验证拦截器类加入到拦截器中

package com.yt.interceptor;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import javax.annotation.Resource;

/**
 * 加入URL拦截
 * @author tyg
 * @date 2020-12-31 14:59
 */
@Configuration
public class InterceptorConfig extends WebMvcConfigurationSupport {

    @Resource
    private AuthHandlerInterceptor globalInterceptor;

    /**
     * 加入权限拦截
     * @param registry 帮助配置映射的拦截器列表
     * @author tyg
     * @date 2020-12-31 14:59
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(globalInterceptor).addPathPatterns("/**");
        super.addInterceptors(registry);
    }

    /**
     * 设置默认数据
     */
    @Override
    public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
        // 默认返回格式 JSON
        configurer.defaultContentType(MediaType.APPLICATION_JSON);
    }
}

3、第2步中,会存在一个问题,如果设置了返回时间格式为如下,是不会生效的,还是会返回时间戳,如果要返回格式化了的时间,那么就要将第2步进行替换,具体原因就与加载机制有关了。

spring.jackson.date-format: yyyy-MM-dd HH:mm:ss

替换为:

package com.yt.interceptor;

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

import javax.annotation.Resource;

/**
 * 加入URL拦截
 * @author tyg
 * @date 2020-12-31 14:59
 */
@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

    @Resource
    private AuthHandlerInterceptor globalInterceptor;

    /**
     * 加入权限拦截
     * @param registry 帮助配置映射的拦截器列表
     * @author tyg
     * @date 2020-12-31 14:59
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(globalInterceptor).addPathPatterns("/**");
    }
}

本文地址:https://blog.csdn.net/qq_26365837/article/details/112022854