通过@RequestMapping注解可以定义不同的处理器映射规则。
之前我们也经常编写URL路径映射,大致可以写为:
@RequestMapping("/item")或者
@RequestMapping(value="/item")value的值是数组,所以可以将多个url映射到同一个方法上。
或者
value=“占位符”,@PathVariable是用来获得请求url中的动态参数的 @Controller @RequestMapping("page") public class PageController { @RequestMapping(value = "/user/{userId}/roles/{roleId}", method = RequestMethod.GET) public String toPage(@PathVariable("userId") String userId,@PathVariable("roleId") String roleId) { System.out.println("User Id : " + userId); System.out.println("Role Id : " + roleId); return "hello"; } }在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头,通过此方法对url进行分类管理。如下:@RequestMapping放在类名上边,设置请求前缀。
@Controller @RequestMapping("/item") public class ItemController { ... }然后在方法名上边设置请求映射url,即@RequestMapping注解应放在方法名上边,如下:
@RequestMapping("/itemList") public ModelAndView getItemsList() { // 查询商品列表 List<Items> itemList = itemService.getItemList(); // 把查询结果传递给页面 ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("itemList", itemList); // addObject方法相当于放到request域上 // 设置逻辑视图 modelAndView.setViewName("itemList"); // 返回结果 return modelAndView; }最后在浏览器中输入地址进行访问时,访问地址应为:http://localhost:8080/springmvc-web2/item/itemList.action。
限定GET方法:@RequestMapping(method = RequestMethod.GET)。 如果通过post方式访问则报错: 以例明示:
@RequestMapping(value="/updateitem",method={RequestMethod.GET})限定POST方法:@RequestMapping(method = RequestMethod.POST)。 如果通过get方式访问则报错: 以例明示:
@RequestMapping(value="/updateitem",method={RequestMethod.POST})GET和POST都可以:@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})。 以例明示:
@RequestMapping(value="/updateitem",method={RequestMethod.POST,RequestMethod.GET})注意,这儿可能有中文乱码问题,大家须谨慎对待。