繁体   English   中英

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

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

我有一个 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);
    }
}

现在我只想向/user/roleChange添加一个拦截器。 我知道您可以使用.excludePathPatterns()排除所有其他路径,但我只是好奇是否有办法为拦截器指定一个路径。 谢谢!

下面是拦截器的示例代码

@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;
    }
}

在此我为拦截器注册了“/user”。

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

暂无
暂无

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

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