• 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} 
     
  • 相关阅读:
    ubuntu下wget的配置文件在哪里
    ubuntu下apt-get的配置文件是哪个
    Jar包方式运行web项目
    深入浅说服务如何以Jar包的方式发布
    maven 私服的setting.xml配置
    maven 配置私服 连接
    一、Spring MVC起步——IntelliJ IDEA 搭建Spring MVC环境(手把手搭建)
    intellij IDEA配置tomcat
    maven工程项目与项目之间的依赖方式
    手动创建Maven项目并建立两个项目之间的依赖关系
  • 原文地址:https://www.cnblogs.com/newlangwen/p/9024050.html
Copyright © 2020-2023  润新知