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

Leo*_*eon 22 spring path-variables interceptor

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

非常感谢你!

ash*_*rio 71

由Pao链接的线程为我做了一个款待

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

Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 
Run Code Online (Sandbox Code Playgroud)

  • 然后`String value =(String)pathVariables.get("yourPathVarName");`就是这样.这应该标记为答案 (9认同)

Aru*_*ngh 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 {
    }
}
Run Code Online (Sandbox Code Playgroud)

注册拦截器。

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,您将能够通过为所有请求的路径变量指定的名称来读取@PathVariable。


Pao*_*Pao 4

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