在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