6、JSP语言基础之---JSP内置对象

来源:互联网 发布:怎么联系网络运营商 编辑:程序博客网 时间:2024/06/05 21:50

对应书本第6章

总结:
数据流的观点,页面间跳转,前者页面的数据可为后者获取;
本页面的一些东西就在本页面写代码实现,代码要清晰;

注意,本章的9个内置对象都是java语言的,而非JavaScript的,所以代码放在<% %>中。
JSP内置对象有9个,不需要先定义可以直接用。
这9个分别是:request、response、session、application、out、pageContext、config、page、exception

6.2 request对象

一个请求,比如提交一个表单就是一个请求,打开一个超链接也是一个请求,当请求结束这个request也就消亡了

request对象封装了客户端产生的HTTP请求的所有细节,包括HTTP头信息、系统信息、请求方式、请求参数等。
直接用request对象的方法即可。

请求参数
超链接跳转也是一种访问请求,超链接可以带有参数。例

index.jsp中有:<a href="deal.jsp?id=1&user=">处理页</a>deal.jsp中有<%@ page language="java" contentType="text/html; charset=GB18030" pageEncoding="utf-8"%><%String id=request.getParameter("id");   //获取id参数的值String user=request.getParameter("user");//获取user参数的值,实际为空字符串""String pwd=request.getParameter("pwd");//获取pwd参数值,实际为null%><html></html>

页面转发的属性
语法:

request.setAttribute(String name,Object object);request.getAttribute(String name);

例子:

index.jsp中:<body><%try{//捕获异常信息    int money=100;    int number=0;  //可以换成其他数试试    request.setAttribute("result",money/number);//保存执行结果}catch(Exception e){    request.setAttribute("result","很抱歉,页面产生错误!");//保存错误提示信息}%><jsp:forward page="deal.jsp"/></body>deal.jsp中:<body><%  String message=request.getAttribute("result").toString(); %><%=message %></body>

获取cookie
首先保证客户机允许使用cookie!!!

cookie可以标识用户身份,记录用户名和密码,跟踪重复用户等。
浏览器是将cookie以key/value形式保存到本地某个指定目录。
方法有:
Cookie cookie = new Cookie(“cookie名”, cookie值);
Cookie[ ] cookies = request.getCookies();
response.addCookie(cookie);
cookies[i].getName() //获取cookie的key
cookies[i].getValue() //获取cookie的value

例:通过cookie保存并读取用户登录信息
效果如下:
这里写图片描述

index.jsp<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ page import="java.net.URLDecoder" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>通过cookie保存并读取用户登录信息</title></head><body><%    Cookie[ ] cookies = request.getCookies();//从request中获得Cookie对象的集合    String user = "";   //登录用户    String date = "";   //注册的时间    if (cookies != null) {        for (int i = 0; i < cookies.length; i++) {  //遍历cookie对象的集合            if (cookies[i].getName().equals("mrCookie")) {//如果cookie对象的名称为mrCookie                user = URLDecoder.decode(cookies[i].getValue().split("#")[0],"UTF-8");//获取用户名                date = URLDecoder.decode(cookies[i].getValue().split("#")[1],"UTF-8");//获取注册时间            }        }    }    if ("".equals(user) && "".equals(date)) {//如果没有注册%>        游客您好,欢迎您初次光临!        <form action="deal.jsp" method="post">            请输入姓名:<input name="user" type="text" value="">            <input type="submit" value="确定">        </form><%    } else {//已经注册%>        欢迎[<b><%=user %></b>]再次光临<br>        您注册的时间是:<%=date %><%    }%></body></html>-----------------------------------------------deal.jsp<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><%@ page import="java.net.URLEncoder" %><%@ page import="java.text.*" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>写入cookie</title><!-- 此处的window.location.href 表示当前打开的URL页面,比如这里虽然是deal.jsp但是打开页面仍是index.jsp --><script type="text/javascript">window.location.href="index.jsp"</script></head><body><%    request.setCharacterEncoding("utf-8");    String user=URLEncoder.encode(request.getParameter("user"),"utf-8");    //获取用户名,"user"是index.jsp中那个文本框名    SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒 E ");    String time=URLEncoder.encode(sdf.format(new java.util.Date()),"utf-8"); //将日期按sdf的格式并用utf-8保存到内部    // cookie是以key/value形式存储    Cookie cookie = new Cookie("mrCookie", user+"#"+time); //因为cookie内不能存储汉字,所以才化成utf-8的内部形式    cookie.setMaxAge(60*60*24*30);      //设置cookie有效期30response.addCookie(cookie); //保存cookie%></body></html>总结:整体结构是index.jsp中用到deal.jsp,所以index.jsp有request,deal.jsp有response;在jsp文件中既有java代码又有html,有的地方是两者结合着写,但是java代码放在<% %>内;为啥在点击“确定”按钮后就会到deal.jsp执行?因为浏览器并不是将所有的表单控件全部发送到服务器的,而是会查找所有的【成功控件】,只将这些成功控件的数据发送到服务端, 什么是成功控件呢?简单地来说,成功控件就是:每个表单中的控件都应该有一个name属性和”当前值“, 在提交时,它们将以 name=value 的形式做为提交数据的一部分。

request获取客户端信息(P126)
例:index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>使用request对象的相关方法获取客户端信息</title></head><body><br>客户提交信息的方式:<%=request.getMethod()%><br>使用的协议:<%=request.getProtocol()%><br>获取发出请求字符串的客户端地址:<%=request.getRequestURI()%><br>获取发出请求字符串的客户端地址:<%=request.getRequestURL()%><br>获取提交数据的客户端IP地址:<%=request.getRemoteAddr()%><br>获取服务器端口号:<%=request.getServerPort()%><br>获取服务器的名称:<%=request.getServerName()%><br>获取客户端的主机名:<%=request.getRemoteHost()%><br>获取客户端所请求的脚本文件的文件路径:<%=request.getServletPath()%><br>获得Http协议定义的文件头信息Host的值:<%=request.getHeader("host")%><br>获得Http协议定义的文件头信息User-Agent的值:<%=request.getHeader("user-agent")%><br>获得Http协议定义的文件头信息accept-language的值:<%=request.getHeader("accept-language")%><br>获得请求文件的绝对路径:<%=getServletContext().getRealPath("index.jsp")%></body></html>结果:客户提交信息的方式:GET 使用的协议:HTTP/1.1 获取发出请求字符串的客户端地址:/6.05/index.jsp 获取发出请求字符串的客户端地址:http://localhost:8080/6.05/index.jsp 获取提交数据的客户端IP地址:0:0:0:0:0:0:0:1 获取服务器端口号:8080 获取服务器的名称:localhost 获取客户端的主机名:0:0:0:0:0:0:0:1 获取客户端所请求的脚本文件的文件路径:/index.jsp 获得Http协议定义的文件头信息Host的值:localhost:8080 获得Http协议定义的文件头信息User-Agent的值:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Win64; x64; Trident/6.0) 获得Http协议定义的文件头信息accept-language的值:zh-CN 获得请求文件的绝对路径:D:\Java\eclipse_ee\lifan_workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\5\index.jsp 

request获取页面的国家信息
通过http请求能知道是从哪个国家发出的
java.util.Locale类封装了一个国家和该国所使的一种语言。
见test.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%><%@ page import="java.util.*" %><html><head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"><title>Insert title here</title></head><body><%    Locale locale=request.getLocale();    String str="";    if(locale.equals(Locale.US))        str="Welcome to US!";    if(locale.equals(Locale.CHINA))        str="欢迎来到中国!";%><%= str %></body></html>

6.3 response对象

用于响应客户请求,向客户端输出信息。
它封装了JSP产生的响应,并发送到客户端。
请求的数据可以各种数据类型,甚至是文件。
response对象在JSP页面内有效。

重定向网页

重定向与转发区别:
假设你去办理某个执照
重定向:你先去了A局,A局的人说:“这个事情不归我们管,去B局”,然后,你就从A退了出来,自己乘车去了B局。
转发:你先去了A局,A局看了以后,知道这个事情其实应该B局来管,但是他没有把你退回来,而是让你坐一会儿,自己到后面办公室联系了B的人,让他们办好后,送了过来。

代码:index.jsp重定向到login.jsp

index.jsp<body><% response.sendRedirect("login.jsp"); %></body>login.jsplogin的代码。。。

对页面的一些设置

<body>    <%     // 设置HTTP头来实现禁用缓存,下面两行    response.setHeader("Cache-Control","no-store");    response.setDateHeader("Expires",0);    // 页面每隔6s自动刷新    response.setHeader("refresh","6");    // 定时跳转    response.setHeader("refresh","5;URL=index.jsp");    %></body>

设置输出缓冲
服务器输出到客户端的内容不直接到客户端,而是先到输出缓冲区
对缓冲区配置的方法:
这里写图片描述
例:
设缓冲区大小为32KB
response.setBufferSize(32);

6.4 session对象

比request对象用途更广!!

request与session对比:
request是一个请求,比如提交一个表单就是一个请求,打开一个超链接也是一个请求,当请求结束这个request也就消亡了,只能在一次请求中使用
session是一个会话, 当用户第一次和服务器建立连接时,服务器就会产生一个session直到用户离开或超时,只要用户没有关闭浏览器就能使用

session:会话。会保存用户的状态。
为啥会有session?因为http协议是无状态协议,服务器不保存相关信息,为了弥补该缺点,http协议提供了session。
一个session会存在直到浏览器关闭,指整个浏览器关闭不是仅关闭此页面(客户端长时间不向服务器发请求session也会自动消失,时间取决于服务器,例如tomcat默认30分钟,该时间可通过编写程序修改)
一个session就是一个打电话

创建及获取会话:session.setAttribute("username","陈默");session.getAttribute("username");将session中某个对象移除:session.removeAttribute("username");session手动销毁:session.invalidate();会话超时的管理:一般session的生命周期在20-30分钟间,session提供了设置会话生命周期的方法,分别为:session.getLastAccessedTime():返回客户端最后一次与会话关联的请求时间;session.getMaxInactiveInterval():以秒为单位返回一个会话内两个请求最大时间间隔;session.setMaxInactiveInterval():以秒为单位设置session的有效时间例  session.setMaxInactiveInterval(10000);

例子:
例6.18(书本P133)在index.jsp中用户名输入框;在session.jsp将显示index.jsp中的用户名,以及一个最喜欢地方输入框;result.jsp将显示用户名及最想去的地方
代码:

本例总结:相邻页面间跳转,一些数据直接用request.getParameter()方法就可获得,而如果第三个页面需要用到第一个页面输入的属性,则需要在第二个页面将第一个页面的某个属性添加到session中,第三个页面通过session获得第一个页面的属性。

#########index.jsp<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">    <title>My JSP 'index.jsp' starting page</title>    <meta http-equiv="pragma" content="no-cache">    <meta http-equiv="cache-control" content="no-cache">    <meta http-equiv="expires" content="0">        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    <meta http-equiv="description" content="This is my page">       <link rel="stylesheet" type="text/css" href="css/style.css">  </head>  <body>  <!-- 下面是转到session.jsp-->  <form id="form1" name="form1" method="post" action="session.jsp">  。。。。。。。。。   <input type="text" name="name" />   <input type="submit" name="Submit" value="提交" />  </form>  </body></html>#########session.jsp<body></body>以上与index.jsp那部分相同 <body>  <%    String name = request.getParameter("name");     //获取用户填写的用户名        session.setAttribute("name",name);              //将用户名保存在session对象中,因为最后的result.jsp还要用到name属性   %>    <!-- 下面是转到result.jsp-->  <form id="form1" name="form1" method="post" action="result.jsp">   <table width="28%" border="0">      <tr>        <td>您的名字是:</td>        <td><%=name%></td>      </tr>      <tr>        <td>您最喜欢去的地方是:</td>        <td><label>          <input type="text" name="address" />        </label></td>      </tr>      <tr>        <td colspan="2"><label>          <div align="center">            <input type="submit" name="Submit" value="提交" />            </div>        </label></td>      </tr>    </table>  </form>###############result.jsp<body></body>以上与index.jsp那部分相同<body>    <div align="center">  <%    String name = (String)session.getAttribute("name");     //获取保存在session范围内的对象    String solution = request.getParameter("address");      //获取用户输入的最想去的地方   %><form id="form1" name="form1" method="post" action="">  <table width="28%" border="0">    <tr>      <td colspan="2"><div align="center"><strong>显示答案</strong></div>          </td>    </tr>    <tr>      <td width="49%"><div align="left">您的名字是:</div></td>      <td width="51%"><label>        <div align="left"><%=name%></div>       <!-- 将用户输入的用户名在页面中显示 -->      </label></td>    </tr>    <tr>      <td><label>        <div align="left">您最喜欢去的地方是:</div>      </label></td>      <td><div align="left"><%=solution%></div></td> <!-- 将用户输入的最想去的地方在页面中显示 -->    </tr>  </table></form></div></body>

6.5 application对象

用途:用于保存所有应用程序中的公有数据;
存在:服务器启动时自动创建,服务器停止时销毁;
没被销毁时,所有用户均可共享该application对象。
与session对比:application对象生命更长,类似于“全局变量”

获取初始化参数Parameter
在 项目名/WebContent/WEB_INF/web.xml 中

例子,在web.xml 配置连接MySQL所需的url参数<context-param>    <param-name>url</param-name>    <param-value>jdbc:mysql://127.0.0.1:3306/db_database</param-value></context-param>

application有两种方法:
application.getInitParameter(String name) //根据参数名求参数值
application.getInitParameterNames() //获取所有参数名组成枚举类型

例:获取web.xml中全部初始化参数<%@ page import="java.util.*" %><body><%    Enumeration<String> enuma=(Enumeration<String>)application.getInitParameterNames();    while(enuma.hasMoreElements())    {        String name=(String)enuma.nextElement();  //获取参数名        String value=application.getInitParameter(name); //获取参数值        out.print(name+": ");        out.println(value);    }%></body>

读写Attribute
session只在当前客户的会话范围内有效,当超过保存时间,session对象被收回;application对象在整个应用区域内有效。

application的方法有:
getAttributeNames()
getAttribute(String name)
setAttribute(String key,Object obj)
removeAttribute(String name)

6.6 out对象

用途:用于在浏览器输出信息,管理服务器上的输出缓冲区。

向浏览器输出数据
例:

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><pre>    <%        out.println(3.14);        out.println("测试");    %></pre>

管理缓冲
方法有:
clear()
clearBuffer()
flush()
isAutoFlush()
getBufferSize()

6.7 其他内置对象

pageContext、config、page、exception

0 0