This article summarizes the way that page jumps are implemented in JSP and servlet. Share to everyone for your reference, specific as follows:
Suppose you want to jump from test1.jsp to test2.jsp
A. JSP Jump:
1. Forwarding using the Requestdispatcher.forward method
<%
RequestDispatcher rd = Getservletcontext (). Getrequestdispatcher ("/test/test2.jsp");
Rd.forward (request, response);
%>
2. Response.sendredirect redirect
<%
response.sendredirect ("test2.jsp");
%>
3. Use the Forward label
Copy Code code as follows:
<jsp:forward page= "test2.jsp"/>
4. Meta tags in HTML tags
Copy Code code as follows:
<meta http-equiv= "Refresh" content= "0; Url=test2.jsp ">
5. Use of Response.setheader
<%
int staytime=0;
String url= "test2.jsp";
String content=staytime+ "; Url= "+url;
Response.setheader ("REFRESH", content);
%>
6. Send a redirection request using Response.setheader and Response.setstatus
<%
Response.setstatus (httpservletresponse.sc_moved_permanently);
String newlocation = "test2.jsp";
Response.setheader ("Location", newlocation);
%>
7. Using JavaScript scripts
<script type= "Text/javascript" >
window.location.href= "test2.jsp";
</script>
Two. In the servlet jump:
Suppose you jump from the servlet to test2.jsp
1. Forward
ServletContext sc = Getservletcontext ();
RequestDispatcher rd = Sc.getrequestdispatcher ("/test/test2.jsp"); Directed 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"); Directed 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);
}
}
I hope this article will help you with JSP program design.