欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jsp和servlet中实现页面跳转的方式实例总结

程序员文章站 2023-08-24 16:44:56
本文实例总结了jsp和servlet中实现页面跳转的方式。分享给大家供大家参考,具体如下: 假设要求从test1.jsp 跳转到test2.jsp 一. jsp中跳转:...

本文实例总结了jsp和servlet中实现页面跳转的方式。分享给大家供大家参考,具体如下:

假设要求从test1.jsp 跳转到test2.jsp

一. jsp中跳转:

1. 使用requestdispatcher.forward方法转发

<%
 requestdispatcher rd = getservletcontext().getrequestdispatcher("/test/test2.jsp"); 
 rd.forward(request, response); 
%>

2. response.sendredirect 重定向

<%
  response.sendredirect("test2.jsp");
%>

3.  使用forward标签

复制代码 代码如下:
<jsp:forward page="test2.jsp"/>

4. html标记中的meta标记

复制代码 代码如下:
<meta http-equiv="refresh" content="0; url=test2.jsp">

5. 使用response.setheader

<%
int staytime=0;
string url="test2.jsp";
string content=staytime+";url="+url; 
response.setheader("refresh",content);
%>

6. 使用response.setheader和response.setstatus 发送重定向请求

<%
 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中跳转:

假设 从 servlet中跳转到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程序设计有所帮助。