3

I need to submit request URL as a String parameter to a method

@RequestMapping(value = "/test", method = RequestMethod.POST)
public void testItt(@RequestParam String requestParameter, @RequestURL String requestUrl) { 
   // Do something with requestUrl 
} 

How to submit Request URL correctly?

I tried request.getRequestURL().toString()

But I feel there must be a better way.

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
john
  • 647
  • 5
  • 23
  • 53

1 Answers1

8

Never just grab the URL from the request. This is too easy! programming is supposed to be hard and when it's not hard, you MAKE it hard! :)

But you can retrieve the URL the way you show up above

So lets start off with an annotation that represents the value you want to retrieve

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.PARAMETER)
public @interface RequestURL {
}

This will work as a way to inject the value you already have access to.

Next we need to create a class that can build the URL string

public class RequestUrlArgumentResolver
   implements HandlerMethodArgumentResolver {

   @Override
   public boolean supportsParameter(MethodParameter methodParameter) {
       return methodParameter.getParameterAnnotation(RequestURL.class) != null;
   }

   @Override
   public Object resolveArgument(
     MethodParameter methodParameter, 
     ModelAndViewContainer modelAndViewContainer, 
     NativeWebRequest nativeWebRequest, 
     WebDataBinderFactory webDataBinderFactory) throws Exception {

        HttpServletRequest request 
          = (HttpServletRequest) nativeWebRequest.getNativeRequest();

        //Nice and cozy at home surrounded by safety not obfuscation
        return request.getRequestURL().toString();
    }
}

Next thing we need to do is get the framework to recognize the handler for this annotation.

add the method below to your configuration (If your config does not implement WebMvcConfigurer you may need to implement this class or create a new config which does and include the new config)

...
@Override
public void addArgumentResolvers(
  List<HandlerMethodArgumentResolver> argumentResolvers) {
    argumentResolvers.add(new RequestUrlArgumentResolver());
}
...

Then finally we are back to your original request mapping and it should work as originally written

@RequestMapping(value = "/test", method = RequestMethod.POST)
    public void testItt(@RequestParam String requestParameter, 
                        @RequestURL String requestUrl) { 
   // Do something with requestUrl 
} 

Credits - https://www.baeldung.com/spring-mvc-custom-data-binder

Zergleb
  • 2,212
  • 15
  • 24