84560296 2020-01-05
controller层:
@GetMapping(value = "/api/users/{device}") public ResultDO get(@PathVariable("device") String device){ *** }
拦截器中:
public class ParameterInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //传统方式获取 String device = request.getParameter("device"); System.out.println("传统方式获取device: \t" + device); //map方式 Map map = (Map) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); System.out.println("map封装格式: \t" + map); return true; } *** }
配置拦截器:
@Configuration public class MyWebMvcConfig implements WebMvcConfigurer { @Autowired private ParameterInterceptor parameterInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(parameterInterceptor).addPathPatterns("/api/users/**"); } @Bean public ParameterInterceptor parameterInterceptor(){ return new ParameterInterceptor(); } }
运行sprinboot项目访问访问 URL: http://127.0.0.1:8080/api/users/andriod 测试,查看控制台输出:
传统方式获取device: null map封装格式: {device=andriod}
说明request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE)这种方式能获取到restful风格的参数