欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SpringMVC 重定向参数RedirectAttributes实例

程序员文章站 2022-06-15 13:32:42
目录重定向参数redirectattributes1. addattribute2. addflashattribute重定向携带参数问题问题描述问题来源重定向参数redirectattributes...

重定向参数redirectattributes

springmvc 中常用到 redirect 来实现重定向。但使用场景各有需求,如果只是简单的页面跳转显然无法满足所有要求,比如重定向时需要在 url 中拼接参数,或者返回的页面需要传递 model。

springmvc 用 redirectattributes 解决了这两个需要。

1. addattribute

@requestmapping("/save")
public string save(user user, redirectattributes redirectattributes) {
    redirectattributes.addattribute("param", "value1");
    return "redirect:/index";
}

请求 /save 后,跳转至/index,并且会在url拼接 ?param=value1。

2. addflashattribute

@requestmapping("/save")
public string save(user user, redirectattributes redirectattributes) {
    redirectattributes.addflashattribute("param", "value1");
    return "redirect:/index";
}

请求 /save 后,跳转至 /index,并且可以在 index 对应的模版中通过表达式,比如 jsp 中 jstl 用 ${param},获取返回值。该值其实是保存在 session 中的,并且会在下次重定向请求时删除。

redirectattributes 中两个方法的简单介绍就是这样。

重定向携带参数问题

问题描述

a.jsp发送请求进入controller,并想重定向到b.jsp并携带参数,发现携带的参数前台获取不到,然后采用以下方法即可

   @requestmapping("/index")
    public string delete(string id, redirectattributes redirectattributes) {
           redirectattributes.addflashattribute("msg","删除成功!");
           return "redirect:hello";
    }
    @requestmapping("hello")
    public string index( @modelattribute("msg") string msg) {
         
          return "sentinel";
    }

首先进入delete方法,将msg放在redirectattributes里,然后重定向到hello,通过@modelattribute(“msg”) string msg获取到msg的值,那么自然sentinel页面就能获取到msg的值。

问题来源

b.jsp发送请求,跳转到a.jsp,并将请求所产生的数据携带到a页面。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。