Spring MVC restful 路径小数点问题
来源:互联网 发布:mac电磁阀型号 编辑:程序博客网 时间:2024/06/01 10:50
之前有个小伙伴问了我一个问题,就是在使用Spring MVC的时候。当使用www.xxx.com/abc/1.11这个路径。然后在Controller使用@PathVariable注解来接收这个值的时候得到的却是1
,遇到这种情况如何解决。如果没有遇到过这种问题那么我们应该如何解决它呢?首先要解决这个问题我们先来看一下Spring MVC的原理图。如下:
- 在Spring MVC初始化的时候会把@RequestMapping解析生成请求url与对应页面控制器的关联关系 – Spring MVC @RequestMapping
- 当用户发送一个请求时来到前端控制器,前端控制器根据请求url来决定使用哪个页面控制器(也就是@Controller类中的@RequestMapping方法)进行处理并把请求委托给HanderAdpter。– Spring MVC DispatcherServlet
- 在调用这个页面控制器的前后会涉及到拦截器的调用,也就是HandlerIntercepter。
- 在调用完成页面控制器之后会返回ModelAndView对象。 最后通过页面渲染器(ViewResolver)把对应的页面模板以及数据进行渲染返回给请求。
其实在调用hander方法前后有2个动作就是对于HandlerMethod里面的请求参数解析(HandlerMethodArgumentResolver)以及返回参数解析(HandlerMethodReturnValueHandler)。现在主要的是讨论请求参数解析。
1、简单示例代码
为了模拟这种情况我们先来搭建一个项目,这里使用了Servlet3规范,所以不需要有web.xml文件。它使用java类来加载Servlet类。这个项目是非常简单的,一共就涉及到3个类。
1) 项目结构
2) pom.xml
使用maven管理jar包,引入相关的Jar包依赖。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.carlspace.spring</groupId> <artifactId>springboot-demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>springboot-demo</name> <url>http://maven.apache.org</url> <properties> <java.version>1.7</java.version> <servlet.api.version>3.1.0</servlet.api.version> <taglibs.version>1.1.2</taglibs.version> <jstl.version>1.2</jstl.version> </properties> <dependencies> <!-- spring core --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> </dependency> <!-- spring web --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <!-- servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>${servlet.api.version}</version> <scope>provided</scope> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>${taglibs.version}</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>${jstl.version}</version> </dependency> <!-- logger --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> </dependency> <!-- test --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>io.spring.platform</groupId> <artifactId>platform-bom</artifactId> <version>2.0.8.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>${java.version}</source> <target>${java.version}</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-war-plugin</artifactId> <version>2.4</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
3) MyMVCConfig.java
配置spring mvc容器相关组件。
@Configuration@EnableWebMvc@ComponentScan("com.carlspace.spring.mvc")public class MyMVCConfig extends WebMvcConfigurerAdapter{ @Bean public InternalResourceViewResolver viewResolver(){ InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("WEB-INF/classes/views/"); viewResolver.setSuffix(".jsp"); viewResolver.setViewClass(JstlView.class); return viewResolver; }// @Override// public void configurePathMatch(PathMatchConfigurer configurer) {// configurer.setUseSuffixPatternMatch(false);// }}
4) WebInitializer.java
加载Spring MVC容器到Servlet容器当中。
public class WebInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext servletContext) throws ServletException { AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext(); applicationContext.register(MyMVCConfig.class); Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(applicationContext)); servlet.addMapping("/"); servlet.setLoadOnStartup(1); }}
5) HelloController.java
@Controllerpublic class HelloController { @RequestMapping public String index(){ return "redirect:index"; } @RequestMapping("index") public String hello(){ return "index"; } @RequestMapping("index/{amount}") @ResponseBody public String test(@PathVariable BigDecimal amount, @RequestParam BigDecimal test){ System.out.println(amount); System.out.println(test); return "aaa"; } @RequestMapping("index/{amount}/{name}") @ResponseBody public String test1(@PathVariable BigDecimal amount, @RequestParam BigDecimal test, @PathVariable String name){ System.out.println(amount); System.out.println(test); return "aaa"; }}
2、问题分析
出现问题的url是http://localhost:8080/index/1.11?test=1.12。其中1.11会变成1.那么我们的问题就可以定位在请求参数的解析出错。那么相应的请求参数解析类是PathVariableMethodArgumentResolver。这个类是继承自AbstractNamedValueMethodArgumentResolver,我们来看一看它的解析。org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver#resolveArgument.
可以看到请求URI里面是1.11但是解析后是1.
在org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver#resolveName中可以看到最终是从request中的HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE获取值的。下面我们就来看看这个变量是如何生成的。
其实它的生成是在getHandler的时候,也就是我们需要找到对应Handler的时候。也就是我们最开始说Spring MVC原理的第二步的时候。org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping#handleMatch。
我们再来具体看一下在把这个值塞到request之前是如何获取的。同样是上面的方法,我们可以看一看:
decodedUriVariables = getUrlPathHelper().decodePathVariables(request, uriVariables);
这个方法从方法就可以看出它是从request里面获取Path variables。
再获取请求参数之前我们要注意一个变化那就是URI。
后面加了一个.*,也就是我们请求的URI是/index/{amount}
,但是Spring MVC把它解析成了/index/{amount}.*
。其实Spring MVC在初始化的时候会把RequestMapping里面的URI注册到一个Map里面。
再进行handler处理的时候会去找匹配的uri。org.springframework.web.servlet.mvc.condition.PatternsRequestCondition#getMatchingPattern。其实我们可以看到这个PatternsRequestCondition其实是RequestMappingInfo的一个属性。
在容器初始化的时候会把@RequestMapping方法解析成这个对象。下面是getMatchingPattern的具体方法。
private String getMatchingPattern(String pattern, String lookupPath) { if (pattern.equals(lookupPath)) { return pattern; } if (this.useSuffixPatternMatch) { if (!this.fileExtensions.isEmpty() && lookupPath.indexOf('.') != -1) { for (String extension : this.fileExtensions) { if (this.pathMatcher.match(pattern + extension, lookupPath)) { return pattern + extension; } } } else { boolean hasSuffix = pattern.indexOf('.') != -1; if (!hasSuffix && this.pathMatcher.match(pattern + ".*", lookupPath)) { return pattern + ".*"; } } } if (this.pathMatcher.match(pattern, lookupPath)) { return pattern; } if (this.useTrailingSlashMatch) { if (!pattern.endsWith("/") && this.pathMatcher.match(pattern + "/", lookupPath)) { return pattern +"/"; } } return null; }
但是Spring MVC中,在路径参数中如果带”.”的话“.”后面的值将会被忽略。例如访问http://http://localhost:8080/pathvar/xx.yy。Spring MVC就会把“.”后面的yy忽略。
所以它会自动加上.*进行匹配。
3、解决方法
既然我们已经清楚为什么会出现这个问题了。下面我们就来解析这个问题。解决问题方法有二:
方法一、找开MyMVCConfig类中注释的代码。
再次访问http://localhost:8080/index/1.11?test=1.12
会在控制台打出1.11
方法二:把带小数的url不写在末尾
此时也同样能够获取到正确的值。
- Spring MVC restful 路径小数点问题
- Spring MVC restful 路径小数点问题
- Spring MVC下,RESTful风格 与 静态资源(static resource)路径映射问题
- spring mvc如何匹配请求路径(restful接口写法)
- Restful Spring MVC
- Spring MVC Restful
- Restful Spring MVC
- spring mvc Restful架构
- spring MVC 乱码、restful
- Spring MVC Restful风格
- Spring MVC Restful构建中静态资源访问问题
- [spring mvc踩坑填坑]spring mvc文件上传路径问题
- 关于spring-mvc请求路径的问题
- Spring mvc redirect跳转路径问题
- spring mvc restful工程demo
- Spring MVC RESTFul Web Services
- spring mvc restful 传入List
- Spring MVC 相对路径
- 设计模式--单例模式
- Python写一个简单的神经网络
- C
- 平衡二叉树(Java实现)
- 良好的编程习惯
- Spring MVC restful 路径小数点问题
- System Verilog视频学习笔记(8)- Randomization
- MonkeyRunner
- Linux网络编程[DNS解析原理,了解相关DNS解析的函数]
- c#生成安装包程序和卸载程序
- scala实例——六
- 组件化架构漫谈
- 【JSP学习笔记(2)】——JavaScript应用
- 元素互不相邻的最大和子数组