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" 路径时,拦截器的逻辑将会执行。

相关推荐
刀法如飞4 天前
一款Go语言Gin框架MVC脚手架,满足大部分场景
go·mvc·gin
莫寒清5 天前
Spring MVC:@PathVariable 注解详解
java·spring·mvc
莫寒清8 天前
Spring MVC:@RequestParam 注解详解
java·spring·mvc
莫寒清8 天前
Spring MVC:MultipartFile 详解
java·spring·mvc
*.✧屠苏隐遥(ノ◕ヮ◕)ノ*.✧8 天前
JSP, MVC, El, JSTL, MAC
java·开发语言·mvc·mac·jsp
fchampion9 天前
最终一致性
java·spring·rabbitmq·github·mvc
好学且牛逼的马12 天前
从“Servlet汪洋”到“响应式时代”:Spring MVC 1.x到5.x演进全记录与核心知识点详解
spring·servlet·mvc
知识即是力量ol15 天前
口语八股——Spring 面试实战指南(二):事务管理篇、Spring MVC 篇、Spring Boot 篇、Bean生命周期篇
spring·面试·mvc·springboot·八股·事务管理·bean生命周期
weixin_4219947815 天前
MVC 模式初探
mvc·.net·.netcore