《Spring實戰》讀書筆記--SpringMVC之forward與redirect 1.forward與redirect介紹 1.1 redirect 重定向,服務器收到請求后發送一個狀態碼給客戶端,讓客戶端再重新請求,并且第一次請求中Request里的數據消失。所以redirect相當于客戶端向服務器發出兩次請求,第一次請求的數據不會轉發給第二次請求,URL地址會變化兩次。
1.2 forward 轉發(前往),服務器內部的重定向,在Servlet中通過RequestDispatcher轉發給另一個程序處理請求,請求的數據依然在。所以forward相當于客戶端向服務器發送一次請求,服務器處理兩次,請求數據不會消失且URL地址只變化一次。
2.Servlet與SpringMVC中的forward與redirect 2.1 Servlet中的forward與redirect Servlet中的HttpServletResponse類中有sendRedirect(String location)方法直接重定向到URL為location的地址。 應用:
1 @WebServlet(name="deleteOneServlet",urlPatterns="/deleteOne.action"
)
2 public class DeleteOneServlet
extends HttpServlet{
3 private static final long serialVersionUID = 1L
;
4 private ContentService contentService =
new ContentService();
5 @Override
6 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
7 // 從頁面中獲取數據
8 String id = req.getParameter("id"
);
9 // 調用Servive執行業務邏輯
10 contentService.deleteOne(id);
11 // 重定向
12 resp.sendRedirect("/list.action"
);
13 }
14 }
Servlet可以通過HttpServletRequest類的getRequestDispatcher(String path)獲得RequestDispatcher對象,該通過該對象的forward(ServletRequest request, ServletResponse response)方法轉發請求與相應給任何資源(如Servlet、HTML file、JSP file)。 RequestDispatcher類的API
1 package javax.servlet;
2 public interface RequestDispatcher{
3 public void forward(ServletRequest request, ServletResponse response)
throws ServletException, IOException;
4 public void include(ServletRequest request, ServletResponse response)
throws ServletException, IOException;
5 }
6 API上的介紹:
7 Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server.
8 The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name.
9
10 This
interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource.
應用:
1 @WebServlet(name="query",urlPatterns="/query.action"
)
2 public class QueryServlet
extends HttpServlet{
3 private static final long serialVersionUID = 1L
;
4 private ContentService contentService =
new ContentService();
5 @Override
6 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
7 // 從頁面獲取參數
8 String command = req.getParameter("command"
);
9 String description = req.getParameter("description"
);
10 // 調用Service處理業務邏輯
11 List<Message> messages =
contentService.query(command, description);
12 // 向頁面傳遞值
13 req.setAttribute("messages"
, messages);
14 req.setAttribute("command"
, command);
15 req.setAttribute("description"
, description);
16 // 轉發到視圖中
17 req.getRequestDispatcher("/WEB-INF/jsp/back/list.jsp"
).forward(req, resp);
18 }
19 }
?
2.2 SpringMVC中的Servlet SpringMVC是基于Servlet的Web MVC框架,所以forward與redirect的處理結果一樣,方式更為簡單。SpringMVC中的InternalResourceViewResolver視圖解析器會識別redirect與forward關鍵字,然后處理。 應用:
1 @Controller
2 @RequestMapping(value="/springMVC"
)
3 public class UserController {
4 @RequestMapping(value="/login"
)
5 public String login() {
6 return "login"
;
7 }
8
9 @RequestMapping(value="/upload", method=
RequestMethod.POST)
10 public String fileUpload(@RequestPart(value="file") MultipartFile multipartFile)
throws Exception{
11 String path = "E:/java/fileupload/" +
multipartFile.getOriginalFilename();
12 multipartFile.transferTo(
new File(path));
13 // 重定向
14 return "redirect:/springMVC/index"
;
15 // 轉發
16 return "foward:/springMVC/index"
;
17 }
18 }
3. SpringMVC重定向傳遞數據 從上面我們可以看出redirect不能傳遞數據,但我們可以使用其它方案傳遞數據。主要有:
通過URL模板以路徑變量或查詢參數形式傳遞數據 通過flash屬性傳遞數據 3.1 通過URL模板進行重定向 方式如下:
1 @Controller
2 @RequestMapping(value="/springMVC"
)
3 public class UserController {
4 @RequestMapping(value="/index/{name}",method=
RequestMethod.GET)
5 public String index(@PathVariable(value="name"
) String name,
6 @RequestParam(value="id")
int id) {
7 System.out.println(name +
id);
8 return "login"
;
9 }
10
11 @RequestMapping(value="/data/{id}",method=
RequestMethod.GET)
12 public String data(@PathVariable(value="id")
int id, Model model) {
13 model.addAttribute("id"
, id);
14 model.addAttribute("name", "Tom"
);
15 return "redirect:/springMVC/index/{name}"
;
16 }
17 }
使用模板方式時,若使用了占位符則變為路徑參數,否則變為請求變量。所以以上重定向URL路徑變為"/springMVC/index/Tom?id=5"。 該方法簡單有效,但傳遞數據值簡單,若數據復雜則可使用下面的方式傳遞數據
3.2 使用flash屬性 Spring提供了RedirectAttributes設置flash屬性的方法重定向傳遞參數。 原理:在重定向執行之前,所有的flash屬性會復制到session中。在重定向后,放在Session中的flash屬性會被取出,放到Model中。注:RedirectAttributes類繼承自Model類。 方式如下:
1 @Controller
2 @RequestMapping(value="/springMVC"
)
3 public class UserController {
4 @RequestMapping(value="/index",method=
RequestMethod.GET)
5 public String index(User user) {
6 System.out.println(user);
7 return "login"
;
8 }
9
10 @RequestMapping(value="/data/{id}",method=
RequestMethod.GET)
11 public String data(@PathVariable(value="id")
int id, RedirectAttributes model) {
12 User user =
new User(id,"Tom"
);
13 model.addFlashAttribute("user"
, user);
14 return "redirect:/springMVC/index"
;
15 }
16 }
4.References http://blog.csdn.net/tenor/article/details/4077079
轉載于:https://www.cnblogs.com/maying3010/p/6682582.html
總結
以上是生活随笔 為你收集整理的《Spring实战》读书笔记--SpringMVC之forward与redirect 的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網站內容還不錯,歡迎將生活随笔 推薦給好友。