@pathvariable 注解

Posted on 2017-01-16 09:09  Ninsh  阅读(5257)  评论(0编辑  收藏  举报

1.4. @PathVariable 注解

 

带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。

[java] view plain copy
 
  1. /** 
  2.      * localhost:8080/springmvc/hello/pathVariable/bigsea 
  3.      * localhost:8080/springmvc/hello/pathVariable/sea 
  4.      * 这些URL 都会 执行此方法 并且将  <b>bigsea</b>、<b>sea</b> 作为参数 传递到name字段 
  5.      * @param name 
  6.      * @return 
  7.      */  
  8.     @RequestMapping("/pathVariable/{name}")  
  9.     public String pathVariable(@PathVariable("name")String name){  
  10.         System.out.println("hello "+name);  
  11.         return "helloworld";  
  12.     }  

JSP(这里指定全路径):

[java] view plain copy
 
  1. <h1>pathVariable</h1>  
  2. <a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>  
  3. <br/>  
  4. <a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>  
  5. <br/>  

运行结果:

[plain] view plain copy
 
  1. hello bigsea  
  2. hello sea