JSP页面跳转的常见方式

来源:互联网 发布:兄贵pat it 编辑:程序博客网 时间:2024/05/01 08:50
JSP页面跳转的几种常用方式:
1>RequestDispatcher.forward()
  在服务器端起作用,当使用forward()时,Servlet engine传递HTTP请求从当前的Servlet或者是JSP到另外的一个Servlet、JSP 或普通HTML文件,也即你的form提交至a.jsp
,在a.jsp用到了forward()重定向至b.jsp,此时form提交的所有信息在 b.jsp都可以获得,参数自动传递. 


  重定向后浏览器地址栏URL不变,通常在Servlet中使用,不在jsp中使用。
  public void doPost(HttpServletRequest request,HttpServletResponse response)
                                throws ServletException,IOException{
  response.setContentType("text/html; charset=gb2312");
  ServletContext sc = getServletContext();
  RequestDispatcher rd = null;
  rd = sc.getRequestDispatcher("/index.jsp"); //定向的页面
  rd.forward(request, response);
  }




2> response.sendRedirect()
  在用户的浏览器端工作,sendRedirect()可以带参数传递.
  重定向后在浏览器地址栏会发生变化
  public void doPost(HttpServletRequest request,HttpServletResponse response)
                                throws ServletException,IOException{
  response.setContentType("text/html; charset=gb2312");
  response.sendRedirect("/index.jsp");
  }
  注意:
  (1) response.sendRedirect之后,应该紧跟一句return。
  比较:
  (1) Dispatcher.forward()是容器中控制权的转向,在客户端浏览器地址栏中不会显示出转向后的地址;
  (2) response.sendRedirect()则是完全的跳转,浏览器将会得到跳转的地址,并重新发送请求链接,但前者更高效也更常用!




3> 通过window.location.href="";来跳转
 
  <%
   window.location.href="index.jsp";
  %>




4> JSP中实现在某页面停留若干秒后,自动重定向到另一页面
  在html文件中,下面的代码:
  <meta http-equiv="refresh" content="300; url=target.jsp">
  代码中300为刷新的延迟时间,以秒为单位。targer.html想转向的目标页,若为本页则为自动刷新本页。
 代码:
  String content=stayTime+";URL="+URL;
  response.setHeader("REFRESH",content);



0 0
原创粉丝点击