SpringBoot复习:(61)拦截器(HandlerInterceptor)的用法

一、自定义拦截器:

package cn.edu.tju.interceptor;


import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

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


public class MyInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        System.out.println("Servlet path is : " +request.getServletPath());

        return true;
    }
}

二、通过WebMvcConfigurer配置拦截器

package cn.edu.tju.config;


import cn.edu.tju.component.MyDateConverter;
import cn.edu.tju.interceptor.MyInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfig implements WebMvcConfigurer {



    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }
}


异常时,postHandle不会执行。afterCompletion会执行

过滤器先于拦截器执行。

package cn.edu.tju.config;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;


@Component
public class MyFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        System.out.println("in my filter【before]......");
        chain.doFilter(request, response);
        System.out.println("in my filter【after】......");
    }

    public void destroy() {
        System.out.println("after response......");
    }
}




package cn.edu.tju;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
@ServletComponentScan
public class Start {
    public static void main(String[] args) {
        SpringApplication.run(Start.class, args);
    }
}

你可能感兴趣的:(SpringBoot,spring,boot,后端,java)