1.@RequestMapping可以限制http的请求方法:
例如:
@RequestMapping(value = "/editItems",method = {RequestMethod.POST})
则访问/editItems时只能通过post方式请求获取资源,地址栏直接输入localhost:8080/editItems.action则会报错说,不支持get请求,,可起到拦截get请求的作用,method = {RequestMethod.POST,RequestMethod.GET},method是个数组,可添加允许多个
controller的String返回方法:
2.controller方法的返回值:
1.返回ModelAndView
需要方法结束时,定义ModelAndView,将model和view分别进行设置
2。返回String:
如果controller方法返回string,表示返回逻辑视图名
真正视图(jsp的路经)=前缀+逻辑视图名+后缀
@RequestMapping(value = "/editItems",method = {RequestMethod.POST})
public String editItems(Model model) throws Exception {
//model要调用service获取
ItemsCustom itemsCustom=itemsService.finItemById(1);
ModelAndView modelAndView = new ModelAndView();
// List<Items> itemsList = itemsService.finditemsList();
//将商品信息放到model
/* modelAndView.addObject("itemsCustom", itemsCustom);
//指定view
modelAndView.setViewName("/items/editItems");*/
//通过形参中的model将model数据传到页面
//相当于 modelAndView.addObject("itemsCustom", itemsCustom);
model.addAttribute("itemsCustom", itemsCustom);
//相当于 modelAndView.setViewName("/items/editItems");
return "/items/editItems";
}
2.1 redirect重定向
商品修改提交后,重定向到商品查询列表。
redirect重定向的特点:浏览器地址栏的url会变化,修改提交的request数据无法传到重定向的地址,因为重定向后进行重新request(request无法共享)
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit()throws Exception{
ModelAndView modelAndView=new ModelAndView();
//调用service更新商品信息,页面需将商品信息传到此方法
//...............
// modelAndView.setViewName("success");
//return modelAndView;
//因为在一个controller里面,所以地址可以不用加根路径
return "redirect:queryItems.action";
}
2.2 forward页面转发
特点:通过forward页面转发,浏览器地址url不变,request可以共享
测试用法如下:
@RequestMapping("/editItemsSubmit")
public String editItemsSubmit(HttpServletRequest request)throws Exception{
ModelAndView modelAndView=new ModelAndView();
//调用service更新商品信息,页面需将商品信息传到此方法
//...............
// modelAndView.setViewName("success");
//return modelAndView;
//因为在一个controller里面,所以地址可以不用加根路径
return "forward:queryItems.action";
}
获取request共享的id
@RequestMapping("/queryItems")
public ModelAndView queryItems(HttpServletRequest request) throws Exception {
System.out.println(request.getParameter("id"));
// System.out.println(request.getParameter("name"));
记录一个坑:这里如果 我的
<form action="${pageContext.request.contextPath}/editItemsSubmit.action" method="get" id="itemForm" enctype="multipart/form-data">
提交方式写成post,则request.getParameter("id")获取的值为空,写成get的提交方式,则能获取到值
3.返回void