RedirectAttributes 使用规则

阅读更多
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by kenny.dong on 2018/6/4.
 */
@RestApiController
@RequestMapping("/test")
public class RedictTest {


    @RequestMapping(value = "/testA", method = RequestMethod.GET)
    public String testA(HttpServletRequest request,
                                 HttpServletResponse response, RedirectAttributes attr){
        attr.addAttribute("test1","a");
        attr.addFlashAttribute("test2","b");
        attr.addFlashAttribute("test3","c");
        return "redirect:/test/testB";
        //浏览器的参数会有test1=a,但不会有test2=b&test3=c
    }


    @RequestMapping(value = "/testB", method = RequestMethod.GET)
    public String testB(@ModelAttribute(value = "test2")String  b, @RequestParam(value = "test1")String  a, HttpServletRequest request,
                        HttpServletResponse response, RedirectAttributes attr){
        System.out.println("test2" + b);//@ModelAttribute 可以获取addFlashAttribute放入的数据
        System.out.println("test1" + a);//@RequestParam 可以获取addAttribute 放入的数据
        Map map = (Map) request.getAttribute(DispatcherServlet.INPUT_FLASH_MAP_ATTRIBUTE);//可以获取所有的addFlashAttribute放入的数据
        attr.addAllAttributes(map);
        attr.addAttribute("test1","d");//重新覆盖其他URL跳转过来的test参数
        attr.addAttribute("test4","e");
        return "redirect:http://www.baidu.com";
    }
}

 

你可能感兴趣的:(RedirectAttributes 使用规则)