Câu hỏi phỏng vấn Java
Câu hỏi

What’s the difference between sendRedirect and forward methods?

Câu trả lời

The sendRedirect() and forward() methods are used in Java Servlets to control the flow of an application, but they serve different purposes and operate in distinct ways.

sendRedirect() Method

The sendRedirect() method is used to redirect the client to a different resource, which could be a different page, a different site, or a different servlet. It is a method of the HttpServletResponse interface. When sendRedirect() is called, the server sends a temporary redirect response to the client, which causes the client's browser to issue a new request to the redirected location. This method is visible to the client as the browser's URL changes to the new URL.

  • Client-side redirect: The redirect process is visible to the client.
  • Two HTTP requests: It involves two browser requests — one to the original URL and one to the redirected URL.
  • URL change: The URL in the client's browser address bar changes to the target URL.
  • New request and response objects: Since it results in a new request, the original request and response objects are discarded.
  • Use cases: It is typically used when redirecting to a different domain or after completing a particular action (like form submission) to prevent form resubmission on page refresh[1][2][3][5][6][7][8][9][11][15][16][18].

forward() Method

The forward() method is used to forward a request from one servlet to another resource (servlet, JSP file, or HTML file) within the same application. It is a method of the RequestDispatcher interface, which can be obtained from the servlet request. Using forward(), the request is transferred to another resource for further processing, but the client is not aware of this operation — the URL in the browser does not change.

  • Server-side redirect: The forwarding process is handled internally by the server and is not visible to the client.
  • Single HTTP request: Only one request is involved, and the client is unaware of the forwarding.
  • URL remains the same: The URL in the client's browser remains unchanged.
  • Same request and response objects: The request and response objects are passed to the target resource.
  • Use cases: It is commonly used for tasks that do not require the client to see a different U...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What is the main difference between StringBuffer and StringBuilder ?

middle

What is Java Priority Queue?

middle

If an object reference is set to null , will the Garbage Collector immediately free the memory held by that object?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào