To navigate to another page in a Java bean, you can use the sendRedirect()
method of the HttpServletResponse
class. The sendRedirect()
method sends a temporary redirect response to the client using the specified redirect location URL.
Here is an example of how to use the sendRedirect()
method in a Java bean:
import javax.servlet.http.HttpServletResponse; public class MyBean { public void goToPage(HttpServletResponse response) throws IOException { response.sendRedirect("http://www.example.com/"); } }
In this example, the goToPage()
method redirects the client to the URL "http://www.example.com/".
To use the MyBean
bean in a servlet, you can inject it into the servlet using the @Inject
annotation and call the goToPage()
method from the servlet's doGet()
or doPost()
method:
import javax.inject.Inject; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { @Inject MyBean bean; protected void doGet(HttpServletRequest request, HttpServletResponse response) { bean.goToPage(response); } }
When the servlet's doGet()
method is called, the goToPage()
method of the MyBean
bean is called and the client is redirected to the specified URL.
Note that the sendRedirect()
method sends a temporary redirect response to the client, which means that the client's browser will send a new request to the specified URL. If you want to forward the request to another page within the server, you can use the RequestDispatcher.forward()
method instead.