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";
    }
}
相关推荐
NE_STOP7 小时前
MyBatis-配置文件解读及MyBatis为何不用编写Mapper接口的实现类
java
后端AI实验室12 小时前
用AI写代码,我差点把漏洞发上线:血泪总结的10个教训
java·ai
程序员清风13 小时前
小红书二面:Spring Boot的单例模式是如何实现的?
java·后端·面试
belhomme14 小时前
(面试题)Redis实现 IP 维度滑动窗口限流实践
java·面试
Be_Better14 小时前
学会与虚拟机对话---ASM
java
开源之眼16 小时前
《github star 加星 Taimili.com 艾米莉 》为什么Java里面,Service 层不直接返回 Result 对象?
java·后端·github
Maori31617 小时前
放弃 SDKMAN!在 Garuda Linux + Fish 环境下的优雅 Java 管理指南
java
用户9083246027317 小时前
Spring AI 1.1.2 + Neo4j:用知识图谱增强 RAG 检索(上篇:图谱构建)
java·spring boot
小王和八蛋17 小时前
DecimalFormat 与 BigDecimal
java·后端