SpringMVC 實現頁面跳轉

1.頁面跳轉的兩種方式
1.1請求轉發
  • request.getRequestDispatcher(path).forward(request, response);
  • 一次請求
  • 地址欄路徑不會發生變化
  • 可以使用請求作用域傳參
  • 只能訪問內部資源(當前項目下的資源)
  • 可以訪問安全目錄下的資源(WEB-INF)
  • 路徑中的/表示項目根路徑
響應重定向

response.sendRedirect(location);

  • 多次請求
  • 地址欄路徑會發生變化(最後一次請求的路徑)
  • 不能使用請求作用域傳參
  • 既可以訪問內部資源, 也可以訪問外部資源
  • 不能訪問安全目錄下的資源(WEB-INF)
  • 路徑中的/表示服務器根路徑
2.SpringMVC實現頁面跳轉
2.1請求轉發
  1. 通過HttpServletRequest實現
  2. 通過返回字符串實現
  3. 通過返回null或void返回實現(瞭解)
@Controller
@RequestMapping("/demo")
public class DemoController {
    @GetMapping("/demo4")
    public Object demo4() {
        System.out.println("DemoController.demo4");
        return null;
    }

    @GetMapping("/demo3")
    public void demo3() {
        System.out.println("DemoController.demo3");
    }

    @GetMapping("/demo2")
    public String demo2() {
        System.out.println("DemoController.demo2");
        // /表示項目根路徑
        return "forward:/demo/demo1";
    }

    @GetMapping("/demo1")
    public void demo1(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("DemoController.demo1");
        req.getRequestDispatcher("/WEB-INF/jsp/demo.jsp").forward(req, resp);
    }
}
2.2響應重定向
  1. 通過HttpServletResponse對象實現
  2. 通過返回字符串實現(redirect:)
  3. 通過返回View對象實現
@Controller
@RequestMapping("/demo")
public class DemoController {
    @GetMapping("/demo3")
    public View demo3(HttpServletRequest req) {
        // /表示服務器根路徑
        RedirectView view = new RedirectView(req.getContextPath() + "/demo.jsp");
        return view;
    }

    @GetMapping("/demo2")
    public String demo2() {
        System.out.println("DemoController.demo2");
        // /表示項目根路徑
        return "redirect:/demo.jsp";
    }

    @GetMapping("/demo1")
    public void demo1(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        System.out.println("DemoController.demo1");
        // /表示服務器根路徑
        resp.sendRedirect(req.getContextPath() + "/demo.jsp");
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章