RequestDispatcher.forward () 및 HttpServletResponse.sendRedirect ()
간의 개념 차이 무엇 forward()
과 sendRedirect()
?
requestDispatcher-forward () 메소드
forward
메소드 를 사용하면 요청이 추가 처리를 위해 동일한 서버 내의 다른 자원으로 전송됩니다.의 경우
forward
웹 컨테이너는 모든 처리를 내부적으로 처리하며 클라이언트 또는 브라우저는 관여하지 않습니다.객체
forward
에서이 호출 되면requestDispatcher
요청 및 응답 객체를 전달하므로 이전 요청 객체는 요청을 처리 할 새 리소스에 존재합니다.시각적으로 전달 된 주소를 볼 수 없으며 투명합니다.
forward()
방법을 사용하는 것이보다 빠릅니다sendRedirect
.forward를 사용하여 리디렉션하고 새로운 리소스에서 동일한 데이터를 사용하려는
request.setAttribute()
경우 요청 객체를 사용할 수 있으므로 사용할 수 있습니다.SendRedirect
의 경우
sendRedirect
, 요청은 추가 처리를 위해 다른 자원, 다른 도메인 또는 다른 서버로 전송됩니다.을 사용
sendRedirect
하면 컨테이너가 요청을 클라이언트 나 브라우저로 전송하므로sendRedirect
메소드 내부에 제공된 URL 이 클라이언트에 대한 새 요청으로 표시됩니다.
sendRedirect
호출의 경우 이전 요청 및 응답 오브젝트는 브라우저에서 새 요청으로 처리되므로 손실됩니다.주소 표시 줄에서 새로운 경로 재 지정된 주소를 볼 수 있습니다. 투명하지 않습니다.
sendRedirect
완전히 새로운 요청이 작성되고 이전 요청 오브젝트가 손실되므로 한 번의 추가 왕복이 필요하므로 속도가 느려집니다. 두 개의 브라우저 요청이 필요합니다.그러나에서
sendRedirect
사용하려면 데이터를 세션에 저장하거나 URL과 함께 전달해야합니다.어느 것이 좋은가요?
방법이 더 유용한 시나리오에 따라 다릅니다.
제어가 새로운 서버 또는 컨텍스트로 전송되고 완전히 새로운 작업으로 처리되기를 원하면로 이동하십시오
sendRedirect
. 일반적으로 웹 페이지를 브라우저를 다시로드 할 때 작업을 안전하게 반복 할 수 있고 결과에 영향을 미치지 않으면 앞으로를 사용해야합니다.
웹 개발 세계에서 "리디렉션"이라는 용어 Location
는 클라이언트가 새로운 GET 요청을 보내야하는 새 URL을 포함 하는 헤더로 클라이언트에게 빈 HTTP 응답을 보내는 행위입니다 . 그래서 기본적으로:
- 클라이언트가에 HTTP 요청을 보냅니다
some.jsp
. - 서버는
Location: other.jsp
헤더 와 함께 HTTP 응답을 다시 보냅니다. - 클라이언트가 HTTP 요청을 보냅니다
other.jsp
(브라우저 주소 표시 줄에 반영됨). - 서버는의 내용으로 HTTP 응답을 다시 보냅니다
other.jsp
.
웹 브라우저의 기본 제공 / addon 개발자 도구 세트를 사용하여이를 추적 할 수 있습니다. Chrome / IE9 / Firebug에서 F12를 누르고 "네트워크"섹션을 확인하십시오.
위의 내용은에 의해 달성됩니다 sendRedirect("other.jsp")
. 는 RequestDispatcher#forward()
리디렉션을 보내지 않습니다. 대신 대상 페이지의 내용을 HTTP 응답으로 사용합니다.
- 클라이언트가에 HTTP 요청을 보냅니다
some.jsp
. - 서버는의 내용으로 HTTP 응답을 다시 보냅니다
other.jsp
.
그러나 원래 HTTP 요청이 some.jsp
수행되었으므로 브라우저 주소 표시 줄의 URL은 변경되지 않습니다.
이는 RequestDispatcher
MVC 패러다임 및 / 또는 JSP를 직접 액세스에서 숨기려는 경우에 매우 유용합니다. JSP를 /WEB-INF
폴더 에 넣고 Servlet
요청을 제어, 사전 처리 및 사후 처리 하는 을 사용할 수 있습니다 . /WEB-INF
폴더 의 JSP는 URL로 직접 액세스 할 수 없지만을 Servlet
사용하여 액세스 할 수 있습니다 RequestDispatcher#forward()
.
당신은 예를 들어 JSP의에서 파일 수 /WEB-INF/login.jsp
와 LoginServlet
온 매핑 된 url-pattern
의를 /login
. 를 호출 http://example.com/context/login
하면 서블릿 doGet()
이 호출됩니다. 당신은 할 수있는 사전 거기 처리 물건과 마지막으로 앞으로 요청 등이 :
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
양식을 제출할 때 일반적으로 다음을 사용하려고합니다 POST
.
<form action="login" method="post">
이 방법으로 서블릿 doPost()
이 호출되고 거기에서 사후 처리 작업 (예 : 유효성 검사, 비즈니스 로직, 사용자 로그인 등)을 수행 할 수 있습니다.
오류가있는 경우 일반적으로 요청을 동일한 페이지로 다시 전달 하고 오류를 입력 필드 옆에 표시합니다. RequestDispatcher
이것을 위해 사용할 수 있습니다 .
A는 경우 POST
에 성공, 당신은 일반적으로 할 리디렉션 요청이 사용자가 새로 고침 요청 (예 : F5를 누르거나 역사를 다시 탐색) 때 다시 제출 수 없기 때문 요청을.
User user = userDAO.find(username, password);
if (user != null) {
request.getSession().setAttribute("user", user); // Login user.
response.sendRedirect("home"); // Redirects to http://example.com/context/home after succesful login.
} else {
request.setAttribute("error", "Unknown login, please try again."); // Set error.
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response); // Forward to same page so that you can display error.
}
따라서 리디렉션 은 클라이언트에게 GET
지정된 URL에서 새 요청 을 발생하도록 지시합니다 . 그러면 요청을 새로 고치면 리디렉션 된 요청 만 새로 고쳐지고 초기 요청은 새로 고쳐지지 않습니다. 이렇게하면 "이중 제출"과 혼동 및 나쁜 사용자 경험이 방지됩니다. 이것을 POST-Redirect-GET
패턴 이라고도합니다 .
The RequestDispatcher
interface allows you to do a server side forward/include whereas sendRedirect()
does a client side redirect. In a client side redirect, the server will send back an HTTP status code of 302
(temporary redirect) which causes the web browser to issue a brand new HTTP GET
request for the content at the redirected location. In contrast, when using the RequestDispatcher
interface, the include/forward to the new resource is handled entirely on the server side.
Either of these methods may be "better", i.e. more suitable, depending on what you want to do.
A server-side redirect is faster insofar as you get the data from a different page without making a round trip to the browser. But the URL seen in the browser is still the original address, so you're creating a little inconsistency there.
A client-side redirect is more versatile insofar as it can send you to a completely different server, or change the protocol (e.g. from HTTP to HTTPS), or both. And the browser is aware of the new URL. But it takes an extra back-and-forth between server and client.
SendRedirect()
will search the content between the servers. it is slow because it has to intimate the browser by sending the URL of the content. then browser will create a new request for the content within the same server or in another one.
RquestDispatcher
is for searching the content within the server i think. its the server side process and it is faster compare to the SendRedirect()
method. but the thing is that it will not intimate the browser in which server it is searching the required date or content, neither it will not ask the browser to change the URL in URL tab. so it causes little inconvenience to the user.
The main important difference between the forward() and sendRedirect() method is that in case of forward(), redirect happens at server end and not visible to client, but in case of sendRedirect(), redirection happens at client end and it's visible to client.
Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.
For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.
For other scenarios, forward is efficient to use since as it is faster than sendRedirect
Request Dispatcher is an Interface which is used to dispatch the request or response from web resource to the another web resource. It contains mainly two methods.
request.forward(req,res)
: This method is used forward the request from one web resource to another resource. i.e from one servlet to another servlet or from one web application to another web appliacation.response.include(req,res)
: This method is used include the response of one servlet to another servlet
NOTE: BY using Request Dispatcher we can forward or include the request or responses with in the same server.
request.sendRedirect()
: BY using this we can forward or include the request or responses across the different servers. In this the client gets a intimation while redirecting the page but in the above process the client will not get intimation
Dispatcher allow request data to travel from one servlet to other servlet. Alternative of request dispatcher is send redirect but for every new request send redirect come back to network on contrary request dispatcher occur within server.
Example
Servlet Dispatcher In Java Let's understand concept of request dispatcher with simple example. Consider situation where we have three servlet named as servlet1,servlet2 and Servlet3. In case if we don’t use dispatcher, whenever we request for servlet1, server pass control to servlet1, after that if we request for servlet2 then control come backs from servlet 1 to server and passed to servlet2. In this case if server is located in India and servlet is requested from America then for second request it must come back to server(India) and go back to servlet(America). This option is not good if we have heavy traffic in between request and response. Solution of this problem is dispatcher.
Servlet Dispatcher In Java In same case if we use dispatcher within server then control is passed from servlet1 to servlet2 without coming back to server and without involving network. This concept is also known as servlet chaining. It is known as servlet chaining because we are creating chain of servlet request, from servlet1 to servlet2, Servlet2 to Servlet3 and server will get data from servlet3.
Data passing
In servlet chaining not only control is passed but data also travel from one servlet to other servlet which is major advantage compare to send redirect. In send redirect every request is new request, every time you get new data.
Consider that servlet1 have some request parameter which should be executed by servlet3 then data can travel from servlet1 to servlet2 and after that from servlet2 to servlet3, so here we are preserving request from one servlet to other servlet.
Life of request is very small, as soon as we get response, request is over but here life of request can be preserved from one servlet to other. With help of this we can divide task in many servlet.
Disadvantage
Most of the time dispatcher is efficient but in case of large data or if we don’t need data at all or in case of low trafficking send redirect work efficiently.
Simply difference between Forward(ServletRequest request, ServletResponse response)
and sendRedirect(String url)
is
forward():
- The
forward()
method is executed in the server side. - The request is transfer to other resource within same server.
- It does not depend on the client’s request protocol since the
forward ()
method is provided by the servlet container. - The request is shared by the target resource.
- Only one call is consumed in this method.
- It can be used within server.
- We cannot see forwarded message, it is transparent.
- The
forward()
method is faster thansendRedirect()
method. - It is declared in
RequestDispatcher
interface.
sendRedirect():
- The sendRedirect() method is executed in the client side.
- The request is transfer to other resource to different server.
- The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients.
- New request is created for the destination resource.
- Two request and response calls are consumed.
- It can be used within and outside the server.
- We can see redirected address, it is not transparent.
- The sendRedirect() method is slower because when new request is created old request object is lost.
- It is declared in HttpServletResponse.
'Programing' 카테고리의 다른 글
ConnectionTimeout과 SocketTimeout (0) | 2020.07.18 |
---|---|
NuoDB를 사용하여 Ruby On Rails에서 SQL 명령을 수동으로 실행하는 방법 (0) | 2020.07.18 |
WebDriver : 요소가 존재하는지 확인 하시겠습니까? (0) | 2020.07.18 |
GROUP_CONCAT ORDER BY (0) | 2020.07.18 |
PHP로 디렉토리를 재귀 적으로 압축하는 방법? (0) | 2020.07.18 |