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

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM