In Spring MVC controller, I can get path variable using @PathVariable to get the value of a variable defined in @RequestMapping. How can I get the value of the variable in an interceptor?
Thank you very much!
In Spring MVC controller, I can get path variable using @PathVariable to get the value of a variable defined in @RequestMapping. How can I get the value of the variable in an interceptor?
Thank you very much!
The thread linked to by Pao worked a treat for me
In the preHandle() method you can extract the various PathVariables by running the following code
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
Add a Interceptor.
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.TreeMap;
@Component
public class MyHandlerInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Map map = new TreeMap<>((Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE));
Object myPathVariableValue = map.get("myPathVariableName");
// some code around myPathVariableValue.
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
Register the Interceptor.
import com.intercept.MyHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ConditionalOnProperty(name = "mongodb.multitenant.enabled", havingValue = "false")
public class ResourceConfig implements WebMvcConfigurer {
@Autowired
MyHandlerInterceptor webServiceTenantInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(webServiceTenantInterceptor);
}
}
With this you will be able to read the @PathVariable by the name you have given to the pathvariable for all the request made.
There is a thread in the Spring forums, where someone says, there is no "easy way", so i suppose you would have to parse the URL to get it.
Almost 1 year too late, but:
String[] requestMappingParams = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).params()
for (String value : requestMappingParams) {...
should help