SpringMVC3:如何在拦截器中获取路径变量?

SpringMVC3:如何在拦截器中获取路径变量?,spring,interceptor,path-variables,Spring,Interceptor,Path Variables,在SpringMVC控制器中,我可以使用@PathVariable获取路径变量,以获取@RequestMapping中定义的变量的值。如何在拦截器中获取变量的值 多谢各位 在春季论坛中有一个论坛,有人说,没有“简单的方法”,所以我想你必须解析URL才能获得它。几乎晚了一年,但是: String[] requestMappingParams = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).p

在SpringMVC控制器中,我可以使用@PathVariable获取路径变量,以获取@RequestMapping中定义的变量的值。如何在拦截器中获取变量的值


多谢各位

在春季论坛中有一个论坛,有人说,没有“简单的方法”,所以我想你必须解析URL才能获得它。

几乎晚了一年,但是:

         String[] requestMappingParams = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class).params()

         for (String value : requestMappingParams) {...

应该有帮助

Pao链接的帖子对我来说很有用

在preHandle()方法中,可以通过运行以下代码来提取各种PathVariable

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);
    }
}

使用此方法,您将能够通过为所有请求指定的PathVariable名称来读取@PathVariable。

这对于检索RequestParams似乎很有用,但我不知道如何使用此方法获取PathVariable的值,然后
String value=(String)PathVariables.get(“yourPathVarName”)就是这样。这应该标记为answerPerfect,示例代码也适用于
@ControllerAdvice
@ExceptionHandler
。谢谢,我们有没有办法在预处理方法中更新这个path变量?例如:“yourPathVarName from”的值在测试之间进行测试。实际上上面@ashario()给出的答案表明这是可以做到的。