5_攔截器

建立攔截器

 
  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. 控制檯數據【訪問連接以後】

相關文章
相關標籤/搜索