EN
Spring - get request URI from WebRequest
8
points
In this short article, we would like to show how to get a request URI from WebRequest.
Quick solution:
WebRequest webRequest = ...
String requestUri = ((ServletWebRequest)webRequest).getRequest().getRequestURI();
Practical example
Request URI can be useful when we work with interceptors.
RequestUtils.java file:
package com.example.config;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import javax.servlet.http.HttpServletRequest;
public class RequestUtils {
public static String getRequestUri(WebRequest webRequest)
{
HttpServletRequest servletRequest = ((ServletWebRequest)webRequest).getRequest();
return httpServletRequest.getRequestURI();
}
}
Usage example:
package com.example.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.ui.ModelMap;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import javax.servlet.http.HttpServletRequest;
@Configuration
public class WebConfig implements WebMvcConfigurer
{
@Override
public void addInterceptors(InterceptorRegistry registry)
{
registry.addWebRequestInterceptor(new WebRequestInterceptor() {
@Override
public void preHandle(WebRequest request) throws Exception {
String requestUri = RequestUtils.getRequestUri(request); // <-- Request URI
System.out.println("requestUri=" + requestUri);
}
@Override
public void postHandle(WebRequest request, ModelMap model) throws Exception {
// some code here ...
}
@Override
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
// some code here ...
}
});
}
}