在拦截器中获取url路径里面@PathVariable的参数值
解决办法
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
String classId = (String)pathVariables.get("classId");
示例接口
// 获取某个班级下面的学生列表 @RequestMapping("/classes/{classId}/students")
public String list(@PathVariable String classId){
return "学生列表";
}
拦截器完整示例
package com.example.demo;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;
public class SpringMVCInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
Map pathVariables = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
String chatbotId = (String)pathVariables.get("classId");
System.out.println("classId: " + classId);
if ("1234".equals(classId))
return true;
return false;
}
@Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
// TODO Auto-generated method stub
}
}
package com.example.demo;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
@Configuration
public class MvcInterceptorConfig extends WebMvcConfigurationSupport{
@Override
protected void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new SpringMVCInterceptor()).addPathPatterns("/classes/**");
super.addInterceptors(registry);
}
}
以上是 在拦截器中获取url路径里面@PathVariable的参数值 的全部内容, 来源链接: utcz.com/z/516786.html