Search code examples
javaspringspring-bootinterceptor

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!


Solution

  • 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");