在03-springboot-web中建立interceptor包,並建立一個LoginInterceptor攔截器java
代碼示例:node
package com.bjpowernode.springboot.interceptor; import org.springframework.web.servlet.HandlerInterceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginInterceptor implements HandlerInterceptor { @Override //進入Controller以前執行該方法 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //登陸攔截的業務邏輯 System.out.println("-------登陸請求攔截器--------------"); System.out.println(request.getRequestURI().toString()); Object object = request.getSession().getAttribute("user"); if (object == null) { System.out.println("用戶沒有登陸"); return false; } //繼續提交請求,false 請求不提交了 return true; } }
在03-springboot-web中建立一個config包,建立一個配置類InterceptorConfig,並實現WebMvcConfigurer接口, 覆蓋接口中的addInterceptors方法,併爲該配置類添加@Configuration註解,標註此類爲一個配置類,讓Spring Boot 掃描到,這裏的操做就至關於SpringMVC的註冊攔截器 ,@Configuration就至關於一個applicationContext-mvc.xmlweb
代碼示例:spring
package com.bjpowernode.springboot.config; import com.bjpowernode.springboot.interceptor.LoginInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class InterceptorConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { //須要攔截的路徑,/**表示須要攔截全部請求 String[]addPathPatterns={"/**"}; //不須要攔截的路徑 String [] excludePathPaterns={ "/boot/get", "/boot/post", "/boot/put", "/myservlet" }; //註冊一個登陸攔截器 registry.addInterceptor(new LoginInterceptor()) .addPathPatterns(addPathPatterns) .excludePathPatterns(excludePathPaterns); //註冊一個權限攔截器 若是有多個攔截器 ,只須要添加如下一行代碼 //registry.addInterceptor(new LoginInterceptor()) // .addPathPatterns(addPathPatterns) // .excludePathPatterns(excludePathPatterns); } }
訪問http://localhost:8080/boot/get 控制檯不會輸出信息瀏覽器
訪問http://localhost:8080/boot/stu 控制檯輸出信息 springboot