简体   繁体   中英

Check if a controller has a @RequestHeader dynamically (in a test)

Using SpringBoot I managed to get the list of all controllers dynamically (in a test) using RequestMappingHandlerMapping , but I cannot check if the controller uses the @RequestHeader("language") or not. Is there a way to retrieve this information? I don't think it's possible from RequestMappingHandlerMapping .

Thanks.

public void randomApi(@PathVariable("user") String user,
                      @RequestHeader("language") String language){...}

RequestMappingHandlerMapping represents all controller methods, you have to get a particular controller method that you are interested from it first. The easiest way to do it is first give a name to the controller method such as GetRandomApi :

@GetMapping(name = "GetRandomApi" , value= "/random")
public void randomApi(@PathVariable("user") String user, @RequestHeader("language") String language){

}

and then get the controller method by this name:

HandlerMethod hm = mapping.getHandlerMethodsForMappingName("GetRandomApi").get(0);

Please note HandlerMethod represents a controller method and I assume you only has one controller method with this name.

To check if this controller method has a parameter which is annotated with @RequestHeader , you can do something likes:

for( MethodParameter param : hm.getMethodParameters()){     
        RequestHeader requestHeader = param.getParameterAnnotation(RequestHeader.class);
        if(requestHeader != null) {
            System.out.println(String.format("parameter index %s is annotated with @RequestHeader with the value %s", 
            param.getParameterIndex(), 
            requestHeader.value()));
        }
}

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