JAVA 框架 springmvc controller的返回值

一、返回值:ModleView对象。

使用modelAndView.setViewName设置返回的页面。使用modelAndView.addObject设置返回的数据。

1     @RequestMapping("/edit")
2     public ModelAndView editTable(HttpServletRequest request){
3         ModelAndView modelAndView=new ModelAndView();
4         String id=request.getParameter("id");
5         goods goodser= this.goodsService.findByIdSer(Integer.parseInt(id));
6         modelAndView.setViewName("edit");
7         modelAndView.addObject("goods",goodser);
8         return modelAndView;
9     }

 二、返回值:字符串

字符串为页面名称除去扩展名

1     @RequestMapping("/edit")
2     public String editTable(HttpServletRequest request,Model model){
3         String id=request.getParameter("id");
4         goods goodser= this.goodsService.findByIdSer(Integer.parseInt(id));
5         model.addAttribute("goods",goodser);
6         return "edit";
7     }

三、返回值:void

通过参数httpservletrequest来确定设置返回值,通过request 设置值和转发。

1     @RequestMapping("/edit")
2     public void editTable(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
3         String id=request.getParameter("id");
4         goods goodser= this.goodsService.findByIdSer(Integer.parseInt(id));
5         request.setAttribute("gooods",goodser);
6         request.getRequestDispatcher("WEB-INF/jsp/success.jsp").forward(request,response);
7     }

 四:转发

通过return  forward:*.action 方式进行转发,通过Model设置数据。绝对路径是带有/

1     @RequestMapping("/update")
2     public String upddateById(goods goods,Model model){
3         this.goodsService.updateById(goods);
4         model.addAttribute("id",goods.getId());
5     return  "forward:edit.action";
6     }

绝对路径写法:根据需求来适用绝对路径和相对路径。

1    @RequestMapping("/update")
2     public String upddateById(goods goods,Model model){
3         this.goodsService.updateById(goods);
4         model.addAttribute("id",goods.getId());
5     return  "redirect:/goods/edit.action";
6     }

注意这里需要带上扩展名.action

url没发生变化。

五、重定向:

通过return "redirect:*.action"  通过Model设置数据。绝对路径是带有/。

1     @RequestMapping("/update")
2     public String upddateById(goods goods,Model model){
3         this.goodsService.updateById(goods);
4         model.addAttribute("id",goods.getId());
5     return  "redirect:edit.action";
6     }

 url发生变化。

Modle 底层也是通过request.setAttribute来设置属性,但是对request上做了更好的封装,无论是转发还是重定向都可以设置值。

猜你喜欢

转载自www.cnblogs.com/evilliu/p/8980423.html