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:
xxxxxxxxxx
1
WebRequest webRequest = ...
2
3
String requestUri = ((ServletWebRequest)webRequest).getRequest().getRequestURI();
Request URI can be useful when we work with interceptors.
RequestUtils.java
file:
xxxxxxxxxx
1
package com.example.config;
2
3
import org.springframework.web.context.request.ServletWebRequest;
4
import org.springframework.web.context.request.WebRequest;
5
6
import javax.servlet.http.HttpServletRequest;
7
8
public class RequestUtils {
9
10
public static String getRequestUri(WebRequest webRequest)
11
{
12
HttpServletRequest servletRequest = ((ServletWebRequest)webRequest).getRequest();
13
14
return httpServletRequest.getRequestURI();
15
}
16
}
Usage example:
xxxxxxxxxx
1
package com.example.config;
2
3
import org.springframework.context.annotation.Configuration;
4
import org.springframework.ui.ModelMap;
5
import org.springframework.web.context.request.ServletWebRequest;
6
import org.springframework.web.context.request.WebRequest;
7
import org.springframework.web.context.request.WebRequestInterceptor;
8
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
9
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
10
11
import javax.servlet.http.HttpServletRequest;
12
13
14
public class WebConfig implements WebMvcConfigurer
15
{
16
17
public void addInterceptors(InterceptorRegistry registry)
18
{
19
registry.addWebRequestInterceptor(new WebRequestInterceptor() {
20
21
22
public void preHandle(WebRequest request) throws Exception {
23
String requestUri = RequestUtils.getRequestUri(request); // <-- Request URI
24
System.out.println("requestUri=" + requestUri);
25
}
26
27
28
public void postHandle(WebRequest request, ModelMap model) throws Exception {
29
// some code here ...
30
}
31
32
33
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
34
// some code here ...
35
}
36
});
37
}
38
}