JSP-隐式对象、pageContext、错误处理

简介

隐式对象是_jspService()中的局部变量,故只能在<% %><%= %>中使用

隐式对象

隐式对象说明
outJspWriter对象,内部关联PrintWriter对象
request对应HttpServletRequest对象
response对应HttpServletResponse对象
config对应ServletConfig
application对应ServletContext
session对应HttpSession
pageContext对应PageContent对象。将所有JSP页面信息封装起来,可以通过pageContext获得所有的隐式对象
exception对应Throwable对象,代表由其他JSP页面抛出的一场对象,只会出现在JSP错误页面
page对应转译后的this

pageContext

使用pageContext可以获取所有隐式对象,也可以访问 page、request、session、application范围的变量。

    request = pageContext.getRequest();
    response = pageContext.getResponse();
    config = pageContext.getServletConfig();
    application = pageContext.getServletContext();
    session = pageContext.getSession();
    out = pageContext.getOut();

常用方法:

  • setAttribute(String name, String value, int scope):如果没有指定scope,该属性默认在page范围内
  • getAttribute(String name, int scope) 获得属性值
  • removeAttribute(String name, int scope) 移除属性
  • findAttribute()依次从页面、请求、会话、应用程序范围查找有无对应的属性

查找范围(scope)

  • pageContext.APPLICATION_SCOPE ServletContext(application)
  • pageContext.REQUEST_SCOPE request
  • pageContext.SESSION_SCOPE session
  • pageContext.PAGE_SCOPE pageContext
    <%
    pageContext.setAttribute("scope", "page");
    session.setAttribute("scope", "session");
    application.setAttribute("scope", "application");
    request.setAttribute("scope", "request");

    %>
    page:<%= pageContext.getAttribute("scope", pageContext.PAGE_SCOPE) %><br/>
    session:<%= pageContext.getAttribute("scope", pageContext.SESSION_SCOPE) %><br/>
    application:<%= pageContext.getAttribute("scope", pageContext.APPLICATION_SCOPE) %><br/>
    request:<%= pageContext.getAttribute("scope", pageContext.REQUEST_SCOPE) %><br/>

错误处理

错误界面只有iserrorPage为true时才可以使用exception对象

发生错误的页面 hello.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page errorPage="Error.jsp" %>

<html>
  <body>
    <%=1/0 %>
  </body>
</html>

错误页面 error.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page isErrorPage="true" %>
<html>
  <body>
  <h1>这是一个错误界面</h1>
    <%=exception %>
    <hr/>
  </body>
</html>

error-page

如果希望容器在发现某个错误或者异常时,自动转发至错误页面,则可以使用 <error-page></error-page>

 <error-page>
    <exception-type>java.lang.ArithmeticException</exception-type>
    <location>/JSPTest/Error.jsp</location>
 </error-page>

  <error-page>
    <error-code>404</error-code>
    <location>/JSPTest/Error.jsp</location>
 </error-page>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值