Spring MVC 3:如何在拦截器中获取路径变量?

38
在Spring MVC控制器中,可以使用@PathVariable获取@RequestMapping中定义的变量的值。那么在拦截器中如何获取该变量的值呢?
非常感谢!
4个回答

97

对我来说,Pao链接的线程非常有用。

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

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 

14
然后,String value= (String) pathVariables.get("yourPathVarName");。就是这样。这应该被标记为答案。 - spiderman
1
完美,示例代码也适用于@ControllerAdvice@ExceptionHandler。谢谢。 - Andreas
有没有办法在preHandle方法中更新这个路径变量?例如:将“yourPathVarName from”测试<script>的值更新为“test”。 - TomJava

6

添加拦截器。

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。

4

虽然晚了近一年,但我还是想说:

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

         for (String value : requestMappingParams) {...

should help


1
这似乎有助于检索RequestParams,但我不知道如何使用这种方法获取PathVariables的值。 - chrismarx

4

在Spring论坛中有一个帖子,有人说没有“简单的方法”,所以我认为你需要解析URL来获取它。


1
实际上,@ashario在上面的回答(https://dev59.com/rGct5IYBdhLWcg3wPK-B#23468496)表明它是可以完成的。 - Philippe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接