0
@RestController()   
@RequestMapping(path = "/users") 

public class UserController {     

    @GetMapping()     

    public @ResponseBody  Page<User> getAllUsers(@RequestParam Integer pageSize, UserRequest userRequest) {
      //TODO: some implementation
}}

public class UserRequest{

    public String name;

    public String age;

}

send the request with invalid parameter, like localhost:8800/users?name1=1234, I want to return error. but in fact it ignore the invalid parameter name1.

I tried to add the user defined annotation on the method parameter and on the class , codes like below

@RestController() 
@RequestMapping(path = "/users")

@Validated

public class UserController {

    @GetMapping()     
    
    public @ResponseBody  Page<User> getAllUsers(@RequestParam @Validated Integer pageSize, @Validated UserRequest userRequest} {
    
      //TODO: some implementation
    }
}

But it does not working.

I think it is happened because framework has ignore the invalid parameter before the method was called.

where did framework handle the url and how can I do to make it return error instead of ignore?

monica
  • 1
  • 1

1 Answers1

0

You can reject parameters that are not valid. You can do so in a HandlerInterceptor class.

Reference: Rejecting GET requests with additional query params

In addition to what is done in the above reference, in your addInterceptors, you can specify the path that is intercepted.

Like this:

@Configuration
public class WebConfig implements WebMvcConfigurer {

    private String USERS_PATH = "/users";
    
    // If you want to cover all endpoints in your controller
    // private String USERS_PATH = List.of("/users", "/users/**");

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new FooHandlerInterceptor()).addPathPatterns(USERS_PATH);
    }
} 
Marc Bannout
  • 388
  • 4
  • 15