JSP内置对象

JSP内置对象在JSP页面中无需声明即可使用,常用的有: request, response, session, application, out, config, pageContext.

5.1 概述

1.request:request对象与HttpServletRequest类关联,是javax.servlet.ServletRequest的子类 	
	用途:获取客户端提交的数据
	
2.response:response对象与HttpServletResponse类关联 
	用途:向客户端输入数据
	
3.session:session对象与HttpSession类关联 
	用途:保存在服务器与一个客户端之间需要保留的数据 	当客户端关闭所有网页时,session会自动清除。(session对象扩展了无状态HTTP协议的功能)
	
4.application:application对象与ServletContext类关联
 	一旦创建会保持到服务器关闭为止
 	
5.out: out对象实际上市使用PrintWriter类向客户端输出数据

6.config:config对象是ServletConfig的一个对象(实例),是JSP配置处理程序的句柄。
 	有效范围是当前JSP页面
 	
7.pageContext:pageContext用来管理属于JSP中特殊可见部分中已命名对象的访问。

5.2request对象

5.2.1 request对象的方法

1.getAttribute() 
	public Object getAttribute(String name); 	
	将指定参数的参数值作为一个Object对象返回
	
2.getAttributeNames() 
	public javax.util.Enumeration getAttributeNames(); 	
	此方法得到一个枚举类型的Enumeration对象,其中的值是此次请求中可用属性的名称
	
3.getCharacterEncoding()
 	public String getCharacterEncoding(); 	
 	返回此次请求中所用字符编码的名称
 	
4.getContext()
 	public String getContext(); 	
 	返回此次请求中所用的MIME类型
 	
5.getContextPath() 
	public String getContextPath(); 	
	此方法得到请求URI中的请求的应用上下文路径,即当前Web应用的文件位置
	
6.getLocalAddr()
 	public String getLocalAddr(); 	
 	返回接收请求的Web服务器的地址

7.getLocalName()
 	public String getLocalName(); 	
 	返回接收请求的Web服务器的机器名

8.getMethod()
 	public String getMethod(); 	
 	得到此次请求中的HTTP请求类型

9.getParameter() 
	public String getParameter(); 	
	得到请求中指令的参数值

10.getParameterMap()
 	public java.util.Map getParameterMap(); 	
 	得到请求中所有参数的一个Map对象,其中参数名为键,字符串数组为值

11.getParameterNames() 
	public javax.util.Enumeration getParameterNames(); 	
	获得所有请求中参数名称的枚举

12.getParameterValues() 
	public String[] getParameterValues(String name); 	
	获得所有请求参数值的数组,数组内容为指定参数name的多个值

13.getProtocol()
 	public String getProtocol(); 
 		返回此次请求所用协议的名称和版本号,形式为:协议名称/主版本号/副版本号

14.getQueryString() 
	public String getQueryString(); 	
	返回请求URI中所包含的位于路径之后的查询字符串

15.getRemoteAddr()
 	public String getRemoteAddr(); 	
 	返回此次发送请求的客户端的IP地址

16.getRemoteHost() 
	public String getRemoteHost(); 	
	返回此次发送请求的客户端的机器名

17.getRemotePort() 
	public String getRemotePort(); 	
	获得客户端或最后一个发送请求的代理的端口号

18.getRequestURI() 
	public String getRequestURI(); 	
	返回请求路径URI

19.getRequestURL()
 	public StringBuffer getRequestURL(); 	
 	得到请求URL,包括协议、服务器名、端口号和URI路径

20.getServerPort() 
	public String getServerPort() 	
	得到接收请求的服务器端的端口号

21.getServletPath() 
	public Stirng getServletPath(); 	
	获得当前请求URI中标识Servlet的部分,如果是JSP页面则获得JSP页面的完整上下文路径

22.getSession()
 	public HttpSession getSession(); 	
 	得到与当前请求相联的Httpsession对象,如果此请求还没有会话则创建一个新会话

23.removeAttribute() 
	public void removeAttribute(String name); 	
	删除指定参数name的属性值

24.setAttribute()
 	public Object setAttribute(String name,Object attribute); 	
 	将指定的属性对象attribute用名称name保存于请求中

25.setCharacterEncoding() 
	public void setCharacterEncoding(String encoding); 	
	设置读取请求数据时所用的字符编码,此方法必须在调用request的所用其他方法之前调用,才能再行读取参数

5.2.2 获取表单数据

	在JSP中服务器端程序与客户端交互最常用的方法就是采用表单提交数据,HTML表单提交方法主要是GET和POST,最常用的是POST。
	
	使用request对象的getParameter()方法可以获取表单数据。
	
	程序中数据验证与显示由客户端浏览器完成,javaScipt语句也由客户端浏览器负责解释,在接收正确的数值后JSP程序再做出相应的处理。

5.3 response对象

	response对象与request对象相对应
	
	response对象可以用来对客户端的请求作出响应,向客户端发送各种数据(数据类型由page指令的contentType或通过response.setContentType()设置)

5.3.1 response对象的方法

	response对象实现了javax.servlet.ServlerResponse接口,此接口位于server-api.jar包中,这个接口声明如下: 
	public abstract interface javax.servlet.http.HttpServletResponse extends javax.servlet.ServerResponse ;
			可见HttpServletResponse接口扩展自ServletResponse类
1.flushBuffer() 
	此方法强制将response缓冲区中的所有内容写到客户端 		
	public void flushBuffer() throws IOException
	
2.getBufferSize() 		
	得到实际缓冲区的大小,单位为字节 		
	public int getBufferSize()
	
3.getCharacterEncoding() 		
	得到当前response的字符集编码名称 		
	public String getCharacterEncoding()
	
4.getContentType() 	
	得到当前response中所发送的MIME类型 	
	public String getContentType()
	
5.getOutputStream() 	
	返回一个可用于向response中写入二进制数据的输出流ServleetOutputStream。在JSP页面不建议使用,因为JSP页面中的数据为文本数据 	
	public ServetOutputStream getOutputStream() throws IOException

6.getWriter() 	
	返回一个可用于在response中写入文本数据的PrintWriter对象。不建议使用,因为可能会影响到Web容器的内在机制 
	public PrintWriter getWriter() throws IOException

7.sendRedirect() 	
	用于页面的重定向,参数location要导向目标地址,相对路径和绝对路径均可 		
	public void sendRedirect(String location) throws IOException	

8.setBufferSize() 	
	设置response的响应缓冲区的大小(字节数) 		
	public void setBufferSize(int size)

9.setCharacterEncoding() 	
	设置response的响应字符编码,即ContentType的charset值 		此方法必须在getWriter()之前调用 		
	public void setCharacterEncoding(String encoding)

10.setContentType() 	
	设置response的ContentType,其中包括charset值 		
	此方法必须在getWriter()之前调用 		
	public void setContentType(String type)

5.3.2使用cookie

	cookie是服务器发送给客户端浏览器的体积较小的纯文本信息,以后当浏览器访问同一个服务器时就把他们发送给服务器。通过服务器读取cookie来获取一系列方便。 	但安全性不高 	浏览器最多存放300个cookie,每个站点最多20个,单个cookie大小限制为4KB

1.创建Cookie
 	调用Cookie对象的构造方法 
	Cookie (String cookieName,String coolieValue);
注意Cookie的name和value都不能包含空白字符和以下字符:[]()=,"/?@:(冒号)

2.设置与读取Cookie的属性 
	在把Cookie加入待发送的应答头之前,可以查看和设置Cookie的各种属性。
	 		getConment/setConment 获取/设置Cookie的注释 		getDomian/setDomain 获取/设置Cookie适用的域
使用这两个方法可以指示浏览器把Cookie返回给同一个域内的其他服务器。 
	域必须以 “.”开始,非国家域两个“.”,国家域三个“.” 
	一般Cookie只返回与发送给它的服务器名称完全相同的服务器
			getMaxAge()/setMaxAge() 获取/设置Cookie的过期时间,以秒计。
				如果不设置,Cookie只在当前会话内有效,而且不会保存在磁盘上
			getName()/setName() 获取/设置Cookie的名称
			
			getPath()/setPath() 获取/设置Cookie的适用路径
				如果不设置,Cookie将返回给当前页面所在目录及其子目录下的所有页面
			getSecure()/setSecure() 获取/设置一个boolean值,表示Cookie是否只能通过加密的连接(即SSL)发送
			getvalue()/setValue() 获取/设置Cookie的值
			getVersion()/setVersion() 获取/设置Cookie所遵从的协议版本
				默认版本0遵从Netscape;版本1遵从RFC2109
				
3.将Cookie加入HTTP头中
		可将addCookie()方法加入到Set-Cookie应答头
	Cookie userCookie = new Cookie("userCookie","dzycsai") ; 
	response.addCookie(userCookie) ;
	
4.读取Cookie
		从客户端读取Cookie是调用request对象的getCookie()方法,获得与HTTP头对应的Cookie数组,再通过循环调用getName()匹配目标Cookie,找到后再调用getValue()获取Cookie值

5.Cookie工具函数
		用编写一个得到指定名称的Cookie对象值的方法
		String getCookieValue( Cookie[] cookieArray) , String cookieName ,String defaultValue) {
			for (int i=0;i<cookieArray.length;i++){
				Cookie cookie = cookieArray[i] ;
				if(cookieName.equals(cookie.getName()) ;
					return (cookie.getValue()) ;
				}
				return defaultValue ;
			}

5.3.3 response对象重定向

			sendRedirectExample1.jsp
<%@ page contentType="text/html;charset=utf-8" %>
<html>
<body>
<% //页面重定向程序片
String url;
url = request.getParameter("goaddress") ;
if(url != null)	//检验URL地址是否为空
	response.sendRedirect(url) ;
%>
<form name="form1"  action="sendRedirectExample1.jsp"  method="post" >
页面重定向:
<select name="goaddress" onchange="javascript:form1.submit()">
	<option value="">======请选择======</option>
	<option value="http://www.csai.cn">中国系统分析员</option>
	<option value="http://www.51cmm.com">软件工程专家网</option>
	<option value="http://www.hnii.gov.cn">湖南省信息办</option>
	<option value="http://www.temco.com.cn">天工远科信息技术有限公司</option>
</select>
</form>
</body>
</html>

5.3.4 定时刷新页面

				refreshExample.jsp
<%@ page contentType="text/html;charset=utf-8" %>
<%@ import "java.util.*,java.io.*, java.text.*" %>
<html>
<head>
<title>定时刷新页面</title>
</head>
<body>
<% //设置刷新页面的时间,每隔一秒刷新一次
	response.setHeader("refresh","1") ;
%>
当前时间为:
<% //输出当前最新的时间
	Date thisDay = new Date() ; 
	SimpleDateFormat sdf = new SimpleDateFormat( "yyyy'年'mm'月'dd'日'hh'时'mm'分'ss'秒' " ) ;
	out.println("中式:"+ sdf.format(thisDay) ) ;
	out.println( "美式:"+ new Date() ) ;
%>
</body>
</html>

5.4 session对象

	seesion对象用来保存与每个用户会话期间需要保持的数据信息,如用户名等,方便其他一些程序的处理

5.4.1 session的方法

	session对象实现了 java.sevlet.http.HttpSession接口,此接口位于servlet-api.jar包中
1.getAttribute()
	public Object getAttribute(String name) ;

2.getAttributeNames()
	public java.util.Enumeration getAttribute() ;

3.getMaxInactiveInterval()
	public int getMaxInactiveInterval() ;
	获得客户端会话的有效时间间隔,即客户端在网站上无任何操作还能保持会话有效的时间间隔
	
4.getServletContext()
	public java.servlet.ServletContext getServletContext() ;
	获得当前会话所属的ServletContext

5.invalidate()
	public void invalidate() ;
	此方法使当前会话失效

6.isNew()
	public boolean isNew() ;

7.removeAttribute()
	public void removeAttribute(String name) ;

8.setMaxInactiveInterval()
	public void setMaxInactiveInterval(Int time) ;
	设置会话的有效时间间隔

例子:记住会话的用户名

				sessionUserLogin.jsp
<%@ page contentType="text/html; charset=Utf-8" %>
<script language ="javaScript">
function on_submit(){//验证数据的合法性(Verify the validity of the data)
if(form1.userName.value == ""){
	alert("用户名不能为空,请输入用户名(Username is null,Please enter Username!)!");
	form1.password.focus();
	return false;
}
if(form1.userpassword.value == ""){
	alert("用户密码不能为空,请输入密码(The Userpassword is null,please enter your password)!");
	form1.userpassword.focus();
	return false;
}
}
</script>
<%!
public String codeToString(String str){
	String tempString = str;
	try{
		byte tempB[] = tempString.getBytes("utf-8");
		tempString = new String(tempB);
		return tempString;
		}catch (Exception e){
			return tempString;
		}		
	}
%>
<% 
 String username2 = request.getParameter("username") ;
 String userpassword2 = request.getParameter("userpassword") ;
 if(username2 !=null&&username2 !="" &&userpassword2 !=null&&userpassword2 !="") {
	session.setAttribute("userName" , codeToString(username2)) ;
	response.sendRedirect("sessionUserLogin1.jsp") ;
	}
%>
 <html>
 <head>
 <title>用户登录</title>
 </head>
 <body>
 <table align="center">
 <form name="form1" method="post" action="sessionUserLogin.jsp" onsubmit="return on_submit()" >
<tr align="center">
 <td>用户登录</td>
 </tr>
<tr align="center">
<td>
 请输入用户名:<input type="text" name="username" size="20" >
 </td>
 </tr>
 <tr align="center">
 <td>
 请输入密码:&nbsp;&nbsp;<input type="password" name="userpassword" size="20" >
 </td>
 </tr>
 <tr align="center">
 <td>
 <input type="submit" value="提交" name="b1" >
 <input type="reset" value="全部重写" name="b2" >
 </td>
 </tr>
</form>
</table>
</body>
</html>

第二个文件

			sessionUserLogin1.jsp
<%@ page contentType="text/html; charset=Utf-8" %>
<html>
<head>
<title>用户登录成功</title>
</head>
<body>
用户登录成功!<br>
你的用户名是:<%=(String)session.getAttribute("userName") %> 
</body>
</html>

5.4.2 猜字母游戏

			guessCharExample1.jsp
<%@ page contentType="text/html;charset=gb2312" %>
<html>
<head>
<title>猜字母游戏</title>
</head>
<body>
<% String CharString = new String ("abcdefghijklmnopqrstuvwxyz");
	int charNumber = ((int)(Math.random()*100+1)%26-1);
	Character TempCharacter = new Character (CharString.charAt(charNumber));
	session.setAttribute("ttt",TempCharacter);
 %>
<BR>
<P>输入你所猜的字母:
<form action="guessResultExample1.jsp" method="post" name="form">
	<input type = "text" name="guessChar">
	<input type = "submit" value="提交" name = "submit">
</form>
</body>
</html>

5.5 application对象

5.5.1 application对象的方法

1.getAttribute()
	public Object getAttribute(String name) ;
	获得Servlet上下文中name属性的值

2.getAttributeNames()
	public java.util.Enumeration getAttributeNames() ;

3.getContext()
	public ServletContext getContext(String urlpath) ;
	得到指定URL的Servlet上下文中的ServletContext对象,必须是绝对路径,以“/”开头

4.getInitParameter()
	public String getInitParameter(String name) ;
	得到当前Web应用上下文的name属性的值

5.getInitParameterNames()
	public java.util.Enumeration getInitParameterNames() ;

6.getRealPath()
	public String getRealPath(String path) ;
	返回path的绝对路径,如果无法解释则返回null

7.getServletContextName()
	public String getServletContextName() ;
	得到当前Web应用描述文件中<display-name>元素中定义的上下文名称

8.removeAttribute()
	public void removeAttribute(String name) ;

9.setAttribute()
public void setAttribute(String name,Object attribute) ;
将Servlet中的name属性对象设为attribute,如果name存在则替换成attribute,不存在则创建一个

5.5.2 计数器

<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>网站计数器</title>
</head>
<body>
<%!
	synchronized void countPeople(){
		ServletContext application = ((HttpServlet)(this)).getServletContext() ;
		Integer number = (Integer)application.getAttribute("Count") ;
		if(number == null){
			number = new Integer(1) ;
			application.setAttribute("Count",number) ;
		}else {
			number = new Integer(number.intValue()+1) ;
			application.setAttribute("Count",number) ;
		}
	}
 %>
 <%
 	if(session.isNew())
 		countPeople() ;
 	Integer yourNumber = (Integer)application.getAttribute("Count") ;
  %>
  欢迎访问本站,你是第<%=yourNumber %>位访问者
</body>
</html>

5.6 out对象

5.6.1 out对象的方法

out对象代表向客户端输出内容的输出对象,是java.servlet.jsp.JspWriter类的一个子类,还间接继承了java.io.Writer类

1.clear()
	public void clear() throws java.io.IOException 
	此方法清空输出缓冲区中的内容,如果缓冲区已刷新,则抛出IOException异常,以表示有些数据已被不可恢复地写至客户端

2.clearBuffer()
	public void clearBuffer() throws IOException
	此方法清空缓冲区中的内容,与clear()不同,如果缓冲区已刷新,并不抛出IOException异常

3.close()
	public void close() throws IOException
	此方法在刷新并输出JspWriter后将其关闭。如果在close()之后再调用flush()或writer(),则抛出IOException异常

4.flush()
	public void flush() throws IOException
	将缓冲区中的当前内容刷新输出,如果有Web应用则表示将缓冲区中的内容立即交付给客户端

5.getBufferSize()
	public int getBufferSize() ;
	此方法得到输出缓冲区的大小,单位为字节,如果无缓冲区则返回0

6.isAutoFlush()
	public boolean isAutoFlush() ;
	设置是否自动刷新输出缓冲区

7.print()
	public void print( Object ob ) throws IOException
	......(略去其他类型的写法)

5.6.2 用out对象输出表格

<%@ page contentType="text/html; charset=utf-8" %>
<html>
<head>
<title>out输出的表格</title>
</head>
<body>
<%
out.print("<table border='2' width='100%' ><tr><td align='center' width='100%' colspan='4'>");			//colspan单元格可横跨的格数
out.print("参会人员名单"+"</tr>") ;						//border的值为0,无线框;为1,细实线;>=2,有厚度的线框
out.print("<tr><td align='center' width='25%'>姓名</td>");			//tr换行,td换格
out.print("<td align='center' width='15%'>年龄</td>");
out.print("<td align='center' width='15%'>性别</td>");
out.print("<td align='center' width='45%'>工作单位</td>");

out.print("<tr><td align='center' width='25%'>邓子云</td>");
out.print("<td align='center' width='15%'>26</td>");
out.print("<td align='center' width='15%'>男</td>");
out.print("<td align='center' width='45%'>湖南现代物流院</td>");

out.print("<tr><td align='center' width='25%'>张伟</td>");
out.print("<td align='center' width='15%'>28</td>");
out.print("<td align='center' width='15%'>男</td>");
out.print("<td align='center' width='45%'>爱情公寓</td>");

out.print("<tr><td align='center' width='25%'>琪琪</td>");
out.print("<td align='center' width='15%'>23</td>");
out.print("<td align='center' width='15%'>女</td>");
out.print("<td align='center' width='45%'>长沙航空职业技术学院</td>");

out.print("</table>");
 %>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

White–Night

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值