在Spring MVC控制器中,可以使用@PathVariable获取@RequestMapping中定义的变量的值。那么在拦截器中如何获取该变量的值呢?
非常感谢!
非常感谢!
对我来说,Pao链接的线程非常有用。
在preHandle()方法中,您可以通过运行以下代码提取各种PathVariables
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
添加拦截器。
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 {
}
}
注册拦截器。
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);
}
}
虽然晚了近一年,但我还是想说:
String[] requestMappingParams = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).params()
for (String value : requestMappingParams) {...
should help
在Spring论坛中有一个帖子,有人说没有“简单的方法”,所以我认为你需要解析URL来获取它。
String value= (String) pathVariables.get("yourPathVarName");
。就是这样。这应该被标记为答案。 - spiderman@ControllerAdvice
和@ExceptionHandler
。谢谢。 - Andreas