简体   繁体   中英

How to add an interceptor to one specfic url in springboot?

I have a UserController class as below:

@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. 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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