spring boot 拦截器例子

在Spring Boot中,拦截器是通过实现`HandlerInterceptor`接口来实现的。它允许你在请求到达控制器方法之前和之后执行自定义的逻辑。下面我将为你提供一个简单的Spring Boot拦截器的例子。

假设我们有一个简单的控制器类`UserController`,其中有两个请求处理方法:`getUser`和`saveUser`,我们希望在每次请求这两个方法前后记录日志。

1. 创建一个拦截器类 `LoggingInterceptor` 实现 `HandlerInterceptor` 接口:

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

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Before handling request. URL: " + request.getRequestURL());
        return true; // Returning true allows the request to continue to the controller method. Returning false will stop the request.
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("After handling request. URL: " + request.getRequestURL());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // This method is called after the view rendering is complete.
        // It can be used for resource cleanup tasks.
    }
}

2. 在Spring Boot中注册拦截器,创建一个配置类`InterceptorConfig`:

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

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {

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

3. 创建一个简单的`UserController`:

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @GetMapping("/user")
    public String getUser(@RequestParam("id") String userId) {
        System.out.println("Getting user: " + userId);
        return "User: " + userId;
    }

    @PostMapping("/user")
    public String saveUser(@RequestParam("name") String username) {
        System.out.println("Saving user: " + username);
        return "Saved user: " + username;
    }
}

4. 运行Spring Boot应用,然后通过浏览器或者API请求测试:

当访问`http://localhost:8080/user?id=123`时,控制台输出:


Before handling request. URL: http://localhost:8080/user?id=123
Getting user: 123
After handling request. URL: http://localhost:8080/user?id=123
 

当通过POST请求`http://localhost:8080/user`,参数为`name=John Doe`时,控制台输出:


Before handling request. URL: http://localhost:8080/user
Saving user: John Doe
After handling request. URL: http://localhost:8080/user
 

以上就是一个简单的Spring Boot拦截器的例子,它会在请求到达控制器方法前后记录日志。实际应用中,你可以根据需要在拦截器中添加更多的逻辑,比如权限验证、异常处理等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

田猿笔记

写文章不容易,希望大家小小打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值