springBoot使用攔截器

//自定義攔截器,實現HandlerInterceptor類html

public class loginInterceptor implements HandlerInterceptor {post

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    
	Object user = request.getSession().getAttribute("loginUser");
	 
     if(user==null) {
	 
         request.setAttribute("error","沒有權限,請登陸");
		 
         request.getRequestDispatcher("/index.html").forward(request, response);
		 
         return false;
     }
    return true;
}


public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

}

public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

}

}spa

//注入到容器中 @Configuration必須寫上,不然不起做用code

// 1.x.x 以前使用的是 繼承 WebMvcConfigurerAdapter,官方不建議使用 能夠配置本身定義的配置方式htm

//2.x.x 使用實現WebMvcConfigurer類 這個裏面有不少方法,能夠配置本身定義的配置方式繼承

@Configurationget

public class myConfig implements WebMvcConfigurer {io

public void addInterceptors(InterceptorRegistry registry) {

   //攔截根目錄下的全部的的,排除/index.html / /user/login
   
    registry.addInterceptor(new loginInterceptor()).addPathPatterns("/**")
	
    .excludePathPatterns("/index.html","/","/user/login");
}

}class

相關文章
相關標籤/搜索