JavaWeb学习----JSP内置对象详解

 【声明】 

欢迎转载,但请保留文章原始出处→_→ 

生命壹号:http://www.cnblogs.com/smyhvae/

文章来源:http://www.cnblogs.com/smyhvae/p/4065790.html

 

【系列】JSP学习系列文章:(持续更新)

JavaWeb学习(一)----JSP简介及入门(含Tomcat的使用)

JavaWeb学习(二)----JSP脚本元素、指令元素、动作元素

JavaWeb学习(三)----JSP内置对象详解

 

【正文】

呼~~~花了一下午的时间,终于把JSP的内置对象的内容学完了,并做好了笔记,方便以后回顾。

今天是10月的最后一天,小小地总结一下吧,这个月共发表博客25篇(排版好麻烦的说),所有内容均由生命壹号本人敲键盘码起。基本是一天一篇,包括国庆的时候也是独霸教研室在学习,学习的大致内容也是和数据库、JavaWeb有关。毕竟以后搞开发不可能是单机吧,网络的部分是多么的重要。下个月要提高学习效率,学习任务要加大,争取早日进入工程实践,嘿嘿~~~

菜鸟加油,恩,说我自己呢!

骚年矜持,恩,在说你咧!

一、内置对象介绍

JSP内置对象:可以不用声明和创建,就可以直接在JSP页面脚本(Java程序片和Java表达式)中使用的成员变量。

那为什么不用生命和创建就可以直接使用呢?这是因为,内置对象必须由支持JSP的容器去创建。例如Tomcat就是一个容器。

JSP共有以下9大内置对象:

  • out
  • request
  • response
  • session
  • pageContext
  • application
  • config
  • page
  • exception

前四个是重点,后五个了解即可。这九个内置对象中,有四个作用域:request、session、application、page。作用域即这个对象的生命周期的范围。

 

二、内置对象out

类型:Javax.servlet.jsp.JspWriter

作用:主要用来向客户端输出数据

作用域:page。也就是说,每个页面都有一个自己的out对象。

重要方法:print()/println()/write()    向客户端页面输出数据

举例:

out.write("文字内容"); 

我们再到D:\apache-tomcat-8.0.14\work\Catalina\localhost目录中去看一下生成的Java源代码:

1ae8844c-13fa-4c89-96c2-67476d279f4f

完整版代码如下:

/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/8.0.14
 * Generated at: 2014-10-31 11:14:54 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private javax.el.ExpressionFactory _el_expressionfactory;
  private org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public void _jspInit() {
    _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
    _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
        throws java.io.IOException, javax.servlet.ServletException {

final java.lang.String _jspx_method = request.getMethod();
if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
return;
}

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;


    try {
      response.setContentType("text/html; charset=UTF-8");
      pageContext = _jspxFactory.getPageContext(this, request, response,
                  null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\r\n");
      out.write("<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\r\n");
      out.write("<html>\r\n");
      out.write("<head>\r\n");
      out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\r\n");
      out.write("<title>Insert title here</title>\r\n");
      out.write("</head>\r\n");
      out.write("<body>\r\n");

    out.println("文字内容");

      out.write("\r\n");
      out.write("</body>\r\n");
      out.write("</html>");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}
View Code

在这里,我们可以这样理解,一个Jsp文件编译之后就是一个类,而out就对应一个页面对象。

 

三、内置对象request

类型:Javax.servlet.http.HttpServletRequest

描述:来自客户端的请求经Servlet容器处理后,由request对象进行封装。注:客户端和服务器的一次通信就是一次请求(发送请求或得到相应)。

作用域:request。说明,这次请求结束后,它的生命周期 就结束了。

重要方法:

getParameter(key) 获取提交表单的数据

getParameterValues(key) 获取提交表单的一组数据

request.getRequestDispatcher("list.jsp").forward(request,response) 转发(通过代码的方式进行转发)

request.setAttribute(key,object) 设置请求对象的属性

request.gettAttribute(key) 获取请求对象的属性

request.setCharacterEncoding("UTF-8") 对请求数据重新编码 

我们接下来将每个方法都介绍一下。

(1)getParameterValues(key)    获取提交表单的数据

举例:输入用户名密码,并验证正确性。

新建JavaWeb工程Test04,新建request.jsp文件,代码如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="request-receiver.jsp">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13         
14         <input type="submit" name="登陆"/>        
15     </form>
16 </body>
17 </html>

10至15行:添加表单,在里面输入用户名密码,然后将数据发送至request-receiver.jsp页面来处理(第10行的action里面的内容)。

新建request-receiver.jsp文件:

 1 <%
 2 //获取请求数据
 3 String name = request.getParameter("user");
 4 String pwd = request.getParameter("pwd");
 5 System.out.println(name+","+pwd);
 6 
 7 if("smyh".equals(name) && "007".equals(pwd)) {
 8     out.println("登陆成功");    
 9 }else{
10     out.println("errors");
11 }
12 %>

像request-receiver.jsp这样的页面,如果不需要显示在网页上,可以把自动生成的html代码全部删除。

整个过程是这样的:

QQ图片20141031112038

运行程序,当我们在网页输入正确的用户名之后,效果如下:

dc4eab30-df18-4375-8993-6dd32ca2f965

然后点击“提交”,效果如下:

c21d473e-cb21-4e15-8e2e-592424799dcc

【乱码问题的解决】

显然我们已经登录成功了,但是这里出现了乱码。原因是:Tomcat默认编码为:iso8859-1。request.jsp页面发出去的数据是UTF-8编码,经过tomcat服务器后,变成了iso8859-1编码,所以需要在request-receiver.jsp将数据再转回来,变成UTF-8编码(这个问题涉及到另外一个内置对象,稍后再讲)。

另外一个问题是,如果我们输入的是中文的用户名,也可能出现乱码,可以在request-receiver.jsp文件里,加一句代码让用户名、密码在控制台输出显示,看一下就知道了。

为解决乱码的问题,我们需要在request-receiver.jsp文件中加一句话:

//设置请求方式的编码

request.setCharacterEncoding("UTF-8");

这样的话,就将获取到的数据改为了UTF-8编码。

此时,如果在控制台输出的用户名还出现乱码,是因为还涉及到了另外一个问题:在request.jsp中发送请求,默认是采用get方式,这个时候,参数就会作为url的一部分一起发给服务器(见上方图片中的url地址)而url的编码很显然不是UTF-8。所以,我们需要将其改为post方式。总而言之,完整版代码如下:

request.jsp:输入用户名密码,并提交给request-receiver.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="request-receiver.jsp" method="post">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13         
14         <input  type="submit" name="登陆"/>        
15     
16     </form>
17 </body>
18 </html>

第10行,将提交方式改为post,而非默认的get方式。

request-receiver.jsp:验证用户名、密码的正确性

 1 <%
 2 //获取请求数据
 3 //设置请求方式的编码
 4 request.setCharacterEncoding("UTF-8");
 5 String name = request.getParameter("user");
 6 String pwd = request.getParameter("pwd");
 7 System.out.println(name+","+pwd);
 8 
 9 if("smyh".equals(name) && "007".equals(pwd)) {
10     out.println("登陆成功");    
11 }else{
12     out.println("errors");
13 }
14 %>

第4行,将获取到的请求数据还原为UTF-8的方式。

(2)getParameterValues(key)    获取提交表单的一组数据

我们现在往request.jsp中添加一组单选按钮:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="request-receiver.jsp" method="post">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13         <input type="checkbox" name="likes" value="羽毛球">羽毛球
14         <input type="checkbox" name="likes" value="摄影">摄影
15         <input type="checkbox" name="likes" value="音乐">音乐
16         <br/>
17                 
18         <input  type="submit" name="登陆"/>        
19     
20     </form>
21 </body>
22 </html>

13至15行是添加的三个单选按钮,构成了数组“likes”。

然后在request-receiver.jsp中获取这个数组,并在控制台输出:

 1 <%
 2 //获取请求数据
 3 //设置请求方式的编码
 4 request.setCharacterEncoding("UTF-8");
 5 String name = request.getParameter("user");
 6 String pwd = request.getParameter("pwd");
 7 System.out.println(name+","+pwd);
 8 
 9 String[] likes = request.getParameterValues("likes");
10 for(int i =0;i<likes.length;i++) {
11     System.out.println(likes[i]);
12 }
13 
14 if("smyh".equals(name) && "007".equals(pwd)) {
15     out.println("登陆成功");    
16 }else{
17     out.println("errors");
18 }
19 %>

运行后,输入对应值:

fd1c9edc-350f-435d-9308-5fd2ef423866

后台输出如下:

aaa17a7b-111d-4528-b59e-1f499038534c

(3)request.getRequestDispatcher("list.jsp").forward(request,response)   转发(通过代码的方式进行转发)

(4)request.setAttribute(key,object)   设置请求对象的属性

(5)request.gettAttribute(key)    获取请求对象的属性

现在的情形是,request.jsp负责发数据,request-receiver.jsp负责处理数据(判断用户名密码的正确性),如果用户名密码正确,那我们就通过request.getRequestDispatcher(request-success.jsp),将请求转发给request-success.jsp页面,显示出“登陆成功”的效果。

request.jsp代码不变:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="request-receiver.jsp" method="post">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13                 
14         <input  type="submit" name="登陆"/>        
15     
16     </form>
17 </body>
18 </html>

request-receiver.jsp代码如下:

 1 <%
 2 //获取请求数据
 3 //设置请求方式的编码
 4 request.setCharacterEncoding("UTF-8");
 5 String name = request.getParameter("user");
 6 String pwd = request.getParameter("pwd");
 7 System.out.println(name+","+pwd);
 8 
 9 if("smyh".equals(name) && "007".equals(pwd)) {
10     out.println("登陆成功");    
11     request.setAttribute("age", "22");
12     request.getRequestDispatcher("request-success.jsp").forward(request, response);
13     
14 }else{
15     out.println("errors");
16 }
17 %>

12行:如果用户名密码正确,就将这个请求转发给"request-success.jsp"。forward(request, response)表示当前的请求对象和当前的响应对象。

11行:在转发之前,我们可以给这个请求添加一些属性,然后在request-success.jsp页面中接收。

新建request-success.jsp,代码如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     欢迎你,<%=request.getParameter("user") %> <br/>
11     年龄:<%=request.getAttribute("age") %>    
12     
13 </body>
14 </html>

10行:获取之前的用户名,显示“欢迎你”,表示登陆成功。

11行:获取获取请求对象的属性。

运行程序,输入用户名密码后,提交,出现如下界面:(注意url)

84efb2a7-b3c3-42bd-b54a-773abfa8cba1

如果在request-receiver.jsp中没有加入第01、02行的编码方式(即页面的编码方式),最终显示的页面将会出现乱码:

b65b31de-24b8-4173-9def-764f6392fc2a 

 

四、内置对象resonpse

类型:Javax.servlet.http. HttpServletResponse

描述:它封闭了JSP 的响应,然后被发送到客户端以响应客户的请求。

作用域:page

重要方法:

response.sendRedirect("页面"):页面跳转。注意,之前的forward是转发,这里是跳转,注意区分。

response.setCharacterEncoding("gbk"):设置响应编码

注意,response.sendRedirect("页面")这个方法,是实现页面跳转,而不是转发

【举例】现在需要做的是,如果登陆失败,我们就跳到另外一个界面,而不再是转发了。

request.jsp的代码依然不变。

request-receiver.jsp的代码如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%
 4 //获取请求数据
 5 //设置请求方式的编码
 6 request.setCharacterEncoding("UTF-8");
 7 String name = request.getParameter("user");
 8 String pwd = request.getParameter("pwd");
 9 System.out.println(name+","+pwd);
10 
11 
12 if("smyh".equals(name) && "007".equals(pwd)) {
13     out.println("登陆成功");    
14     request.setAttribute("age", "22岁");
15     request.getRequestDispatcher("request-success.jsp").forward(request, response);
16     
17 }else{
18     //out.println("errors");
19     response.setCharacterEncoding("UTF-8"); //设置响应的编码
20     //设置响应内容的类型
21     response.setContentType("text/html;charset=UTF-8");
22     response.sendRedirect("response.jsp");
23 }
24 %>

19行至22行是添加的代码:如果用户名、密码错误,就调到response.jsp页面去。

新建response.jsp,代码如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     不好意思,登陆失败。
11 </body>
12 </html>

注意第06行的“content=text/html”,表示:指定服务器返回的数据类型。

运行程序,当输入的用户名、密码错误后,效果如下:(注意url)

a498dc2e-a856-4499-bd21-70245ac2c260

重定向和转发:

重定向的意思是说,当页面进行跳转之后,request和response的生命周期已经结束,完全交给下一个页面去处理了(连url都变了);而转发的时候,还可以往request里面添加携带参数(url不变)。

 

五、session(会话)

类型:Javax.servlet.http.HttpSession

描述:表示一个会话,用来保存用户信息,以便跟踪每个用户的状态。(不要用来保存业务数据,request)

定义:是指在一段时间内客户端和服务器之间的一连串的相关的交互过程。

作用域:session。

如果是第一次接触“会话”这个概念,需要重复一下。说白了,客户端与服务器之间可能需要不断地进行数据交互(请求与相应),这个过程就可以理解为一段回话。Tomcat默认的会话时间为30分钟,这段时间内如果没有交互,会话结束;下次客户端一旦发送请求,重新创建会话。当客户端第一次发送请求的时候,才会创建一个会话。session的生命周期比request长

重要方法:

session.getid():取得session的id号.id由tomcat自动分配。

session.isnew():判断session时候是新建的

session.setAttribute(key,object):往当前会话中设置一个属性

session.getAttribute(key):获取当前会话中的一个属性

session.removeAttribute(key):删除当前会话中的属性

session.setMaxInactiveInterval(1000*60*30):设置当前会话失效时间(ms) 。Tomcat默认的会话时间为30分钟。

session.invalidate():初始化当前会话对象(一般在推出的时候使用,可以删除当前会话的数据) 

会话结束的条件之一:

  • 服务器关闭
  • 会话过期(一段会话时间默认为30分钟)
  • 手动终止会话

【举例】为保持用户登录的状态,我们可以把用户的数据信息保存在session中。

request.jsp登录表单的代码如下:用户登录界面

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="session.jsp" method="post">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13                 
14         <input  type="submit" name="登陆"/>            
15     </form>
16 </body>
17 </html>

session.jsp代码如下:(核心代码)

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <%
 4 //获取请求数据
 5 //设置请求方式的编码
 6 request.setCharacterEncoding("UTF-8");
 7 String name = request.getParameter("user");
 8 String pwd = request.getParameter("pwd");
 9 
10 if("smyh".equals(name) && "007".equals(pwd)) {
11     //将用户名、密码保存到当前会话当中
12     session.setAttribute("name", name);
13     session.setAttribute("pwd", pwd);
14     //如果登陆成功,就跳到session-success.jsp页面
15     response.sendRedirect("session-success.jsp");    
16     
17     System.out.println(session.getId()); //获取当前回话的id
18     //session.setMaxInactiveInterval(1000*60*30); //设置当前session的有效时间
19     //session.invalidate()  //设置session重新初始化,在系统退出时使用
20 }else{
21     response.sendRedirect("fail.jsp");
22 }
23 %>

12、13行:将用户名、密码保存到当前会话当中,只要这段会话没有结束,就可以从session中获取值。

15行:如果用户名密码正确,就跳到session-success.jsp界面

18行:设置当前session的会话时间,不过一般不在代码里设置,而是在web.index里设置:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
 3   <display-name>Test04</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   
13   <!-- 设置当前sessionn的有效时间(分钟) -->
14   <session-config>
15      <session-timeout>30</session-timeout>     
16   </session-config>
17 </web-app>

14行至16行是我设置的会话时间,单位为min。

session-success.jsp代码如下:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <%
11         String name = (String)session.getAttribute("name");
12         String pwd = (String)session.getAttribute("pwd"); 
13         out.println("登陆成功");
14         out.println(name+","+pwd);
15         System.out.println(session.getId()); //获取当前回话的id
16     %>
17 
18 </body>
19 </html>

15行:获取当前会话的id,这个id和session.jsp中18行的id应该是同一个。

登录失败的界面fail.jsp的代码我就不写了。

运行程序,输入用户名密码,提交,会跳到session-success.jsp:

54f76bf2-d96c-44d8-b6f8-f64317ff2376

因为是同一个会话,所以后台输出的id也是同一个:

029df7e0-3dc8-4615-bb95-6459ff545891

现在我们明白了,request中可以存数据,session中也可以存数据。如果是保存用户名信息等,可以存到session中;如果只需要传递数据(从这个页面传到另一个页面),就可以放在request中转发出去,避免内存浪费。

 

六、内置对象pageContext

类型:javax.servlet.jsp.PageContext

描述:本JSP的页面上下文。

作用域:page

注:上下文的理解:上下文可以联系到当前页面所有的信息。

我们先来回顾一下原始的request.jsp代码:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="session.jsp" method="post">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13                 
14         <input  type="submit" name="登陆"/>            
15     </form>
16 
17 </body>
18 </html>

现在将上面的代码改成下面的这个样子:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="<%=request.getContextPath()%>/session.jsp" method="post">
11         username:<input  type="text" name="user"/><br/>
12         password:<input  type="password" name="pwd"/><br/>
13                 
14         <input  type="submit" name="登陆"/>            
15     </form>
16 
17     <h2>pageContext对象</h2>
18     <%
19     //通过PageContext上下文对象获取当前页面的其他内置对象
20     pageContext.getRequest();
21     pageContext.getResponse();
22     pageContext.getSession();
23     pageContext.getOut();
24     String path = request.getContextPath();
25     out.println("当前上下文的绝对路径:"+path);    
26     %>
27 
28 </body>
29 </html>

20至23行:通过PageContext上下文对象获取当前页面的其他内置对象

24行:通过request.getContextPath()获取当前文件的绝对路径。此时,可以在第10行写上session.jsp文件的绝对路径(),以前都是用相对路径写的,是因为文件都在同一目录下。如果jsp文件在其他的文件夹,通过request.getContextPath()来获取路径就相当方便了,避免书写错误。程序运行后,效果如下:

4df0238c-d2d7-4936-a89b-8dc180fe43de 

 

七、内置对象application

类型:javax.servlet.ServletContext

描述:从servlet配置对象获得的servlet上下文

作用域:application

这个对象的生命周期是最长的。服务器启动的时候就会创建application对象。从服务器存在到服务器终止,都一直存在,且只保留一个对象,所有用户共享一个application。不是很常用。

举例:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 
11     <h2>application对象</h2>
12     <%
13     //一个应用程序只有一个application对象
14     //在服务器启动时创建,到服务器关闭时销毁
15     //所有客户端共享一份
16     String serverPath = application.getContextPath();//获取当前应用程序的路径
17     out.println(serverPath);
18     //向application对象添加数据
19     application.setAttribute("", "");
20     
21     %>
22 
23 </body>
24 </html> 

d0c2451d-79c4-4a81-951c-2b5ed1bb0f08

 

 

八、内置对象config

类型:javax.servlet.ServletConfig

描述:本JSP的 ServletConfig

作用域:page

注:代表配置对象,基本用不到。

 

九、内置对象page

类型:java.1ang.Object

描述:实现处理本页当前请求的类的实例(javax.servlet.jsp.HttpJspPage),转换后的Servlet类本身

作用域:page

 

十、内置对象exception

类型:java.lang.Exception

描述:本JSP页面的异常对象

作用域:page

JSP常见错误状态码:

403:禁止访问。比如IP地址被拒绝,站点访问被拒绝等

404:找不到。没有找到文件或目录

500:服务器由于遇到错误而不能完成该请求,Web服务器太忙

举例:

新建一个错误页面error.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" isErrorPage="true"%> 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <h2>错误信息</h2>
11     错误信息为:<%=exception%>
12 </body>
13 </html>

第02行:必须通过isErrorPage="true"指定此页面为错误页面,否则出现了第11行的exception,程序就会报错。

新建另外一个页面use-eception.jsp:

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8" errorPage="error.jsp" %>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10 <%
11     int[] num = {9,2,3,2,8};
12     for(int i =0;i<=num.length;i++){
13         out.println(num[i]);
14     }
15 %>
16 
17 </body>
18 </html>

我们故意在11至14行写一段错误的代码;

02行:命令 errorPage="error.jsp",表示指定错误页面为error.jsp,如果本页面发生错误,就会跳到error.jsp页面中去。

程序运行后,效果如下:

058343be-e396-4923-b402-307484dd016d

不过,实际程序中,一般不这么写,因为业务是写在类里,如果发生错误,将采取其他的办法来处理,那就以后再说咯~~~

posted @ 2014-10-31 19:58  千古壹号  阅读(28315)  评论(10编辑  收藏  举报