一 @RequestMapping注解
定义controller方法对应的url,进行处理器映射的使用
1 为了对url进行分类管理,可以定义根路径,最终访问路径url是:根路径+子路径

例:图中请求路径 :/items/queryItems
2 限制http请求方法
1 首先在form表单中设置提交方式为post

2 在controller中限制访问请求为get


3 在controller中限制访问请求为get和post


二 controller方法返回值
1 返回 ModelAndView
需要方法结束时,定义ModelAndView,将model和view分别进行设置
public ModelAndView queryItems() throws Exception {
List<ItemsCustom> list = itemsService.findItemsList(null);
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("items", list);
modelAndView.setViewName("index");
return modelAndView;
}
2 返回 String
(1)如果controller方法返回String,表示返回逻辑视图名。
真正视图(jsp路径)=前缀+逻辑视图+后缀
@RequestMapping("/queryItems")
public String queryItems(Model model) throws Exception {
List<ItemsCustom> list = itemsService.findItemsList(null);
model.addAttribute("items", list);
return "index";
}

(2)redirect 重定向
特点:url地址会发生变化。修改提交的request数据无法传到重定向的地址,因为重定向后重新进行request。(request无法共享)
@RequestMapping(value = "/editItemsSubmit",method = {RequestMethod.GET,RequestMethod.POST})
public String editItemsSubmit() throws Exception {
return "redirect:/items/queryItems.action";
}
(3)forward 页面转发
特点:url地址不会发生变化。request可以共享
@RequestMapping(value = "/editItemsSubmit",method = {RequestMethod.GET,RequestMethod.POST})
public String editItemsSubmit() throws Exception {
return "forward:/items/queryItems.action";
}

(4) 小结
通过上面例子我们可以发现在创建controller方法时,可以携带参数。例如
public String queryItems(Model model) throws Exception
public String queryItems(public String editItemsSubmit(HttpServletRequest request) throws Exception) throws Exception
3 返回 void
在controller方法形参上可以定义request和response,使用request或response指定响应结果
(1)使用request转向页面
request.getRequestDispatcher("url").forward(request,response);
(2)通过response页面重定向
response.sendRedirect("url");
(3)指定响应结果
response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
网友评论