springboot2.0拦截器和webconfigure配置

springboot2.0拦截器和webconfigure配置

接下来介绍一下springboot如何配置拦截器,很简单,只需要两个配置文件就可以了

首先配置登陆拦截器

@Component
public class LoginInterceptor implements HandlerInterceptor {

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		HttpSession session = arg0.getSession();
		//String uri = request.getRequestURI(); // 获取登录的uri,这个是不进行拦截的
		//if(session.getAttribute("LOGIN_USER")!=null || uri.indexOf("system/login")!=-1) {// 说明登录成功 或者 执行登录功能
//		下边的currentuser是我登陆后加在session中的数据,如果没有就未登录跳转到登陆页面
		if(session.getAttribute("currentUser")!=null) {
			// 登录成功不拦截
			return true;
		}else {
			// 拦截后进入登录页面,getContextPath()是获取项目的根路径,
			// 根路径+/就是我的登陆页面,这个根据自己的登陆页面自己来决定后边加什么
			arg1.sendRedirect(arg0.getContextPath()+"/");
			return false;
		}
	}
}

  

然后配置webconfigure(具体都在注释中)

@Configuration
public class WebConfigurer implements WebMvcConfigurer {

  @Autowired
  private LoginInterceptor loginInterceptor;


  // 这个方法是用来配置静态资源的,比如html,js,css等等
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {

    //文件磁盘图片url 映射
    //配置server虚拟路径,handler为前台访问的目录,locations为files相对应的本地路径
    registry.addResourceHandler("/articlepicture/**").addResourceLocations("file:/D:/WProjects/images/collegeservice/articlepicture/");
    registry.addResourceHandler("/headpicture/**").addResourceLocations("file:/D:/WProjects/images/collegeservice/headpicture/");
    registry.addResourceHandler("/institution/**").addResourceLocations("file:/D:/WProjects/images/collegeservice/institution/");
    registry.addResourceHandler("/photo/**").addResourceLocations("file:/D:/WProjects/images/collegeservice/photo/");
  }
 
  // 这个方法用来注册拦截器,我们自己写好的拦截器需要通过这里添加注册才能生效
  @Override
  public void addInterceptors(InterceptorRegistry registry) {

    // addPathPatterns("/**") 表示拦截所有的请求,
    // excludePathPatterns("/login", "/register") 表示除了登陆与注册之外,因为登陆注册不需要登陆也可以访问
    String[] excludes = new String[]{"/","/static/**","/service/**","/articlepicture/**","/headpicture/**","/institution/**","/photo/**"};
    registry.addInterceptor(loginInterceptor).addPathPatterns("/**").excludePathPatterns(excludes);
//    super.addInterceptors(registry);
  }
}

  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jarbein

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值