Spring RedirectAttributes: addAttribute() vs addFlashAttribute()

前端 未结 3 1541
故里飘歌
故里飘歌 2020-11-28 03:00

My understanding so far is on our controller request mapping method we can specify RedirectAttributes parameter and populate it with attributes for when the request

3条回答
  •  攒了一身酷
    2020-11-28 03:37

    Assume you have 2 controllers.If you redirect from one controller to another controller the values in model object won't be available in the other controller. So if you want to share the model object values then you have to say in first controller

    addFlashAttribute("modelkey", "modelvalue");
    

    Then second controller's model contains now the above key value pair..

    Second question ? What is difference between addAttribute and addFlashAttribute in RedirectAttributes class

    addAttribute will pass the values as requestparameters instead of model,so when you add some using addAttribute you can access those values from request.getParameter

    Here is the code.I have used to find out what is going on :

    @RequestMapping(value = "/rm1", method = RequestMethod.POST)
    public String rm1(Model model,RedirectAttributes rm) {
        System.out.println("Entered rm1 method ");
    
        rm.addFlashAttribute("modelkey", "modelvalue");
        rm.addAttribute("nonflash", "nonflashvalue");
        model.addAttribute("modelkey", "modelvalue");
    
        return "redirect:/rm2.htm";
    }
    
    
    @RequestMapping(value = "/rm2", method = RequestMethod.GET)
    public String rm2(Model model,HttpServletRequest request) {
        System.out.println("Entered rm2 method ");
    
        Map md = model.asMap();
        for (Object modelKey : md.keySet()) {
            Object modelValue = md.get(modelKey);
            System.out.println(modelKey + " -- " + modelValue);
        }
    
        System.out.println("=== Request data ===");
    
        java.util.Enumeration reqEnum = request.getParameterNames();
        while (reqEnum.hasMoreElements()) {
            String s = reqEnum.nextElement();
            System.out.println(s);
            System.out.println("==" + request.getParameter(s));
        }
    
        return "controller2output";
    }
    

提交回复
热议问题