您的位置:首页 > Web前端 > JavaScript

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

2017-07-22 20:07 459 查看

简介

隐式对象是_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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JSP 隐式对象