5_拦截器

原文链接:https://my.oschina.net/u/3783808/blog/1623120

创建拦截器

 
  1. package com.happy.middleware;
  2.  
  3. import org.springframework.web.servlet.HandlerInterceptor;
  4. import org.springframework.web.servlet.ModelAndView;
  5.  
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9.  
  10. public class InterceptorConfig implements HandlerInterceptor {
  11.  
  12.  
  13. /**
  14. * 进入controller层之前拦截请求
  15. *
  16. * @param httpServletRequest
  17. * @param httpServletResponse
  18. * @param o
  19. * @return
  20. * @throws Exception
  21. */
  22. @Override
  23. public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
  24.  
  25. System.out.print("拦截啦");
  26.  
  27. return true;
  28. }
  29.  
  30.  
  31. /**
  32. * 处理请求完成后视图渲染之前的处理操作
  33. *
  34. * @param httpServletRequest
  35. * @param httpServletResponse
  36. * @param o
  37. * @param modelAndView
  38. * @throws Exception
  39. */
  40. @Override
  41. public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
  42.  
  43. }
  44.  
  45. /**
  46. * 视图渲染之后的操作
  47. *
  48. * @param httpServletRequest
  49. * @param httpServletResponse
  50. * @param o
  51. * @param e
  52. * @throws Exception
  53. */
  54. @Override
  55. public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
  56.  
  57. }
  58. }

2. 使用拦截器

 
  1. package com.happy.middleware;
  2.  
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
  5. import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
  6.  
  7. /**
  8. * Created by xiao on 2018/2/22.
  9. */
  10.  
  11. @Configuration
  12. public class MyWebAppConfigurer extends WebMvcConfigurerAdapter {
  13.  
  14. @Override
  15. public void addInterceptors(InterceptorRegistry registry) {
  16.  
  17. registry.addInterceptor(new InterceptorConfig()).addPathPatterns("/**");
  18.  
  19. super.addInterceptors(registry);
  20. }
  21. }

3. 控制台数据【访问链接之后】

转载于:https://my.oschina.net/u/3783808/blog/1623120

展开阅读全文
博主设置当前文章不允许评论。

没有更多推荐了,返回首页