Spring MVC学习之——Controller类中方法的返回值

Controller类中方法的返回值

1.返回ModelAndView

java 复制代码
 	@RequestMapping("/hello")
    public ModelAndView hello(){
        //封装了页面和数据
        ModelAndView view = new ModelAndView();
        //对这个请求的页面添加属性(数据)
        view.addObject("hello","Hello,欢迎成功进入!");
        //设置内容显示的页面
        view.setViewName("success");
        return view;
    }

2.返回字符串

2.1逻辑视图名

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

  • 返回字符串

java 复制代码
	@GetMapping("/hello")
    public String hello(Model model){
        model.addAttribute("hello","Hello,欢迎成功进入!");
        return "success";
    }

2.2Redirect重定向

说明:

  • Contrller方法返回结果重定向到一个url地址,如下商品修改提交后重定向到商品查询方法,参数无法带到商品查询方法中。
  • redirect方式相当于"response.sendRedirect()",转发后浏览器的地址栏变为转发后的地址,因为转发即执行了一个新的request和response。
  • 由于新发起一个request原来的参数在转发时就不能传递到下一个url,如果要传参数可以/item/queryItem后边加参数,如下:/item/queryItem?...&.....
java 复制代码
	@GetMapping("/account/findAccount")
    public String findAccount3(){
        return "redirect:/account/findAll";
    }
    @GetMapping("/account/findAll")
    public String findAll(Model model){
        model.addAttribute("hello","Hello,欢迎成功进入!");
        return "success";
    }

2.3Forward转发

说明:

  • controller方法执行后继续执行另一个controller方法,如下商品修改提交后转向到商品查询页面,修改商品的id参数可以带到商品查询方法中。
  • forward方式相当于request.getRequestDispatcher().forward(request,response),转发后浏览器地址栏还是原来的地址。转发并没有执行新的request和response,而是和转发前的请求共用一个request和response。所以转发前请求的参数在转发后仍然可以读取到。
java 复制代码
@Controller
@RequestMapping("/account")
public class AccountController {
    
    @RequestMapping(value = "/findAccount3")
    public String findAccount3() {
        return "forward:/account/findAccount4";
    }

    @RequestMapping(value = "/findAccount4")
    public String findAccount4(Model model) {
        //添加数据
        model.addAttribute("msg", "这是springmvc的重定向");
        return "success";
    }
}
相关推荐
ThsPool37 分钟前
【遥感学习整理 02】ENVI遥感图像处理基础:从数据读取到遥感信息产品
图像处理·人工智能·学习
0566462 小时前
Python康复训练——常用标准库
开发语言·python·学习
极光代码工作室2 小时前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen3 小时前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言
0566463 小时前
Python康复训练——控制流与函数
开发语言·python·学习
名字还没想好☜3 小时前
Go 的 time.After 在 select 循环里内存泄漏:定时器堆积原理与 timer.Reset 正确姿势
java·数据库·golang·go·goroutine
圆山猫3 小时前
[Virtualization](三):RISC-V H-extension 与 Guest 执行模式
android·java·risc-v
caishenzhibiao4 小时前
期货先行者主图 同花顺期货通指标
java·c语言·c#
史呆芬4 小时前
分布式事务实战:微服务跨服务数据一致性解决方案
java·后端·spring cloud
IT界的老黄牛4 小时前
限流命中后该怎么办:直接丢、阻塞等待、延迟重投三种姿势的取舍
java·rocketmq·redisson·令牌桶·削峰·分布式限流