本文實(shí)例總結(jié)了jsp和servlet中實(shí)現(xiàn)頁面跳轉(zhuǎn)的方式。分享給大家供大家參考,具體如下:
假設(shè)要求從test1.jsp 跳轉(zhuǎn)到test2.jsp
一. jsp中跳轉(zhuǎn):
1. 使用RequestDispatcher.forward方法轉(zhuǎn)發(fā)
% RequestDispatcher rd = getServletContext().getRequestDispatcher("/test/test2.jsp"); rd.forward(request, response); %>
2. response.sendRedirect 重定向
% response.sendRedirect("test2.jsp"); %>
3. 使用forward標(biāo)簽
4. html標(biāo)記中的meta標(biāo)記
5. 使用response.setHeader
% int stayTime=0; String URL="test2.jsp"; String content=stayTime+";URL="+URL; response.setHeader("REFRESH",content); %>
6. 使用response.setHeader和response.setStatus 發(fā)送重定向請求
% response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY); String newLocation = "test2.jsp"; response.setHeader("Location",newLocation); %>
7. 使用javascript腳本
script type="text/javascript"> window.location.href="test2.jsp"; /script>
二. servlet中跳轉(zhuǎn):
假設(shè) 從 servlet中跳轉(zhuǎn)到test2.jsp
1. forward
ServletContext sc = getServletContext(); RequestDispatcher rd = sc.getRequestDispatcher("/test/test2.jsp"); //定向的頁面 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"); //定向的頁面 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); } }
希望本文所述對大家JSP程序設(shè)計(jì)有所幫助。
標(biāo)簽:銅川 開封 臨汾 烏蘭察布 自貢 吉林 山南 白銀
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《jsp和servlet中實(shí)現(xiàn)頁面跳轉(zhuǎn)的方式實(shí)例總結(jié)》,本文關(guān)鍵詞 jsp,和,servlet,中,實(shí)現(xiàn),頁面,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。