SpringMVC学习——Controller类的方法返回值
返回ModelAndView
Controller类方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。之前我就已讲过,在此并不过多赘述。
返回void
在Controller类方法形参上可以定义request和response,使用request或response指定响应结果:
- 使用request转向页面,如下: request.getRequestDispatcher("页面路径").forward(request, response); 之前我们实现商品列表的查询,返回的是ModelAndView,如果现在该方法的返回值是void,那么就应使用request跳转页面,如下: @RequestMapping("/itemList2") public void itmeList2(HttpServletRequest request, HttpServletResponse response) throws Exception { // 查询商品列表 List<Items> itemList = itemService.getItemList(); // 向页面传递参数 request.setAttribute("itemList", itemList); // 如果使用原始的方式做页面跳转,必须给的是jsp的完整路径 request.getRequestDispatcher("/WEB-INF/jsp/itemList.jsp").forward(request, response); } 注意:如果使用原始的方式做页面跳转,那么必须给定jsp页面的完整路径。
- 也可以通过response实现页面重定向: response.sendRedirect("url")
- 也可以通过response指定响应结果,例如响应json数据如下: response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); response.getWriter().write("json串"); 例如,将以上itmeList2方法修改为: @RequestMapping("/itemList2") public void itmeList2(HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter writer = response.getWriter(); response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); writer.write("{"id":"123"}"); } 此时,在浏览器地址栏中输入url访问地址:http://localhost:8080/springmvc-web2/item/itemList2.action进行访问,我们可在浏览器看到如下效果:
返回字符串
逻辑视图名
Controller类方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
Redirect重定向
Contrller类方法返回结果重定向到一个url地址,如下商品信息修改提交后重定向到商品查询方法,参数无法直接带到商品查询方法中。
@RequestMapping(value="/updateitem",method={RequestMethod.POST,RequestMethod.GET}) public String updateItems(Items items) { itemService.updateItem(items); // /是不包含工程名的根目录,即http://localhost:8080/springmvc-web2/item/itemList.action return "redirect:/item/itemList.action"; }
return "redirect:/item/itemList.action?id=xxx&name=xxx";
-
但如果你使用的是Model接口,那么SpringMVC框架会自动将Model中的数据拼装到/item/itemList.action后面。
Controller类方法执行后继续执行另一个Controller类方法,如下商品修改提交后转向到商品修改页面,修改商品的id参数可以直接带到商品修改方法中。
@RequestMapping(value="/updateitem",method={RequestMethod.POST,RequestMethod.GET}) public String updateItems(Items items) throws UnsupportedEncodingException { itemService.updateItem(items); return "forward:/item/itemList.action"; }
--------------------- 本文来自 李阿昀 的 博客 ,全文地址请点击:https://blog..net/yerenyuan_pku/article/details/72511844?utm_source=copy