The following methods can be used to redirect pages in JSP and Servlet:
Assume that you want to jump from test1.jsp to test2.jsp.
1. Jump in JSP:
1. Use the requestdispatcher. Forward Method for forwarding
<%
Requestdispatcher RD = getservletcontext (). getrequestdispatcher ("/test/test2.jsp ");
Rd. Forward (request, response );
%>
2. response. sendredirect redirection
<%
Response. sendredirect ("test2.jsp ");
%>
3. Use the forward label
<JSP: Forward page = "test2.jsp"/>
4. meta tag in HTML Tag
<Meta http-equiv = "refresh" content = "0; url = test2.jsp">
5. Use response. setheader
<%
Int staytime = 0;
String url = "test2.jsp ";
String content = staytime + "; url =" + URL;
Response. setheader ("refresh", content );
%>
6. Use response. setHeader and response. setStatus to send redirect requests
<%
Response. setStatus (HttpServletResponse. SC _MOVED_PERMANENTLY );
String newLocation = "test2.jsp ";
Response. setHeader ("Location", newLocation );
%>
7. Use javascript scripts
<Script type = "text/javascript">
Window. location. href = "test2.jsp ";
</Script>
Ii. redirection in servlet:
Assume that you are redirected to test2.jsp from the servlet.
1. forward
ServletContext SC = getServletContext ();
RequestDispatcher rd = SC. getRequestDispatcher ("/test/test2.jsp"); // targeted page
Rd. forward (request, response );
Public class ForwardServlet extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String id = request. getParameter ("id ");
Response. setContentType ("text/html; charset = gb2312 ");
ServletContext SC = getServletContext ();
RequestDispatcher rd = SC. getRequestDispatcher ("/test/test2.jsp"); // targeted page
Rd. forward (request, response );
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
DoGet (request, response );
}
}
2. sendRedirect
Package com. yanek. test;
Import java. io. IOException;
Import javax. servlet. RequestDispatcher;
Import javax. servlet. ServletContext;
Import javax. servlet. ServletException;
Import javax. servlet. http. HttpServlet;
Import javax. servlet. http. HttpServletRequest;
Import javax. servlet. http. HttpServletResponse;
Public class RedirectServlet extends HttpServlet {
Public void doGet (HttpServletRequest request, HttpServletResponse response)
Throws ServletException, IOException {
String id = request. getParameter ("id ");
Response. setContentType ("text/html; charset = gb2312 ");
Response. sendRedirect ("test/test2.jsp ");
}
Public void doPost (HttpServletRequest request, HttpServletResponse response)
Throws servletexception, ioexception {
Doget (request, response );
}
}