SpringBoot自定義攔截器實現


1、編寫攔截器實現類,此類必須實現接口   HandlerInterceptor,然后重寫里面需要的三個比較常用的方法,實現自己的業務邏輯代碼

如:OneInterceptor

 1 package com.leecx.interceptors.interceptor;
 2 
 3 
 4 import com.leecx.pojo.LeeJSONResult;
 5 import com.leecx.utils.JsonUtils;
 6 import org.springframework.web.servlet.HandlerInterceptor;
 7 import org.springframework.web.servlet.ModelAndView;
 8 
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.io.IOException;
12 import java.io.OutputStream;
13 import java.io.UnsupportedEncodingException;
14 
15 public class OneInterceptor implements HandlerInterceptor{
16 
17     /**
18      * 在請求處理之前進行調用(Controller方法調用之前)
19      */
20     @Override
21     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
22 
23         System.out.println("=====================");
24         if (true) {
25             returnErrorResponse(httpServletResponse, LeeJSONResult.errorMsg("被one攔截..."));
26         }
27 
28         System.out.println("被one攔截...");
29 
30         return false;
31     }
32 
33     /**
34      * 請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后)
35      */
36     @Override
37     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
38 
39     }
40 
41     /**
42      * 在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行(主要是用於進行資源清理工作)
43      */
44     @Override
45     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
46 
47     }
48 
49     public void returnErrorResponse(HttpServletResponse response, LeeJSONResult result) throws IOException, UnsupportedEncodingException {
50         OutputStream out = null;
51         try{
52             response.setCharacterEncoding("utf-8");
53             response.setContentType("text/json");
54             out = response.getOutputStream();
55             out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
56             out.flush();
57         } finally{
58             if(out!=null){
59                 out.close();
60             }
61         }
62     }
63 }

說明:

1、preHandle  方法會在請求處理之前進行調用(Controller方法調用之前)

2、postHandle  請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后)

3、afterCompletion  在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行(主要是用於進行資源清理工作)

2、編寫攔截器配置文件主類 WebMvcConfigurer  此類必須繼承  WebMvcConfigurerAdapter 類,並重寫其中的方法  addInterceptors   並且在主類上加上注解  @Configuration    

如:WebMvcConfigurer

 1 package com.leecx.interceptors.config;
 2 
 3 import com.leecx.interceptors.interceptor.OneInterceptor;
 4 import com.leecx.interceptors.interceptor.TwoInterceptor;
 5 import org.springframework.context.annotation.Configuration;
 6 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
 7 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
 8 
 9 @Configuration
10 public class WebMvcConfigurer extends WebMvcConfigurerAdapter{
11 
12     /**
13      * <p>Title:</p>
14      * <p>Description:重寫增加自定義攔截器的注冊,某一個攔截器需要先注冊進來,才能工作</p>
15      * param[1]: null
16      * return:
17      * exception:
18      * date:2018/4/18 0018 下午 17:29
19      * author:段美林[duanml@neusoft.com]
20      */
21     @Override
22     public void addInterceptors(InterceptorRegistry registry) {
23 
24         registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
25 
26         registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/one/**")
27                                                      .addPathPatterns("/two/**");
28 
29         super.addInterceptors(registry);
30     }
31 }

說明:

   攔截器的執行是會根據 registry 注入的先后順序執行,比如:/one/**   同時被  OneInterceptor、TwoInterceptor 攔截,但會先執行 OneInterceptor攔截的業務請求,因為它先注入進來的

 

3、在controller業務層,只要請求的地址為  攔截器 申明的需要攔截地址即可進入相應的業務處理。

如:OneInterceptorController    這個controller 類的所有實現方法都會被 攔截器  OneInterceptor   所攔截到。

 1 package com.leecx.controller;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Date;
 5 import java.util.List;
 6 
 7 import org.springframework.stereotype.Controller;
 8 import org.springframework.ui.ModelMap;
 9 import org.springframework.web.bind.annotation.PostMapping;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 
12 import com.leecx.pojo.User;
13 
14 @Controller
15 @RequestMapping("/one")
16 public class OneInterceptorController {
17 
18     @RequestMapping("/index")
19     public String index(ModelMap map) {
20         System.out.println("=========one is  index");
21         map.addAttribute("name", "itzixi22");
22         return "thymeleaf/index";
23     }
24     
25     @RequestMapping("center")
26     public String center() {
27         return "thymeleaf/center/center";
28     }
29 
30     @RequestMapping("test")
31     public String test(ModelMap map) {
32         
33         User user = new User();
34         user.setAge(18);
35         user.setName("manager");
36         user.setPassword("123456");
37         user.setBirthday(new Date());
38         
39         map.addAttribute("user", user);
40         
41         
42         User u1 = new User();
43         u1.setAge(19);
44         u1.setName("itzixi");
45         u1.setPassword("123456");
46         u1.setBirthday(new Date());
47         
48         User u2 = new User();
49         u2.setAge(17);
50         u2.setName("LeeCX");
51         u2.setPassword("123456");
52         u2.setBirthday(new Date());
53         
54         List<User> userList = new ArrayList<>();
55         userList.add(user);
56         userList.add(u1);
57         userList.add(u2);
58         
59         map.addAttribute("userList", userList);
60         
61         return "thymeleaf/test";
62     }
63     
64     @PostMapping("postform")
65     public String postform(User user) {
66         System.out.println(user.getName());
67         return "redirect:/th/test";
68     }
69 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM