1. 程式人生 > 實用技巧 >框架 Spring Boot 技術入門到整合 12-1 Springboot中如何使用攔截器

框架 Spring Boot 技術入門到整合 12-1 Springboot中如何使用攔截器

0    課程地址

https://www.imooc.com/video/16794

1    本節重點
1.1  使用攔截器使用相關注解

使用註解 @Configuration 配置攔截器

繼承此類:WebMvcConfigurerAdapter

重寫 addInterceptors 新增需要攔截的地址

1.2  自己關於攔截器的理解

這裡是訪問某個地址的時候攔截,相當於Spring中的advice,有前置通知,後置通知,環繞通知等,也可以理解為我公司的handler類的作用。不是自己最開始的理解攔截器必須是初始化的時候進行攔截(對使用者密碼的校驗)。

1.3  WebMvcConfigurer可重寫

1.4  兩個攔截器 和一個攔截器攔截兩個Controller是否有區別

從demo3和demo4來看,攔截的效果是沒區別的,都是一旦攔截住,下邊將不會執行,兩個攔截器 同樣是順序關係,而不是非同步關係

2    本節demo
2.1  demo1(攔截器A攔截所有的Controller)

要攔截的網址:http://127.0.0.1:8088//IMooc/hello

package com.example.demo.son.demoa;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * DemoHelloSpringBoot * * @author 魏豆豆 * @date 2020/11/14 */ @RestController public class DemoHelloSpringBoot { @RequestMapping("/hello") public Object helloSpringBoot(){ return "Hello SpringBoot hahaha"; } }

攔截器配置呼叫類:

package com.example.demo.config;

import com.example.demo.controller.interceptor.OneInterceptor;
import com.example.demo.controller.interceptor.TwoInterceptor; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class WebMvcConfigurer extends WebMvcConfigurerAdapter { @Override public void addInterceptors(InterceptorRegistry registry) { /** * 攔截器按照順序執行 */ //1 攔截所有 registry.addInterceptor(new OneInterceptor()).addPathPatterns("/*/**"); /*registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**") .addPathPatterns("/one/**"); registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");*/ super.addInterceptors(registry); } }

攔截器類:

package com.example.demo.controller.interceptor;

import com.example.demo.tools.JSONResult;
import com.example.demo.tools.JsonUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class OneInterceptor implements HandlerInterceptor  {

    /**
     * 在請求處理之前進行呼叫(Controller方法呼叫之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
            Object object) throws Exception {
        
        System.out.println("被one攔截,放行...");
     return true;
        
        /*if (true) {
            returnErrorResponse(response, IMoocJSONResult.errorMsg("被one攔截..."));
        }
        
        return false;*/
    }
    
    /**
     * 請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後*/
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, 
            Object object, ModelAndView mv)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    /**
     * 在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行
     * (主要是用於進行資源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
            Object object, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    public void returnErrorResponse(HttpServletResponse response, JSONResult result)
            throws IOException, UnsupportedEncodingException {
        OutputStream out=null;
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } finally{
            if(out!=null){
                out.close();
            }
        }
    }
}

測試結果:

2.2  demo2

攔截網址:http://127.0.0.1:8088//IMooc/one/index

package com.example.demo.controller.interceptor;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.example.demo.bean.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
@RequestMapping("one")
public class OneController {

    @RequestMapping("/index")
    public String index(ModelMap map) {
        map.addAttribute("name", "imooc22");
        return "thymeleaf/index";
    }
    
    @RequestMapping("center")
    public String center() {
        return "thymeleaf/center/center";
    }

    @RequestMapping("test")
    public String test(ModelMap map) {
        
        User user = new User();
        user.setUserAge(18);
        user.setUserName("manager");
        user.setPassWord("123456");
        user.setBirthDay(new Date());
        
        map.addAttribute("user", user);
        
        
        User u1 = new User();
        u1.setUserAge(19);
        u1.setUserName("imooc");
        u1.setPassWord("123456");
        u1.setBirthDay(new Date());
        
        User u2 = new User();
        u2.setUserAge(17);
        u2.setUserName("LeeCX");
        u2.setPassWord("123456");
        u2.setBirthDay(new Date());
        
        List<User> userList = new ArrayList<>();
        userList.add(user);
        userList.add(u1);
        userList.add(u2);
        
        map.addAttribute("userList", userList);
        
        return "thymeleaf/test";
    }
    
    @PostMapping("postform")
    public String postform(User user) {
        System.out.println(user.getUserName());
        return "redirect:/th/test";
    }
}

攔截器配置呼叫類:

package com.example.demo.config;

import com.example.demo.controller.interceptor.OneInterceptor;
import com.example.demo.controller.interceptor.TwoInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 攔截器按照順序執行
         */
        //1    攔截所有
        //registry.addInterceptor(new OneInterceptor()).addPathPatterns("/*/**");

        //2    兩個攔截器按照順序攔截
        registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**");


        /*registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
                                                     .addPathPatterns("/one/**");
        registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");*/
        
        super.addInterceptors(registry);
    }

}

攔截器類A:

package com.example.demo.controller.interceptor;

import com.example.demo.tools.JSONResult;
import com.example.demo.tools.JsonUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

public class OneInterceptor implements HandlerInterceptor  {

    /**
     * 在請求處理之前進行呼叫(Controller方法呼叫之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
            Object object) throws Exception {
        
        System.out.println("被one攔截,放行...");
        return true;
        
        /*if (true) {
            returnErrorResponse(response, IMoocJSONResult.errorMsg("被one攔截..."));
        }
        
        return false;*/
    }
    
    /**
     * 請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, 
            Object object, ModelAndView mv)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    /**
     * 在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行
     * (主要是用於進行資源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, 
            Object object, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    public void returnErrorResponse(HttpServletResponse response, JSONResult result)
            throws IOException, UnsupportedEncodingException {
        OutputStream out=null;
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } finally{
            if(out!=null){
                out.close();
            }
        }
    }
}

測試結果

2.3  demo3 (單攔截器在前,對比檢視結果

訪問網址:(同上)

攔截器配置呼叫類:

package com.example.demo.config;

import com.example.demo.controller.interceptor.OneInterceptor;
import com.example.demo.controller.interceptor.TwoInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 攔截器按照順序執行
         */
        //1    攔截所有
        //registry.addInterceptor(new OneInterceptor()).addPathPatterns("/*/**");

        //2    兩個攔截器按照順序攔截
        /*registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**");*/

        //3    單攔截器在前,對比檢視結果
        registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
                                                     .addPathPatterns("/one/**");

        //4    單攔截器在後,對比檢視結果
        /*registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
                                                     .addPathPatterns("/one/**");
        registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");*/
        
        super.addInterceptors(registry);
    }

}

攔截器A(同上)

攔截器B

package com.example.demo.controller.interceptor;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.example.demo.tools.JSONResult;
import com.example.demo.tools.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


public class TwoInterceptor implements HandlerInterceptor  {

    final static Logger log = LoggerFactory.getLogger(TwoInterceptor.class);
    
    /**
     * 在請求處理之前進行呼叫(Controller方法呼叫之前)
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        
        if (true) {
            returnErrorResponse(response, JSONResult.errorMsg("被two攔截..."));
        }
        
        System.out.println("被two攔截...");
        
        return false;
    }
    
    /**
     * 請求處理之後進行呼叫,但是在檢視被渲染之前(Controller方法呼叫之後)
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    /**
     * 在整個請求結束之後被呼叫,也就是在DispatcherServlet 渲染了對應的檢視之後執行(主要是用於進行資源清理工作)
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub
        
    }
    
    public void returnErrorResponse(HttpServletResponse response, JSONResult result) throws IOException, UnsupportedEncodingException {
        OutputStream out=null;
        try{
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/json");
            out = response.getOutputStream();
            out.write(JsonUtils.objectToJson(result).getBytes("utf-8"));
            out.flush();
        } finally{
            if(out!=null){
                out.close();
            }
        }
    }
}

測試結果:

2.4  demo4(單攔截器在後,對比檢視結果)

訪問網址:(同上)

攔截器配置呼叫類:

package com.example.demo.config;

import com.example.demo.controller.interceptor.OneInterceptor;
import com.example.demo.controller.interceptor.TwoInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 攔截器按照順序執行
         */
        //1    攔截所有
        //registry.addInterceptor(new OneInterceptor()).addPathPatterns("/*/**");

        //2    兩個攔截器按照順序攔截
        /*registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**");*/

        //3    單攔截器在前,對比檢視結果
        /*registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
                                                     .addPathPatterns("/one/**");*/

        //4    單攔截器在後,對比檢視結果
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
                                                     .addPathPatterns("/one/**");
        registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        
        super.addInterceptors(registry);
    }

}

攔截器A(同上)

攔截器B(同上)

測試結果: