通过@RequestMapping注解可以定义不同的处理器映射规则。
1.URL路径映射
(1)@RequestMapping(value="item.action")或@RequestMapping("/item")[当参数值为多个时不可省略value=]
(2)value的值是数组,可以将多个url映射到同一个方法.如:@RequestMapping(value = { "itemList", "itemListAll" })
2.添加在类上面
在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头
可以使用此方法对url进行分类管理,如下:
@Controller
@RequestMapping("item")
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("itemList","itemListAll")//访问地址
public ModelAndView itemList(){
//从Mysql中查询
List<Item> list = itemService.selectItemsList();
ModelAndView mav = new ModelAndView();
//数据
mav.addObject("itemList", list);
mav.setViewName("itemList");
return mav;
}
@RequestMapping("/updates")
public ModelAndView updates(QueryVo vo) {
ModelAndView mav=new ModelAndView();
mav.setViewName("success");
return mav;
}
此时需要进入itemList()方法的请求url为:
http://localhost:8080/springmvc-web2/item/itemList.action
或者
http://localhost:8080/springmvc-web2/item/itemListAll.action
3.请求方法限定
除了可以对url进行设置,还可以限定请求进来的方法
(1)限定GET方法
@RequestMapping(method = RequestMethod.GET)
如果通过POST访问则报错:
HTTP Status 405 - Request method 'POST' not supported
例如:
@RequestMapping(value = "itemList",method = RequestMethod.POST)
(2)限定POST方法
@RequestMapping(method = RequestMethod.POST)
如果通过GET访问则报错:
HTTP Status 405 - Request method 'GET' not supported
(3)GET和POST都可以
@RequestMapping(method = {RequestMethod.GET,RequestMethod.POST})