欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringBoot整合拦截器

程序员文章站 2022-05-28 17:49:35
...

一 点睛

使用@Configuration配置拦截器

继承WebMvcConfigurerAdapter

重写addInterceptors添加需要的拦截器地址

二 实战

1 第一个拦截器

package com.imooc.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 org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.imooc.pojo.IMoocJSONResult;
import com.imooc.utils.JsonUtils;

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, IMoocJSONResult 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 第二个拦截器

package com.imooc.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.imooc.pojo.IMoocJSONResult;
import com.imooc.utils.JsonUtils;

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, IMoocJSONResult.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, IMoocJSONResult 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();
            }
        }
    }
}

3 配置拦截器

package com.imooc.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.imooc.controller.interceptor.OneInterceptor;
import com.imooc.controller.interceptor.TwoInterceptor;

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        /**
         * 拦截器按照顺序执行
         */
        registry.addInterceptor(new OneInterceptor()).addPathPatterns("/one/**");
        registry.addInterceptor(new TwoInterceptor()).addPathPatterns("/two/**")
                                                     .addPathPatterns("/one/**");

        
        super.addInterceptors(registry);
    }

}

4 编写针对第1个拦截器的控制器

package com.imooc.controller.interceptor;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.imooc.pojo.User;

@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.setAge(18);
        user.setName("manager");
        user.setPassword("123456");
        user.setBirthday(new Date());
        
        map.addAttribute("user", user);
        
        
        User u1 = new User();
        u1.setAge(19);
        u1.setName("imooc");
        u1.setPassword("123456");
        u1.setBirthday(new Date());
        
        User u2 = new User();
        u2.setAge(17);
        u2.setName("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.getName());
        return "redirect:/th/test";
    }
}

5 编写针对第2个拦截器的控制器

package com.imooc.controller.interceptor;

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

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.imooc.pojo.User;

@Controller
@RequestMapping("two")
public class TwoController {

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

    @RequestMapping("test")
    public String test(ModelMap map) {
        
        User user = new User();
        user.setAge(18);
        user.setName("manager");
        user.setPassword("123456");
        user.setBirthday(new Date());
        
        map.addAttribute("user", user);
        
        
        User u1 = new User();
        u1.setAge(19);
        u1.setName("itzixi");
        u1.setPassword("123456");
        u1.setBirthday(new Date());
        
        User u2 = new User();
        u2.setAge(17);
        u2.setName("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.getName());
        return "redirect:/th/test";
    }
}

三 测试

1 浏览器输入http://localhost:8080/one/index

浏览器输出:

{"status":500,"msg":"被two拦截...","data":null,"ok":null}

控制台输出:

被one拦截,放行...

被two拦截...

说明/index被拦截器one拦截、被two放行。