JSP跳转与作用域

jsp的跳转分为客户端跳转和服务端跳转,与Servlet基本相同。

1.客户端跳转

<%
    response.sendRedirect("hello.jsp");
%>

2.服务端跳转

可以使用

<%
request.getRequestDispatcher("hello.jsp").forward(request,response);
%>

或者

<jsp:forward page= "hello.jsp"/>





JSP有四个作用域:

pageContext:当前页面

requestContext:一次请求

sessionContext:当前会话

applicationContext:全局,所有用户共享

  • pageContext表示当前页面作用域,通过pageContext.setAttribute(key,value)的数据,只能在当前页面访问,在其他页面就不能访问了。向作用域设置数据:
<%@ page language = "java" contentType = "text/html;charset = utf-8"
pageEncoding ="utf-8"%>
<%
    pageContext.setAttribute("name","gareen");
%>
<%=pageContext.getAttribute("name")%>

从作用域获取数据:

<%@ page language="java" contentType = "text/html;charset=utf-8"
pageEncoding="utf-8"%>
<%=pageContext.getAttribute("name")%>
  • requestContext表示一次请求,随着本次请求结束,其中的数据也被回收。
    <%@ page language = "java" contentType = "text/html;charset = utf-8"
    pageEncoding ="utf-8"%>
    <%
        request.setAttribute("name","gareen");
    %>
    <%=request.getAttribute("name")%>
    <%@ page language="java" contentType = "text/html;charset=utf-8"
    pageEncoding="utf-8"%>
    <%=request.getAttribute("name")%>

    如果发生的是服务端跳转,算是一次请求,所以可以获取到在requestContext中设置的值,这也是一种页面间传递数据的方式

    <%@ page language = "java" contentType = "text/html;charset = utf-8"
    pageEncoding ="utf-8"%>
    <%
        request.setAttribute("name","gareen");
    %>
    <jsp:forward page = "getContext.jsp"/>

    如果发生的是客户端跳转,浏览器会发生一次新的访问,新的访问会产生一个新的request对象,所以页面间客户端跳转的情况下,是无法通过request传递数据的。

<%@ page language = "java" contentType = "text/html;charset = utf-8"
pageEncoding ="utf-8"%>
<%
    request.setAttribute("name","gareen");
    response.sendRedirect("getContext.jsp");
%>
  • sessionContext指的是会话,从一个用户打开网站的那一刻起,无论访问了多少页面,链接都属于同一个会话,知道浏览器关闭。所以页面间传递数据,也是可以通过session传递的。而不同用户对应的session是不一样的,所以session无法在不同的用户之间共享数据,
<%@ page language = "java" contentType = "text/html;charset = utf-8"
pageEncoding ="utf-8"%>
<%
    session.setAttribute("name","gareen");
    response.sendRedirect("getContext.jsp");
%>
<%@ page language="java" contentType = "text/html;charset=utf-8"
pageEncoding="utf-8"%>
<%=session.getAttribute("name")%>
  • applicationContext指的是全局,所有用户共享同一个数据,application对象是ServletContext接口的实例也可以通过request.getServletContext()来获取。所以application==request.getServletContext()会返回true.application映射的就是web应用本身。
  • <%@ page language = "java" contentType = "text/html;charset = utf-8"
    pageEncoding ="utf-8"%>
    <%
        application.setAttribute("name","gareen");
        System.out.println(application==request.getServletContext());
        response.sendRedirect("getContext.jsp");
    %>
    
    <%@ page language="java" contentType = "text/html;charset=utf-8"
    pageEncoding="utf-8"%>
    <%=application.getAttribute("name")%>
发布了25 篇原创文章 · 获赞 1 · 访问量 7526

猜你喜欢

转载自blog.csdn.net/qq_28334237/article/details/83096225