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

来源:互联网 发布:java数据结构和算法 编辑:程序博客网 时间:2024/05/22 04:35

简介

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

隐式对象

隐式对象 说明 out JspWriter对象,内部关联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>
原创粉丝点击