栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC controller方法返回值

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC controller方法返回值

ModelAndView概述

当控制器处理完请求时,通常会将包含视图名称或视图对象以及一些模型属性的ModelAndView对象返回到DispatcherServlet。
ModelAndView代表了MVC Web程序中Model与View的对象。

返回ModelAndView

controller方法中定义ModelAndView对象并返回,对象中可添加model数据、指定view。

返回字符串 逻辑视图名

controller方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。

@Controller
@RequestMapping("/account")
public class AccountController {
    @RequestMapping(value = "/findAccount2")
    public String findAccount2(Model model) {
        //添加数据
        model.addAttribute("msg", "欢迎你 springmvc");
        return "success";
    }
}
返回字符串
Redirect重定向
  • Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中。

  • redirect方式相当于“response.sendRedirect()”,转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。

  • 由于新发起一个request原来的参数在转发时就不能传递到下一个url,如果要传参数可以/item/queryItem后边加参数,如下:/item/queryItem?...&…..

@Controller
@RequestMapping("/account")
public class AccountController {
    
    @RequestMapping(value = "/findAccount3")
    public String findAccount3() {
        return "redirect:/account/findAccount4";
    }

    @RequestMapping(value = "/findAccount4")
    public String findAccount4(Model model) {
        //添加数据
        model.addAttribute("msg", "这是springmvc的重定向");
        return "success";
    }
}
a href="/account/findAccount3">重定向
forward转发
  • controller方法执行后继续执行另一个controller方法,如下商品修改提交后转向到商品修改页面,修改商品的id参数可以带到商品修改方法中。

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

@Controller
@RequestMapping("/account")
public class AccountController {
    
    @RequestMapping(value = "/findAccount3")
    public String findAccount3() {
        return "redirect:/account/findAccount4";
    }

    @RequestMapping(value = "/findAccount4")
    public String findAccount4(Model model) {
        //添加数据
        model.addAttribute("msg", "这是springmvc的重定向");
        return "success";
    }
}
重定向
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/333297.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号