SpringMvc redirect

SpringMVC redirect

核心

首先网上百度到的资源基本已经够用, 留作记录.

SpringMVC—redirect重定向跳转传值

虽然这哥们也是转的, 但又没有留源地址. 因此 ...

个人补充

同时如果懒得去原链接看, 我在这里也写出来, 同时文档略做更改.

同样仅仅考虑 SpringMVC 中的跳转问题:

  1. 这种是最为常见的情况:

    @RequestMapping("/t1.html")
    public String who2(String password, Model model) {

    return "test.jsp";
    }

    在这种拼接中, 会拼接上:




    对应的 suffix, 至于ModelAndView那种方式也不再多说.

  2. 采用redirect的方式

    @RequestMapping("/t1.html")
    public String who2(String password, Model model) {

    return "redirect:/index.jsp";
    }

    至于返回的路径加/, 这里就是指项目根目录, 而更有趣的作用应该是重定向至另一个 Controller, 因为在这里重定向的时候, 默认以当前 class 的 RequestMapping 为前缀,进行拼接. 但不会拼接对应的后缀.

    @RequestMapping("/test")
    @Controller
    public class TestController {

    @RequestMapping("/t1.html")
    public String who2(String password, Model model) {

    return "redirect: t2";
    }
    }

    404响应, HTTP Status 404 - /test/t2, 所以更适合用在 Controller上, 但存在同样的问题, 会将参数拼接在 Url上.

    所以如果不在意参数显示在前台的情况下, 这种方式已经能满足要求了. 如果需要访问的并非本类的 路径, 还可以自行拼接路径.

  3. RedirectAttributes

    在这种方式中, 返回值必须为 redirect 才会有起到存储数据的作用.

    @RequestMapping("/t1.html")
    public String who2(String password, RedirectAttributes model) {
    model.addAttribute("password", password);
    return "redirect: /index.jsp";
    }

    但和上述方式, 直接采用 Model 所带来的问题是相同的

    有以下测试:

    @RequestMapping("/t1.html")
    public String who2(String password, RedirectAttributes model) {
    model.addFlashAttribute("password", password);
    return "redirect: t3";
    }

    @RequestMapping("t3")
    public String who4(ModelMap map, HttpServletRequest request, String password, String username) {
    System.out.println(map.get("password"));
    System.out.println(request.getParameter("password"));
    System.out.println(request.getAttribute("password"));
    System.out.println(request.getSession().getAttribute("password"));
    System.out.println("password:" + password);
    Map map1 = RequestContextUtils.getInputFlashMap(request);
    System.out.println(map1.get("password"));
    return "myname";
    }

    输出结果:

    123
    null
    null
    null
    password:null
    123

    也就不难发现, 这种addFlashAttribute的方式其实仅仅只支持重定向至另一个 method, 而非页面, 因为在页面无法取出对应的参数.

    所以网上的几种方法, EL表达式, Request, Session, 这些方式都是取不出来对应的值得, 特别地, 在看源码之前, 对原理我也不敢多说什么,只知道是这样用的.

    另外一种获取数据的方法是:

    @ModelAttribute("password") String pwd

    //其他几种
    Map map1 = RequestContextUtils.getInputFlashMap(request);

    ModelMap map

    以及在本次被重定向之后, 转发的界面,用EL表达式可以取到.

    以及一种比较特殊的写法(addFlashAttribute, addAttribute 的返回值均为RedirectAttributes):

    model.addAttribute("username", "zzzzz").addFlashAttribute("password", password);

    可以通过多种方式设定想要的参数, 但需要注意的是, 一旦使用了 addAttribute, 参数就会被拼接在url上.

  4. RedirectView

    也是一种用法, 在 RedirectAttributes 用到的场合中, 除了采用 redirect: 的方式, 也可以采用 RedirectView的方式.

    这点类似于,常规使用中的, ModelAndView 和 return new String;

posted @ 2018-04-08 23:28  千江月09  阅读(437)  评论(0)    收藏  举报