1. 程式人生 > >Request物件實現請求轉發

Request物件實現請求轉發

      在實現之前我們首先應該瞭解請求轉發請求重定向的概念和區別:https://www.cnblogs.com/haimishasha/p/5952129.html

       在Servlet中,我們是通過ReqDispatcher物件來實現請求轉發,Servlet把請求轉發給Servlet、HTML、JSP或其它資訊資源,由第2個資訊資源響應該請求,兩個資訊資源共享同一個request物件。

      有兩種方式可以獲取這個物件:

       

         //1.通過ServletContent.getReqDisPathcer()獲取ReqDisPathcer物件,再呼叫該物件的forward()實現請求轉發
        RequestDispatcher requestDispatcher= this.getServletContext().getRequestDispatcher("/test.jsp");
        requestDispatcher.forward(request,response);
        //2.通過Request.getDisPatcher()獲取ReqDisPatcher物件,再呼叫該物件的forward()實現請求轉發
RequestDispatcher requestDispatcher=request.getRequestDispatcher("/test.jsp").forward(request,response);

 下面我們可以來看一個Demo:

  在TestReqDispatcher Servlet中將請求轉發至test.jsp

  

package com.java.controller;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class TestReqDispatcher extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String data="今天天氣很好"; request.setAttribute("data",data); //1.通過ServletContent.getReqDisPathcer()獲取ReqDisPathcer物件,再呼叫該物件的forward()實現請求轉發 RequestDispatcher requestDispatcher= this.getServletContext().getRequestDispatcher("/test.jsp"); requestDispatcher.forward(request,response); //2.通過Request.getDisPatcher()獲取ReqDisPatcher物件,再呼叫該物件的forward()實現請求轉發 //RequestDispatcher requestDispatcher=request.getRequestDispatcher("/test.jsp").forward(request,response); } public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }

 test.jsp

  

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>大家好</title>
</head>
<body>
普通方式取出data:
<h2><%= request.getAttribute("data")%></h2>
EL表示式取出data:
<h2>${data}</h2>

</body>
</html>

  好了,我們看一下在瀏覽器輸出的結果: