提问者:小点点

Spring mvc 3:如何在拦截器中获取path变量?


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

非常感谢你!


共3个答案

匿名用户

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

有了这个,您将能够通过您为所有请求提供的病态变量的名称来读取@PathVariable。

匿名用户

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