springboot实现拦截器
你首先需要一个搭建好的springboot项目,具体怎么搭建我还没有相应的随笔可以交给你,可以自己上网上看一下,学习一下,之后我要是总结出来的话,这里面我会通知的
首先这个项目的目录结构是这样子的
首先在Controller里面写上你想要展示的内容
package com.example.springBoot; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @RequestMapping(value="/") public String Hello(){ return "hello"; } }
然后自定义一个拦截器
package com.example.springBoot; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InterceptorUtil implements HandlerInterceptor { /** * todo : 在请求处理之前调用,此处当userId==lx时才能正常进入控制器,否则被拦截 * @param httpServletRequest * @param httpServletResponse * @param o * @return * @throws Exception */ @Override public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception { String userId = httpServletRequest.getParameter("userId");//接收一个userId的参数 if("lx".equals(userId)) return true; else return false; } @Override public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception { System.out.println("执行postHandle方法"); } @Override public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception { System.out.println("执行afterCompletion方法"); } }
preHandle:请求之前调用,返回值为boolean类型,然后返回true的时候执行下面的两个方法,返回false则不执行
postHandle:请求之后视图渲染之前调用
afterCompletion:视图渲染之后调用
然后写MyWebAppConfigurer,将上述拦截器注入bean中
package com.example.springBoot; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; /** * 注册拦截器 * @author lixue * */ @Configuration public class MyWebAppConfigurer extends WebMvcConfigurerAdapter { @Bean //把拦截器注入为bean public HandlerInterceptor getMyInterceptor(){ return new InterceptorUtil(); } @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(getMyInterceptor()).addPathPatterns("/**"); super.addInterceptors(registry); } }
然后运行Application
package com.example.springBoot; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
右键
然后访问
控制台打印了postHandle afterCompletion这两个方法的输出语句
接下来换一下
什么都没有,控制台也没有继续打印(这是上面操作userId=lx打印出来的userId=lx1并没有打印)
这样就实现了一个简单的拦截器