简体   繁体   English

如何在springboot中向一个特定的url添加拦截器?

[英]How to add an interceptor to one specfic url in springboot?

I have a UserController class as below:我有一个 UserController 类如下:

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/create")
    public Map<String, Object> createAccount(User user) {
        return userService.createAccount(user);
    }

    @PostMapping("/login")
    public Map<String, Object> accountLogin(User user) {
        return userService.accountLogin(user);
    }

    @GetMapping("/activate")
    public Map<String, Object> activateAccount(String confirmationCode) {
        return userService.activateAccount(confirmationCode);
    }

    @PostMapping("/roleChange")
    public Map<String, Object> setUserRole(String uuid, String email, String roleId){
        return userService.setUserRole(uuid, email, roleId);
    }
}

Now I wanna add an interceptor to /user/roleChange only.现在我只想向/user/roleChange添加一个拦截器。 I know you can exclude all the other paths with .excludePathPatterns() but I'm just curious if there's a way to specify one path for the interceptor.我知道您可以使用.excludePathPatterns()排除所有其他路径,但我只是好奇是否有办法为拦截器指定一个路径。 Thank you!谢谢!

Below is the sample code for interceptor下面是拦截器的示例代码

@Configuration
public class AppConfig implements WebMvcConfigurer {

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/user");
    }
}

public class CustomInterceptor implements HandlerInterceptor {

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("Hello..");
        return true;
    }
}

In this I have register "/user" for interceptor.在此我为拦截器注册了“/user”。

registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/user"); registry.addInterceptor(new CustomInterceptor()).addPathPatterns("/user");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM