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拦截器的例子,它会在请求到达控制器方法前后记录日志。实际应用中,你可以根据需要在拦截器中添加更多的逻辑,比如权限验证、异常处理等。

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