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);
  }
}

  

posted @ 2019-04-25 12:31  Jarbein  阅读(1125)  评论(0编辑  收藏  举报