Java中重定向传参与取值问题

重定向:不仅可以重定向到当前应用程序中的其他资源,还可以重定向到同一个站点上的其他应用程序中的资源,甚至是使用绝对URL重定向到其他站点的资源

  • 1、重定向基本语法
@PostMapping(value = "/test")
public String index() {
    return "redirect:index";
}

当我们请求 test 时,重定向到 index 请求中,当然,也可以直接重定向到页面 redirect:index.html

  • 2、重定向传参
@PostMapping(value = "/test")
public String index(RedirectAttributes attributes) {
    attributes.addFlashAttribute("msg", "提示信息");
    return PasswordUtils.redirectTo("/index");
}

我们在重定向时,借助了 RedirectAttributes 对象传入了 msg 参数

注意:
addAttribute,会将参数放入路径传递,例如:127.0.0.1:8080/index?msg=提示信息
addFlashAttribute,不会把参数放入路径传递,例如:127.0.0.1:8080/index

  • 3、重定向接收参数
@RequestMapping(value = "/index")
public ModelAndView index(@ModelAttribute("msg") String msg) {
    ModelAndView mav = new ModelAndView("index");
    // 页面提示语
    mav.addObject("msg", msg);
    return mav;
}

我们使用 @ModelAttribute 接收了参数 msg,将参数赋值给 ModelAndView 对象,传给客户端

Java 中重定向传参与取值问题就讲到这儿 END

如您在阅读中发现不足,欢迎留言!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章