1.請求轉發和重定向的區別
請求重定向和請求轉發都是web開發中資源跳轉的方式。
請求轉發是服務器內部的跳轉
地址欄比發生變化
只有一個請求相應
可以通過request域對跳轉目標的請求
請求重定向是瀏覽器自動發起對跳轉目標的請求
地址欄會發生變化
兩次請求相應
無法通過request域傳遞對象
2.SpringMVC中實現轉發和重定向
(1)在SpringMVC中仍然可以使用傳統方式實現轉發和重定向
request.getRequestDispatcher(" ").forward(request,response);
response.sendRedirect(" ");
(2)在SpringMVC中也提供了快捷方式實現轉發和重定向
只要在返回視圖時,使用如下方式指定即可:
/** * 實現轉發 */ @RequestMapping("/hello11.action") public String hello11(HttpServletRequest request){ request.setAttribute("name", "cjj"); return "forward:hello.action"; } /** * 實現重定向 */ @RequestMapping("/hello12.action") public String hello12(HttpServletRequest request){ request.setAttribute("name", "cjj"); return "redirect:/hello.action"; }
(3)可以利用轉發,實現允許用戶訪問WEB-INF下保存的指定資源
/** * 通過轉發 實現 訪問到在WEB-INF目錄下的資源 * @throws Exception */ @RequestMapping("/toFile.action") public String toFile(String vname){ if("form".equals(vname)){ return vname; }else{ return "err"; } }