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} 
     
  • 相关阅读:
    结对项目之感
    调查问卷之体会
    我的软件工程课程目标
    关于软件工程的课程建议
    结对编程--fault,error,failure
    结对编程总结
    结对编码感想
    我的软件工程课目标
    《软件工程》课之-调查问卷的心得体会
    软件工程课程讨论记录
  • 原文地址:https://www.cnblogs.com/newlangwen/p/9024050.html
Copyright © 2011-2022 走看看