How do you redirect to another page in Java?

In Java, you can achieve page redirection using the sendRedirect() method of the HttpServletResponse object.

Here is a simple example demonstrating how to implement page redirection in Java.

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RedirectServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 重定向到另一个页面
        response.sendRedirect("https://www.example.com/newpage");
    }
}

In the above example, the response.sendRedirect(“https://www.example.com/newpage”) in the doGet() method will redirect the user to the page “https://www.example.com/newpage” in the browser.

Please make sure to place the response.sendRedirect() method at the appropriate location to call it when redirection is needed.

广告
Closing in 10 seconds
bannerAds