其他分享
首页 > 其他分享> > 框架 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(同上)

测试结果:

 

 

 

标签:12,Spring,拦截器,registry,new,import,addPathPatterns,public
来源: https://www.cnblogs.com/1446358788-qq/p/14197423.html