您的位置:首页 > 编程语言 > Java开发

springmvc注解开发-controller方法返回值

2018-02-02 17:01 351 查看
转自:http://blog.csdn.net/yerenyuan_pku/article/details/72511844

返回ModelAndView

Controller类方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。之前我就已讲过,在此并不过多赘述。

返回void

在Controller类方法形参上可以定义request和response,使用request或response指定响应结果:

使用request转向页面,如下:

request.getRequestDispatcher("页面路径").forward(request, response);
1
[/code]

之前我们实现商品列表的查询,返回的是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);
}
[/code]

注意:如果使用原始的方式做页面跳转,那么必须给定jsp页面的完整路径。

也可以通过response实现页面重定向:

response.sendRedirect("url")
[/code]

也可以通过response指定响应结果,例如响应json数据如下:

response.setCharacterEncoding("utf-8");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write("json串");
[/code]

例如,将以上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\"}");
}
[/code]

此时,在浏览器地址栏中输入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";
}
[/code]

redirect方式相当于“response.sendRedirect()”,转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。由于新发起一个request,原来的参数在转发时就不能传递到下一个url,如果要传参数可以在
/item/itemList.action
后边加参数,如下:

return "redirect:/item/itemList.action?id=xxx&name=xxx";
[/code]



但如果你使用的是Model接口,那么SpringMVC框架会自动将Model中的数据拼装到
/item/itemList.action
后面。

forward转发

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";
}
[/code]

forward方式相当于“request.getRequestDispatcher().forward(request,response)”,转发后浏览器地址栏还是原来的地址。转发并没有执行新的request和response,而是和转发前的请求共用一个request和response。所以转发前请求的参数在转发后仍然可以读取到。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: