SpringBoot学习(3) —— 拦截器

拦截器可以拦截对Controller的请求

一. 创建Interceptor方法

package com.xdu.studyspringboot.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

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

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器的方法");
        return true;
    }
}

二. 创建Interceptor配置类

package com.xdu.studyspringboot.config;

import com.xdu.studyspringboot.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration     //添加注解
public class InterceptorConfig implements WebMvcConfigurer {
    @Bean
    public LoginInterceptor loginInterceptor(){
        return new LoginInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //指定拦截的请求
        String[] path = new String[]{"/user/**"};
        //指定不拦截的请求
        String[] excludePath = new String[]{"/user/login"};

        registry.addInterceptor(loginInterceptor())           //添加拦截器
                .addPathPatterns(path)                 //添加拦截请求
                .excludePathPatterns(excludePath);     //添加不拦截的请求
    }
}

三. 测试

package com.xdu.studyspringboot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestController {
    @RequestMapping("/user/account")
    @ResponseBody
    public String UserAccount(){
        return "访问user/account地址";
    }

    @RequestMapping("/user/login")
    @ResponseBody
    public String userLogin(){
        return "访问user/login地址";
    }
}

当访问/user/account时,会执行拦截器方法;当访问/user/login时,不会执行拦截器方法

你可能感兴趣的:(SpringBoot,SpringBoot)