Java servlet several page jump methods

 

Servlet:

Of course, in servlet, the general jump occurs in doGet, doPost and other methods.

1) redirect method

response.sendRedirect("/a.jsp");

The path to the page is a relative path. sendRedirect can jump the page to any page, not necessarily limited to this web application, such as:

response.sendRedirect("http://www.jb51.net");

The browser address bar changes after the jump.

If you want to pass the value out in this way, you can only use the parameter in the url or put it in the session, and you cannot use request.setAttribute to pass it.

2) forward method

RequestDispatcher dispatcher = request.getRequestDispatcher("/a.jsp");

dispatcher .forward(request, response);

The path to the page is a relative path. The forward method can only jump to the page in this web application.

The browser address bar will not change after the jump.

Using this method to jump, you can use three methods to pass the value: parameter, session, request.setAttribute in the url

JSP:

1) response.sendRedirect();

Same as servlet's response.sendRedirect() method.

Out.flush() is not allowed before this statement, if there is, there will be an exception:

java.lang.IllegalStateException: Can't sendRedirect() after data has committed to the client.

at com.caucho.server.connection.AbstractHttpResponse.sendRedirect(AbstractHttpResponse.java:558)

...

Browser address bar changes after jumping

If you want to jump to a different host, after the jump, the statement after this statement will continue to be executed, as if a new thread was opened, but the operation of the response is meaningless;

If you want to jump to the same host, you will not jump until the statement following this statement is executed;

2) response.setHeader("Location","");

Out.flush() is not allowed before this statement, if there is, the page will not jump.

Browser address bar changes after jumping

The statement after this statement will not jump until the execution of the statement is completed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325450889&siteId=291194637