JSP九大内置对象和四种属性范围解读

林炳文Evankaka原创作品。转载请注明出处http://blog.csdn.net/evankaka  

     摘要:本文首先主要讲解了JSP中四种属性范围的概念、用法与实例。然后在这个基础之上又引入了九大内置对象,并对这几大内置对象一个一个的进行分析的解读。内容很详细,例子都附有代码和运行的结果截图。

本文工程下载

一、四种属性范围

1.1、在JSP中提供了四种属性保存范围

page:在一个页面内保存属性,跳转之后无效
request:在一次服务请求范围内,服务器跳转后依然有效
session:-在一次会话范围内,无论何种跳转都可以使用,但是新开浏览器无法使用
application:在整个服务器上保存,所有用户都可以使用

1.2、4种属性范围都支持的操作

public void setAttribute(String name,Object value)
public Object getAttribute(String name)
public Object removeAttribute(String name)

下面,我们来对四种范围来分别进行详细的介绍

1.3、page范围

在JSP中设置一个页的属性范围,必须通过pageContext完成,PageContext属性范围是最重要的JSP属性之一,但是如果使用纯粹的JSP代码开发,此属性显示不出用处,其发挥作用在 Struts ,WebWork 中

如下:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置page属性范围,此属性只在当前JSP页面内起作用
pageContext.setAttribute("name", "linbingwen");
pageContext.setAttribute("time", new Date());
%>
姓名:${pageScope.name}<br>
时间:${pageScope.time}<br>
</body>
</html>
${pageScope.name}这里用了EL表达式来取得值,输出结果如下,


这里要注意发果在其它页面使用:

如下:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
姓名:${pageScope.name}<br>
时间:${pageScope.time}<br>
</body>
</html>
输出结果:


这说明page范围的值只能在本页使用!

1.4、request属性范围

request将属性保存在一次请求范围之内:

前提:必须使用服务器端跳转:<jsp:forward/> 应用点:MVC设计模式、Struts、 Webwork

应用实例

首先是设置request:

request.jsp

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置request属性范围
request.setAttribute("name", "linbingwen");
request.setAttribute("time", new Date());
%>
 <jsp:forward page="requestResult.jsp"/> 
</body>
</html>

然后是显示requestResult.jsp

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
获取request姓名:${requestScope.name}<br>
获取request时间:${requestScope.time}<br>
</body>
</html>

访问结果:


这时比如requestResult1.jsp也想来访问这两个属性

内容和requestResult.jsp一样:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
获取request姓名:${requestScope.name}<br>
获取request时间:${requestScope.time}<br>
</body>
</html>

结果如下,说明request只针对服务器跳转有效,在两次跳转之间保存。



1.5、session属性范围

session:只要设置上去,则不管是什么跳转,都可以取得属性,主要用于验证用户是否登陆。EMAIL--->用户需要先进行登陆,登陆成功后再编辑邮件。与session有关的任何打开的页面都可以取得session

比如session.jsp设置如下:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置session属性范围
session.setAttribute("name", "linbingwen");
session.setAttribute("time", new Date());
%>
<a href="sessionResult.jsp">获取session内容</a>
</body>
</html>
然后是取出sesson的值sessionResult.jsp

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
获取session姓名:${sessionScope.name}<br>
获取session时间:${sessionScope.time}<br>
</body>
</html>
输出结果:


如果还有一个sessionResult1.jsp和sessionResult.jsp一样如下

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置request属性范围
session.setAttribute("name", "linbingwen");
session.setAttribute("time", new Date());
%>
<a href="sessionResult.jsp">获取session内容</a>
</body>
</html>

然后是取出sesson的值sessionResult.jsp

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
获取session姓名:${sessionScope.name}<br>
获取session时间:${sessionScope.time}<br>
</body>
</html>

注意看上面的GIF动画和这里的获取到的时间是一样的,这也说明了这两个jsp页面取得了同一个值

1.6、application属性范围

只要设置一次,则所有的页面窗口都可以取得数据。这里的值将会保存在服务器上,所以每一个用户都可以看见。

如下面application.jsp:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
//设置request属性范围
application.setAttribute("name", "linbingwen");
application.setAttribute("time", new Date());
%>
<a href="applicationResult.jsp">获取application内容</a>
</body>
</html>

然后是applicationResult.jsp

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
获取application姓名:${applicationScope.name}<br>
获取application时间:${applicationScope.time}<br>
</body>
</html>

输出结果:


如果这时在新建一个网页或新建一个新的web项目,但是它们两个要运行在同一个Tomcat中,那么它同样也能访问到这个值。

注意:

pplication、session、request--==--》都与要跨多个页,属性保存是有内存开销的,设置过多的application或每一个session保存过多的对象,性能就降低了。

原则:能用request就不要用session,能用session就不要用application

application应用:在线人员统计、在线人员名单列表,要释放application资源,只能重新启动服务器.

使用application缓存数据库的连接,每次使用时,从缓冲中取出,用完就返回。

二、JSP九大内置对象详解

内置对象(又叫隐含对象,有9个内置对象):不需要预先声明就可以在脚本代码和表达式中随意使用

JSP内置对象映射表


request              请求对象                 类型 javax.servlet.ServletRequest        作用域 Request
response           响应对象                   类型 javax.servlet.SrvletResponse       作用域  Page
pageContext      页面上下文对象         类型 javax.servlet.jsp.PageContext      作用域    Page
session             会话对象                   类型 javax.servlet.http.HttpSession       作用域    Session
application        应用程序对象            类型 javax.servlet.ServletContext          作用域    Application
out                    输出对象                   类型 javax.servlet.jsp.JspWriter             作用域    Page
config               配置对象                   类型 javax.servlet.ServletConfig            作用域    Page
page                页面对象                   类型 javax.lang.Object                            作用域    Page
exception         例外对象                   类型 javax.lang.Throwable                     作用域    page

JSP中一共预先定义了9个这样的对象,分别为:request、response、session、application、out、pagecontext、config、page、exception

2.1、request对象

request 对象是 javax.servlet.httpServletRequest类型的对象。 该对象代表了客户端的请求信息,主要用于接受通过HTTP协议传送到服务器的数据。(包括头信息、系统信息、请求方式以及请求参数等)。request对象的作用域为一次请求。

实现常有的方法

1、获取数据

getParameter;;接收请求参数的,

2、对所有数据进行再编码

public byte[] getBytes(“encoding”)
如下实例将byte数组编码转换

<%@ page contentType="text/html";charset=gbk"%>
<html>
       <body>
             <%
                     //接收内容
                     String name=request.getParameter("uname");
                     byte[] b=name.getBytes("ISO8859-1");
                     name=new String(b);
                     String name= new String(request.getParameter("uname").getBytes("ISO8859-1"));
              %>
              <h1>输入内容为:<%=name%></h1>
       </body>
</html>

3、设置统一的请求编码

public void setCharacterEncoding(String env) throws UnsunpportedEncodingException
如下设置

<%@ page contentType="text/html";charset=gbk"%>
<html>
       <body>
              <%
                     //接收内容
                     request.setCharacterEncoding("GBK");
                     String name= request.getParameter("uname");
              %>
              <h1>输入内容为:<%=name%></h1>
       </body>
</html>

4、获取requst信息:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body bgcolor="#FFFFF0">
<form action="" method="post">
   <input type="text" name="name">
   <input type="submit" value="提交">
</form>
请求方式:<%=request.getMethod()%><br>
请求的资源:<%=request.getRequestURI()%><br>
请求用的协议:<%=request.getProtocol()%><br>
请求的文件名:<%=request.getServletPath()%><br>
请求的服务器的IP:<%=request.getServerName()%><br>
请求服务器的端口:<%=request.getServerPort()%><br>
客户端IP地址:<%=request.getRemoteAddr()%><br>
客户端主机名:<%=request.getRemoteHost()%><br>
表单提交来的值:<%=request.getParameter("name")%><br>
</body>
</html>

我们第一次访问是默认用GET方法,表单提交后使用POST方式。



2.2、response对象

        response 代表的是对客户端的响应,主要是将JSP容器处理过的对象传回到客户端。response对象也具有作用域,它只在JSP页面内有效。response对象的主要使用1.设置HTTP头信息、重定向、设置COOKie
(1).Web服务器收到一个http请求,会针对每个请求创建一个HttpServletRequest和HttpServletResponse对象,向客户端发送数据找HttpServletResponse,从客户端取数据找HttpServletRequest;

(2).HttpServletResponse对象可以向客户端发送三种类型的数据:a.响应头b.状态码c.数据

2.2.1、response对象所提供的方法。
(1)设定表头的方法

void addCookie(Cookie cookie) 新增cookie
void addDateHeader(String name, long date) 新增long类型的值到name标头
void addHeader(String name, String value) 新增String类型的值到name标头
void addIntHeader(String name, int value) 新增int类型的值到name标头
void setDateHeader(String name, long date) 指定long类型的值到name标头
void setHeader(String name, String value) 指定String类型的值到name标头
void setIntHeader(String name, int value) 指定int类型的值到name标头
containsHeader( String name )判断指定名字的HTTP文件头是否已经存在,然后返回真假布尔值
(2)设定响应状态码的方法
void sendError(int sc) 传送状态码(status code)
void sendError(int sc, String msg) 传送状态码和错误信息
void setStatus(int sc) 设定状态码
(3)用来URL 重写(rewriting)的方法
String encodeRedirectURL(String url) 对使用sendRedirect( )方法的URL予以编码
(4)设置重定向
sendRedirect():设置重定向页面.
2.2.2、使用范例
(1)使用response对象可以设置HTTP的头信息。格式response.setHeader(“头信息名称”,”参数”),其中一个重要的头信息:refresh(刷新)。例如,每秒刷新一次也没,显示刷新次数:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 <%!int i=0; %>  
 <%  
  //每秒刷新一次   
   response.setHeader("refresh","1");  
 %>  
<%=i++ %>  
</body>
</html>
输出结果如下:




(2)重定向

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%  
      response.setHeader("refresh","3;URL=index.jsp") ;  
      %>  
      三秒后跳转!!!<br>  
      如果没有跳转,请按<a href="index.jsp">这里</a>!!!  
</body>
</html>
来输出结果看看:

输入http://localhost:8080/JspLearning/responseObject1.jsp,三秒后自动跳转到http://localhost:8080/JspLearning/index.jsp




当然还可以使用response.sendRedirect("**.jsp");命令

如下:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%  
response.sendRedirect("index.jsp");
%> 
</body>
</html>
输出结果,直接重定向返回到首页了,


(3)设置cookie

<%@pagecontentType="text/html;charset=gb2312"%>
<HTML>
<HEAD>
<TITLE>Cookie的使用</TITLE>
</HEAD>
<BODY>
<%
Cookie c1 = newCookie("name","aaa") ;
Cookie c2 = newCookie("password","111") ;
// 最大保存时间为60秒
c1.setMaxAge(60) ;
c2.setMaxAge(60) ;
// 通过response对象将Cookie设置到客户端
response.addCookie(c1) ;
response.addCookie(c2) ;
%>
</BODY>
</HTML> 

(4)读取cookie
<%@page contentType="text/html;charset=gb2312"%>
<HTML>
<HEAD>
<TITLE>Cookie的使用</TITLE>
</HEAD>
<BODY>
<%
// 通过request对象,取得客户端设置的全部Cookie
// 实际上客户端的Cookie是通过HTTP头信息发送到服务器端上的
Cookie c[] = request.getCookies() ;
%>
<%
for(int i=0;i<c.length;i++){
Cookie temp = c[i] ;
%>
<h1><%=temp.getName()%> --> <%=temp.getValue()%></h1>
<%
}
%>
</BODY>
</HTML>

2.3、session对象

session 对象是由服务器自动创建的与用户请求相关的对象。服务器为每个用户都生成一个session对象,用于保存该用户的信息,跟踪用户的操作状态。session对象内部使用Map类来保存数据,因此保存数据的格式为 “Key/value”。 session对象的value可以使复杂的对象类型,而不仅仅局限于字符串类型。

(1)session(会话)对象是类javax.servlet.Httpsession的一个对象。session是从客户端连接服务器开始,到与服务器断开为止。
(2)session对象用于保存每个与服务器建立连接的客户端的信息,session的ID保存于客户端的Cookie中,这个session ID标识唯一和用户,与其他用户的session ID不同。
(3)session对象的ID:
当一个客户端访问服务器的一个JSP页面时,JSP引擎产生一个session对象,同时分配一个String类型的ID号,并发给客户端。客户端将其存储于Cookie.a其标志了一个唯一的ID;采用getID()方法返回session对象在服务器端的编号。服务器端通过此ID,唯一地识别一个用户,并提供特殊的服务。
(4)session对象的有效期:
存在以下几个情况时,session对象和其存储的数据会消失,情况有:
当用户关闭当前正在使用的浏览器时;
关闭网页服务器。
用户未向服务器提出请求超预设时,Tomcat服务器预设为30分钟;
运行程序结束session.
出现以上四种情况时,session对象会消失。

以下是一个简单的session登陆实例:

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login.jsp" method="post">  
    用户名:<input type="text" name="uname"><br>  
    密  码:<input type="password" name="upass"><br>  
    <input type="submit" value="登录">  
    <input type="reset" value="重置">  
</form>  
<%  
    String name = (String)request.getParameter("uname");  
    String password = (String)request.getParameter("upass");  
    if(!(name == null || "".equals(name) || password == null || "".equals(password))){  
        if("linlin".equals(name) && "123456".equals(password)){  
            //如果登录成功,则设置session的属性范围  
            session.setAttribute("userid", name);  
            response.setHeader("refresh","3;URL= welcome.jsp");   
%>          
            <h3>用户登录成功!三秒后跳转到欢迎页……</h3>  
            <h3>如果没有跳转,请按<a href="welcome.jsp">这里</a></h3>  
<%  
        }else{  
%>  
            <h3>错误的用户名或密码!</h3>  
<%  
        }   
    }  
%>  
</body>
</html>

welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%   //如果已经设置过了session属性,则肯定不为空  
    if(session.getAttribute("userid") != null){  
%>  
        <h3>欢迎<%=session.getAttribute("userid")%>登陆~~~~~~~~~~<a href="logout.jsp">注销</a></h3>  
<%  
    }else{  
%>  
        <h3>请先进行本系统的<a href="login.jsp">登录</a></h3>  
<%  
    }  
%>  
</body>
</html>

logout.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%  
    response.setHeader("refresh", "2;URL=login.jsp");  
    session.invalidate();   //注销表示当前的session失效  
%>  
<h3>你已成功退出本系统,两秒后返回到首页!</h3>  
<h3>如果没有跳转,请按<a href="login.jsp">这里</a></h3>  首页
</body>
</html>

结果如下:输入正确用户名和密码后,等三秒,自动跳转到欢迎界面welcome.jsp。欢迎界面里点注销,重定向的注销界面login.jsp,等2秒后自动跳转到login.jsp



2.4、application对象

application 对象可将信息保存在服务器中,直到服务器关闭,否则application对象中保存的信息会在整个应用中都有效。与session对象相比,application对象生命周期更长,类似于系统的“全局变量”。

运用实例:网页访问计数器。

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <body>
    <%
        if(application.getAttribute("counter") == null)
        {
            application.setAttribute("counter", "1");
        }
        else
        {
            String strnum = null;
            strnum = application.getAttribute("counter").toString();
            int icount = 0;
            icount = Integer.valueOf(strnum).intValue();
            icount++;
            application.setAttribute("counter", Integer.toString(icount));
            
        }
            
    %>
    
        您是第<%=application.getAttribute("counter") %>位访问者!
</body>
</html>

输出结果:


运行结果就是访问到该页面之后显示你是第几位访客,刷新之后数目会增加,更换浏览器或者更换客户端地址都会使其访问值正常递增。
    application的存活范围比request和session都要大。只要服务器没有关闭,application对象中的数据就会一直存在,在整个服务器的运行过程当中,application对象只有一个,它会被所有的用户共享。其中getRealPath这个方法可以获取资源在服务器上的物理路径(绝对路径),常用来获取上传文件时要存储文件的路径。

2.5、out 对象

out 对象用于在Web浏览器内输出信息,并且管理应用服务器上的输出缓冲区。在使用 out 对象输出数据时,可以对数据缓冲区进行操作,及时清除缓冲区中的残余数据,为其他的输出让出缓冲空间。待数据输出完毕后,要及时关闭输出流。

out对象的方法

clear()清除网页上输出的内容
clearBuffer()清除缓冲去的内容
close()关闭缓冲区,清除所有的内容
getBufferSize()取得缓冲区的大小
getRemaining()取得缓冲区剩余大小
isAutoFlush()获取缓冲是否进行自动清除的信息
print()进行页面输出
println()进行页面输出并换行

使用out对象进行页面的输出

<%@ page language="java" contentType="text/html;charset=gb2312" %>
<!DOCTYPE html>
<html>
    <head>
        <title>使用out对象输出内容</title>
    </head>
    <body>
        <%
            out.print("hello world");
            out.println("hello world");
        %>
    </body>
</html>
这里在页面上输出是没有什么区别的,如果想换行要使用html元素<br />
使用out对象获得缓冲区使用大小
<%@ page language="java" contentType="text/html;charset=gb2312" %>
<!DOCTYPE html>
<html>
    <head>
        <title>使用out对象求的缓冲区使用的大小</title>
    </head>
    <body>
        <%
            int all = out.getBufferSize();
            int remain = out.getRemaining();
            int use = all - remain;
            out.println("总的缓冲区大小为:"+all+"<br />");
            out.println("正在使用的缓冲区的大小为:"+remain+"<br />");
            out.println("剩余的缓冲区的大小为:"+use+"<br />");
             
        %>
    </body>
</html>

输出结果


2.6、pageContext 对象

pageContext 对象的作用是取得任何范围的参数,通过它可以获取 JSP页面的out、request、reponse、session、application 等对象。pageContext对象的创建和初始化都是由容器来完成的,在JSP页面中可以直接使用 pageContext对象。

这个对象代表页面上下文,该对象主要用于访问JSP之间的共享数据。

pageContext是PageContext类的实例,使用pageContext可以访问page、request、session、application范围的变量。

getAttribute(String name):取得page范围内的name属性。

getAttribute(String name,int scope):取得指定范围内的name属性,其中scope可以是如下4个值:

PageContext.PAGE_SCOPE:对应于page范围。

PageContext.REQUEST_SCOPE:对应于request范围。

PageContext.SESSION_SCOPE:对应于session范围。

PageContext.APPLICATION_SCOPE:对应于application范围。

实例:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%

//使用pageContext设置属性,该属性默认在page范围内
pageContext.setAttribute("name","lin-pageContext");
request.setAttribute("name","lin-request");
session.setAttribute("name","lin-session");
application.setAttribute("name","lin-application");

%>
page设定的值:<%=pageContext.getAttribute("name")%><br>
request设定的值:<%=pageContext.getRequest().getAttribute("name")%><br>
session设定的值:<%=pageContext.getSession().getAttribute("name")%><br>
application设定的值:<%=pageContext.getServletContext().getAttribute("name")%><br>
范围1内的值:<%=pageContext.getAttribute("name",1)%><br>
范围2内的值:<%=pageContext.getAttribute("name",2)%><br>
范围3内的值:<%=pageContext.getAttribute("name",3)%><br>
范围4内的值:<%=pageContext.getAttribute("name",4)%><br>
<!--从最小的范围page开始,然后是reques、session以及application-->
<%pageContext.removeAttribute("name",3);%>
pageContext修改后的session设定的值:<%=session.getValue("name")%><br>
<%pageContext.setAttribute("name","lin-modify",4);%>
pageContext修改后的application设定的值:<%=pageContext.getServletContext().getAttribute("name")%><br>
值的查找:<%=pageContext.findAttribute("name")%><br>
属性name的范围:<%=pageContext.getAttributesScope("name")%><br> 
</body>
</html>

输出结果:


2.7、config 对象

config 对象的主要作用是取得服务器的配置信息。通过 pageConext对象的 getServletConfig() 方法可以获取一个config对象。当一个Servlet 初始化时,容器把某些信息通过 config对象传递给这个 Servlet。 开发者可以在web.xml 文件中为应用程序环境中的Servlet程序和JSP页面提供初始化参数。

config 对象代表当前JSP 配置信息,但JSP 页面通常无须配置,因此也就不存在配置信息。该对象在JSP 页面中非常少用,但在Servlet 则用处相对较大。因为Servlet 需要配置在web.xml 文件中,可以指定配置参数。

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 直接输出config的getServletName的值 -->  
<%=config.getServletName()%>  
<!-- 输出该JSP中名为name的参数配置信息 -->  
name配置参数的值:<%=config.getInitParameter("name")%><br/>  
<!-- 输出该JSP中名为age的参数配置信息 -->  
age配置参数的值:<%=config.getInitParameter("age")%>  
</body>
</html>
web.xml配置里加上:

    <servlet>    
            <!--指定servlet的名字-->  
            <servlet-name>config</servlet-name>    
            <!--指定哪一个JSP页面配置成Servlet-->  
            <jsp-file>/configObject.jsp</jsp-file>  
            <!--配置名为name的参数,值为linbingwen-->  
            <init-param>    
                <param-name>name</param-name>    
                <param-value>linbingwen</param-value>    
            </init-param>    
            <!--配置名为age的参数,值为30-->  
            <init-param>    
                <param-name>age</param-name>    
                <param-value>100</param-value>    
            </init-param>    
        </servlet>    
    <servlet-mapping>   
            <!--指定将config Servlet配置到/config路径-->   
            <servlet-name>config</servlet-name>    
            <url-pattern>/config</url-pattern>    
    </servlet-mapping> 
输出结果:


2.8、page 对象

page 对象代表JSP本身,只有在JSP页面内才是合法的。 page隐含对象本质上包含当前 Servlet接口引用的变量,类似于Java编程中的 this 指针。

1 什么是page对象 ?
(1) page对象代表JSP页面本身
page对象是当前JSP页面本身的一个实例,page对象在当前JSP页面中可以用this关键字来替代。

(2) 在JSP页面哪些地方可以使用page对象
在JSP页面的Java程序片中可以使用page对象
在JSP页面的JSP表达式中可以使用page对象

(3) page对象的基类是:java.lang.Object类。
注意:如果直接通过page对象来调用方法,就只能调用Object类中的那些方法。

(4) javax,servlet.jsp.JspPage接口
JspPage接口继承于javax.servlet.Servlet接口。

我们可以使用JspPage接口对page对象进行强制类型转换,再调用JspPage接口中的各种方法。

(5) javax,servlet.jsp.HttpJspPage接口
HttpJspPage接口继承于:
javax.servlet.jsp.JspPage接口和javax.servlet.Servlet接口。

我们可以使用HttpJspPage接口对page对象进行强制类型转换,再调用HttpJspPage接口中的各种方法。

(6) 在JSP页面中使用this关键字,可调用哪些方法?
在JSP页面中,this关键字表示当前JSP页面这个对象,可以调用的常见方法,如下所示:


如下实例:

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
取page的值:<%=this.getServletInfo() %>
</body>
</html>
输出结果:


2.9、exception 对象

      Exception对象是用来处理Jsp页面文件在执行时所有发生的错误和异常;Jsp页面文件必须在isErrorPage=true的情况下才可以使用该对象;该对象一般配合Page指令一起使用,通过指定某个页面为错误处理页面,把所有的错误都集中到那个页面进行处理,可以使整个系统的性能得到加强;常用方法如下
getMessage():返回错误信息
toString:以字符串的形式返回一个对异常的描述
printStackTrace():以标准错误的形式输出一个错误和错误的堆栈

(1) 可能出错的页面:
在有可能产生异常或错误的JSP页面中,使用page指令设置errorPage属性,属性值为能够进行异常处理的某个JSP页面。
简单来说,只要在当前JSP页面中产生了异常,就交给另外一个专门处理异常的JSP页面。

(2) 专门处理错误的页面:
在专门负责处理异常的JSP页面中,使用page指令设置isErrorPage属性为true,并使用exception对象来获取出错信息。

error.jsp

<%@ page language="java" contentType="text/html;charset=UTF-8" import="java.util.*" isErrorPage="true"%>
<%@ page import="java.io.PrintStream" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=exception %><br />
    <%=exception.getMessage() %><br />
    <%=exception.getLocalizedMessage() %><br />
     
    <%
        exception.printStackTrace(new java.io.PrintWriter(out));
    %>
</body>
</html>
出错的页面

<%@page import="java.util.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="error.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
            int[] arr = {1,2,4};
            out.println(arr[3]);
        %>
</body>
</html>
输出的结果:


不加errorPage="error.jsp"这句的话:代码就会暴出来了


本文工程下载
  • 20
    点赞
  • 77
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值