Java Web _ pageContext 和 page 对象

版权声明: https://blog.csdn.net/baidu_41671472/article/details/81981177
pageContext 对象:jsp页面的上下文对象,通过上下文对象完成请求到其他资源和包含其他资源的方法,也就是请求转发和包含的工作。也提供了获取其他内置对象的方法。
调用pageContest.forward()的方法转发。
调用getRequest, getSession....获取其他内置对象。
调用pageContest.include()的方法包含。例如:则边栏有个导航栏,
        的jsp界面,只要通过include指令找到指定的jsp界面即可。

index.jsp

<body>
    <%
        pageContext.include("header.jsp");
    %>
    <div style="float = left">
        <h1>这是index.jsp</h1>
    </div>
</body>

header.jsp

<body>
    <h1 style = "color:blue">这是头部分</h1>
</body>

最后可以发现,在index界面中加入了header.jsp里面的内容。这就是pageContext的包含功能。这样就可以分别写页面的模块,然后拼合在一起。

index.jsp

<body>
    <%
        pageContext.forward("a.jsp?name=hehe");
        /*通过pageContext对象向a.jsp传送数据”name=hehe“,
        '?'代表的是请求资源和传递参数之间的分离符。
        多个参数之间通过'&'符号来分离。*/
    %>
    <div style="float = left">
        <h1>这是index.jsp</h1>
    </div>
</body>

a.jsp

<body>
    <%= request.getParameter("name") %>
</body>

这是pageContext 的转发功能。将请求转发给其他的jsp页面。

page对象:就jsp文件运行产生的class对象。有的时候可以用this来代替page对象。
this.getInitParameter(String name)
this.getLastModified(HttpServletRequest req)
this.getServletInfo()
this.getServletName()
this.getClass()
this.getInitParameterNames()
this.getServletConfig()
this.getServletContext()

例如:

<body>
    page的基本信息:<%= this.getServletInfo() %>
</body>

pageContext作用域:当前执行页面。也是通过getAttribute()setAttribute() 完成值传递。

<body>
    <%= request.getParameter("name") %>
    <% pageContext.setAttribute("age", 12); %>
        balabalabala......
        <br>
        省略多行代码
        <br>
    <%= pageContext.getAttribute("age") %>
</body>

只要是在这个页面,pageContext就可以通过这种方法来完成值的传递。

猜你喜欢

转载自blog.csdn.net/baidu_41671472/article/details/81981177