当前位置: 代码迷 >> VC/MFC >> 小结上spring mvc中的@RequestMapping的用法
  详细解决方案

小结上spring mvc中的@RequestMapping的用法

热度:8421   发布时间:2013-02-26 00:00:00.0
小结下spring mvc中的@RequestMapping的用法。

?http://jackyrong.iteye.com/blog/1806326

?

小结下spring mvc中的@RequestMapping的用法。?

1)最基本的,方法级别上应用,例如:?
???

Java代码??收藏代码
  1. @RequestMapping(value="/departments")??
  2. public?String?simplePattern(){??
  3. ??
  4. ??System.out.println("simplePattern?method?was?called");??
  5. ??return?"someResult";??
  6. ??
  7. }??


?? 则访问http://localhost/xxxx/departments的时候,会调用 simplePattern方法了?

2) 参数绑定?
??

Java代码??收藏代码
  1. @RequestMapping(value="/departments")??
  2. public?String?findDepatment(??
  3. ??@RequestParam("departmentId")?String?departmentId){??
  4. ????
  5. ????System.out.println("Find?department?with?ID:?"?+?departmentId);??
  6. ????return?"someResult";??
  7. ??
  8. }??


???
? 形如这样的访问形式:?

?? /departments?departmentId=23就可以触发访问findDepatment方法了?

3 REST风格的参数?
??

Java代码??收藏代码
  1. @RequestMapping(value="/departments/{departmentId}")??
  2. public?String?findDepatment(@PathVariable?String?departmentId){??
  3. ??
  4. ??System.out.println("Find?department?with?ID:?"?+?departmentId);??
  5. ??return?"someResult";??
  6. ??
  7. }??


??
? 形如REST风格的地址访问,比如:?
/departments/23,其中用(@PathVariable接收rest风格的参数?

4 REST风格的参数绑定形式之2?
?? 先看例子,这个有点象之前的:?

Java代码??收藏代码
  1. @RequestMapping(value="/departments/{departmentId}")??
  2. public?String?findDepatmentAlternative(??
  3. ??@PathVariable("departmentId")?String?someDepartmentId){??
  4. ??
  5. ????System.out.println("Find?department?with?ID:?"?+?someDepartmentId);??
  6. ????return?"someResult";??
  7. ??
  8. }??



?? 这个有点不同,就是接收形如/departments/23的URL访问,把23作为传入的departmetnId,,但是在实际的方法findDepatmentAlternative中,使用?
@PathVariable("departmentId") String someDepartmentId,将其绑定为?
someDepartmentId,所以这里someDepartmentId为23?

5 url中同时绑定多个id?
?

Java代码??收藏代码
  1. @RequestMapping(value="/departments/{departmentId}/employees/{employeeId}")??
  2. public?String?findEmployee(??
  3. ??@PathVariable?String?departmentId,??
  4. ??@PathVariable?String?employeeId){??
  5. ??
  6. ????System.out.println("Find?employee?with?ID:?"?+?employeeId?+???
  7. ??????"?from?department:?"?+?departmentId);??
  8. ????return?"someResult";??
  9. ??
  10. }??



?? 这个其实也比较好理解了。?

6 支持正则表达式?
??

Java代码??收藏代码
  1. @RequestMapping(value="/{textualPart:[a-z-]+}.{numericPart:[\\d]+}")??
  2. public?String?regularExpression(??
  3. ??@PathVariable?String?textualPart,??
  4. ??@PathVariable?String?numericPart){??
  5. ??
  6. ????System.out.println("Textual?part:?"?+?textualPart?+???
  7. ??????",?numeric?part:?"?+?numericPart);??
  8. ????return?"someResult";??
  9. }??



?? 比如如下的URL:/sometext.123,则输出:?
Textual part: sometext, numeric part: 123.?

  相关解决方案