SpringMVC中拦截器的简单使用

步骤一:创建拦截器类

首先,我们需要创建一个拦截器类,该类需要实现HandlerInterceptor接口。这个接口定义了三个方法,分别在请求处理前、请求处理后和视图渲染后执行。

java 复制代码
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 在请求处理前执行,返回true表示继续执行后续操作,返回false表示终止执行
        System.out.println("拦截器:请求处理前");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理后执行,但在视图渲染前执行
        System.out.println("拦截器:请求处理后");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 在整个请求处理完毕后执行,包括视图渲染完毕
        System.out.println("拦截器:请求完成");
    }
}

步骤二:创建配置类

java 复制代码
import org.springframework.context.annotation.Bean;
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 MyInterceptorConfig extends WebMvcConfigurerAdapter {

    @Bean
    public MyInterceptor myInterceptor() {
        return new MyInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 注册拦截器并指定拦截路径
        registry.addInterceptor(myInterceptor()).addPathPatterns("/secured/**");
    }
}

上述配置类使用了@Configuration注解,表示这是一个配置类。通过@Bean注解将MyInterceptor注册为一个Bean,并在addInterceptors方法中配置拦截器的路径。

步骤三:应用示例

接下来,让我们创建一个简单的Controller,以及一个包含拦截逻辑的方法。

java 复制代码
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/secured/hello")
    @ResponseBody
    public String securedHello() {
        return "Hello from secured endpoint!";
    }
}

步骤四:测试

现在,当我们访问 "/secured/hello" 路径时,拦截器的逻辑将会执行。

相关推荐
William_cl19 小时前
一、前置基础(MVC学习前提)_核心特性_【C# 泛型入门】为什么说 List<T>是程序员的 “万能收纳盒“?避坑指南在此
学习·c#·mvc
程序员小凯2 天前
Spring MVC 分布式事务与数据一致性教程
分布式·spring·mvc
艾菜籽2 天前
SpringMVC练习:加法计算器与登录
java·spring boot·spring·mvc
程序员小凯2 天前
Spring MVC 多租户架构与数据隔离教程
spring·架构·mvc
艾菜籽3 天前
Spring Web MVC入门补充1
java·后端·spring·mvc
艾菜籽3 天前
Spring MVC入门补充2
java·spring·mvc
风兮w3 天前
MVC、MVP和MVVM的区别
mvc
蓝天智能4 天前
QT MVC中Model的特点及使用注意事项
qt·mvc
低音钢琴4 天前
【SpringBoot从初学者到专家的成长15】MVC、Spring MVC与Spring Boot:理解其差异与联系
spring boot·spring·mvc
.NET修仙日记4 天前
2025年ASP.NETMVC面试题库全解析
面试·职场和发展·c#·asp.net·mvc·面试题·asp.net mvc