In jsp and servlet, the following is an example of how to achieve page Jump: jspservlet
This example summarizes the methods for page Jump in jsp and servlet. We will share this with you for your reference. The details are as follows:
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
Copy codeThe Code is as follows: <jsp: forward page = "test2.jsp"/>
4. meta tag in html Tag
Copy codeThe Code is as follows: <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"); // 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.