zoukankan      html  css  js  c++  java
  • springMVC RedirectAttributes

    @Controller
    public class TestController {
    
        @RequestMapping("/redirectDemo")
        public String redirectDemo(RedirectAttributes attributes){
          attributes.addFlashAttribute("message","error.user.login");
          return "redirect:/index";
        }
        @RequestMapping("/index")
        public String index(){
            return "index";
        }
    
    }

     index.ftl

     ${message}

    @RequestMapping("/redirect")
        public String redirectTest(RedirectAttributes attr){
            attr.addAttribute("userName", "root");
            attr.addFlashAttribute("password","123456");
            return "redirect:/book/getbook";
        }
    @RequestMapping("/getbook")
        @ResponseBody
        public String getBook(ModelMap map,HttpServletRequest request,@RequestParam("userName") String userName,
                @RequestParam(value = "password",required = false) String password){
            System.out.println("userName : "+map.get("userName"));
            System.out.println("userName1 :" + request.getAttribute("userName"));
            System.out.println("userName2 :" + request.getParameter("userName"));
            System.out.println("userName3 : " + userName);
            
            
            System.out.println("password : "+map.get("password"));
            System.out.println("password1 :" + request.getAttribute("password"));
            System.out.println("password2 :" + request.getParameter("password"));
            System.out.println("password3 : " + password);
            
            return "result";
        }

    请求结果
     
    url : http://localhost:9019/book/getbook?userName=root
     
    控制台输出
    userName : null
    userName1 :null
    userName2 :root
    userName3 : root
    password : 123456
    password1 :null
    password2 :null
    password3 : null
    总结:
     
    请求转发需要携带参数时
    1、使用  RedirectAttributes 的 addAttribute()方法设置参数,则参数将直接拼接在转发url后面,然后可以在通过request.getParameter("userName")) 和 直接通过spring mvc配置参数映射接收到参数
    2、使用 RedirectAttributes  的 addFlashAttribute()方法设置参数,则参数不会出现在转发url中,然后可以通过modelMap 取出参数
     
     
    补充:
    请求结果页面代码
    result welcome in $!{title}; ${userName}; ${password} 
     
  • 相关阅读:
    leetcode(js)算法605之种花问题
    如何使绝对定位内部元素不继承父级宽度,而是靠内容自动撑开宽度(转载)
    SQL连接查询、变量、运算符、分支、循环语句
    SQL主外键和子查询
    数据库函数
    数据库的备份恢复和部分操作语句
    SQL部分 数据库的建立 增删改查
    【转】毛玻璃特效
    Font Awesome符号字体
    form表单验证和事件
  • 原文地址:https://www.cnblogs.com/newlangwen/p/9024050.html
Copyright © 2011-2022 走看看