32

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

非常感谢!

4

4 回答 4

87

Pao 所链接的主题对我来说是一种享受

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

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 
于 2014-05-05T08:52:27.627 回答
5

添加拦截器。

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。

于 2020-12-30T07:12:00.310 回答
4

几乎为时已晚 1 年,但是:

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

         for (String value : requestMappingParams) {...

应该有帮助

于 2013-08-06T14:04:18.570 回答
4

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

于 2012-09-03T15:44:18.083 回答