基于springboot写的拦截器

第一步:书写一个类

package com.lpy.controller.interceptor;

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MiniInterceptor implements HandlerInterceptor {
	/**
	 * 拦截请求,在controller调用之前
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if(true) {
			System.out.println("请求拦截");
			return false;
		}
		/**
		 * 返回false:请求被拦截,返回
		 * 返回true:请求ok,可以继续执行,放行
		 */
		return true;
	}
	/**
	 * 请求controller之后,渲染视图之前
	 */
	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub

	}
	/**
	 * 请求controller之后,渲染视图之后
	 */
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}

第二步:书写配置

package com.lpy;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
/**
 * 以前spring配置实在xml里面,现在springboot配置实在java类里面
 * @author Richard
 *
 */

import com.lpy.controller.interceptor.MiniInterceptor;
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {
	/**
	 * 显示图片的配置,我们的个人信息的头像
	 * @author Richard
	 * 可以直接通过http://localhost:8082/181127743X140568/face/wx3ce7c79e96132bd8.o6zAJs-h4oiS8tWZhwsiPN2jEeD8.3LCbAy49NFap02319d110a7896da0e48d2c34a1259d6.JPG
	 *访问图片
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		registry.addResourceHandler("/**")
				.addResourceLocations("classpath:/META-INF/resources/") //解决swagger2的访问,注意后面多了一个斜线
		        .addResourceLocations("file:D:\\java_all\\workspace-wxxcs\\video-space\\");
	}
	
	@Bean
	public MiniInterceptor miniInterceptor() {
		
		return new MiniInterceptor();
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		//将拦截器注册进去了
		registry.addInterceptor(miniInterceptor()).addPathPatterns("/user/**");
		super.addInterceptors(registry);
	}
	
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值