Skip to content

JSP内置对象

JSP为简化页面的开发提供了一些内部对象。

这些内部对象不需要由JSP的编写者实例化,它们由JSP容器实现和管理,在所有JSP页面中都能使用内部对象。

内部对象只对表达式和Scriptlet有用,在声明中不能使用。

隐含对象


JSP隐含对象功能概述

对象名称 衍 生 类 功能说明
request javax.servlet.ServletRequest. HttpServletRequest 取得客户端数据与系统的信息
application javax.servlet.ServletContext 记录与处理在线用户共享的数据。
session javax.servlet.http.HttpSession 记录与处理在线用户个别的数据。
out javax.servlet.jsp.JspWriter 控制数据输出的操作。
config javax.servlet.ServletConfig 取得JSP编译后Servlet的信息。
pageContext javax.servlet.jsp.PageContext 存取与处理系统运行时期的各项信息
page java.lang.Object 代表目前的这个JSP网页对象
exception java.lang.Throwable 例外处理机制

输入/输出对象

控制页面的输入和输出

访问与所有请求和响应有关的数据

包括以下三类:

  • out 对象

  • request 对象

  • response 对象

out对象

表示输出流

javax.servlet.jsp.JspWriter 类的实例

使用 write()、print() 和 println() 方法

out

OutTest.jsp
<%
out.println("<table border='1'>");
out.println("<tr>");
out.println("<th bgcolor='#FF6600'>类型</td>");
out.println("<th bgcolor='#FF6600'>输出内容</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>逻辑值</td>");
out.println("<td>");
out.print(true);//输出true
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>字符值</td>");
out.println("<td>");
out.println('c');
out.println("</td>");
out.println("</tr>");
out.println("<tr>");
out.println("<td>整数值</td>");
out.println("<td>");
out.println(34);
%>
源代码
OutTest.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>

    <%
    out.println("<table border='1'>");
    out.println("<tr>");
    out.println("<th bgcolor='#FF6600'>类型</td>");
    out.println("<th bgcolor='#FF6600'>输出内容</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>逻辑值</td>");
    out.println("<td>");
    out.print(true);//输出true
    out.println("</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>字符值</td>");
    out.println("<td>");
    out.println('c');
    out.println("</td>");
    out.println("</tr>");
    out.println("<tr>");
    out.println("<td>整数值</td>");
    out.println("<td>");
    out.println(34);
    %>
</body>

</html>

request对象

表示客户端对网页的请求

实现 javax.servlet.http.HttpServletRequest

使用 HTTP 协议处理客户端的请求

request

String getParameter(String name)

  • 根据页面表单组件名称获取请求页面提交数据

String[ ] getParameterValues (String name)

  • 获取页面请求中一个表单组件对应多个值时的用户的请求数据

RequestTest.jsp
<%
out.println("<h4>hello " + request.getParameter("username") + "</h4>");
out.println("<h4>Your password : " + request.getParameter("password") + "</h4>");
out.println("<br>request.getMethod():");
out.println(request.getMethod()); //返回请求的方法;

out.println("<br>request.getParameterNames():");
Enumeration enumdata = request.getParameterNames(); //返回参数名的枚举;
while (enumdata.hasMoreElements()) {
    String s = (String) enumdata.nextElement(); //返回参数名
    out.println("参数" + s + "=" + request.getParameter(s) + " ;");//输出参数名和对应的参数值
}
%>
源代码
RequestTest.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8" import="java.util.*"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>

    <%
    out.println("<h4>hello " + request.getParameter("username") + "</h4>");
    out.println("<h4>Your password : " + request.getParameter("password") + "</h4>");
    out.println("<br>request.getMethod():");
    out.println(request.getMethod()); //返回请求的方法;

    out.println("<br>request.getParameterNames():");
    Enumeration enumdata = request.getParameterNames(); //返回参数名的枚举;
    while (enumdata.hasMoreElements()) {
        String s = (String) enumdata.nextElement(); //返回参数名
        out.println("参数" + s + "=" + request.getParameter(s) + " ;");//输出参数名和对应的参数值
    }
    %>
</body>

</html>

response对象

处理 JSP 生成的响应

将响应发送给客户端

实现javax.servlet.http.HttpServletResponse 接口使用 HTTP 协议将响应发送给客户端

response

response 对象常用方法

  • void setContentType (String name)

    • 设置作为响应生成的内容的类型和字符编码
  • void sendRedirect (String name)

    • 发送一个响应给浏览器,指示其应请求另一个URL

ResponseTest/Login.jsp
1
2
3
4
5
6
7
8
9
<%
String name = request.getParameter("username");
if (name == null)
  response.sendRedirect("Login.html");
else if (name.equals("chenyi"))
  response.sendRedirect("Welcome.jsp");
else
  throw new Exception("未注册用户!");
%>

源代码
ResponseTest/Login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>

  <%
  String name = request.getParameter("username");
  if (name == null)
    response.sendRedirect("Login.html");
  else if (name.equals("chenyi"))
    response.sendRedirect("Welcome.jsp");
  else
    throw new Exception("未注册用户!");
  %>
</body>

</html>

源代码
ResponseTest/Welcome.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8" import="java.util.*"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <p>
  <h2 align="center">request的Headers信息</h2>
  </p>
  <p align="left">
    request的method:<%=request.getMethod()%><br> request的URI:<%=request.getRequestURI()%><br>
    request的Protocol:<%=request.getProtocol()%><br>
  </p>
  <table border="2">
    <th bgcolor="#FF6600">request header</th>
    <th bgcolor="#FF6600">request values</th>
    <%
    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
      String headName = (String) headerNames.nextElement();
      out.println("<tr><td>" + headName);
      out.println("<td>" + request.getHeader(headName));
    }
    %>
  </table>
</body>

</html>

作用域通信对象

内置对象的作用域

  • Page

  • Request

  • session

  • application

作用域通信对象

  • Application

  • Session

  • pageContext


session对象

Web 服务器为单个用户发送的多个请求创建会话存储有关用户会话的所有信息

javax.servlet.http.HttpSession接口的实例

session 对象最常用的方法有:

  • void setAttribute(String name,Object value)

    • 以键/值的方式,将一个对象的值存放到session 中
  • void getAttribute(String name)

    • 根据名称去获取session中存放对象的值

SessionTest/Login.html
1
2
3
4
5
6
7
<form action="Login.jsp" method="POST">
  <label for="username">用户名:</label> 
  <input type="text" id="username" name="username" /><br> 
  <label for="password">密码:</label> 
  <input type="password" id="password" name="password" /><br> 
  <input type="submit" value="登录" />
</form>

源代码
SessionTest/Login.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登录页面</title>
</head>
<body>
  <h1>登录</h1>
  <form action="Login.jsp" method="POST">
    <label for="username">用户名:</label> 
    <input type="text" id="username" name="username" /><br> 
    <label for="password">密码:</label> 
    <input type="password" id="password" name="password" /><br> 
    <input type="submit" value="登录" />
  </form>
</body>
</html>
SessionTest/Login.jsp
<%
String username = request.getParameter("username");
String password = request.getParameter("password");
if (username == null)
  username = "";
if (password == null)
  password = "";

if (username.equals("chen yi") && password.equals("123456")) {
  //验证用户信息
  session.setAttribute("username", "chen yi");
  response.sendRedirect("Welcome.jsp");//进入欢迎页面
} else {
  response.sendRedirect("Login.html");//进入登陆页面
}
%>
源代码
SessionTest/Login.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <%
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  if (username == null)
    username = "";
  if (password == null)
    password = "";

  if (username.equals("chen yi") && password.equals("123456")) {
    //验证用户信息
    session.setAttribute("username", "chen yi");
    response.sendRedirect("Welcome.jsp");//进入欢迎页面
  } else {
    response.sendRedirect("Login.html");//进入登陆页面
  }
  %>
</body>

</html>

SessionTest/Welcome.jsp
1
2
3
4
5
<%
String username = (String) session.getAttribute("username");
%>
<p>欢迎您!<%=username%></p>
<a href="Bye.jsp">注销</a>

源代码
SessionTest/Welcome.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8" import="java.util.*"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <%
  String username = (String) session.getAttribute("username");
  %>
  <p>欢迎您!<%=username%></p>
  <a href="Bye.jsp">注销</a>
</body>

</html>

SessionTest/Bye.jsp
1
2
3
4
5
6
7
8
<%
String username = (String) session.getAttribute("username");
out.println("Session ID:" + session.getId());//输出会话编号
session.invalidate();//注销会话。 
if (username != null) {
  out.println(username + "再见!欢迎再来!");
}
%>

源代码
SessionTest/Bye.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <%
  String username = (String) session.getAttribute("username");
  out.println("Session ID:" + session.getId());//输出会话编号
  session.invalidate();//注销会话。 
  if (username != null) {
    out.println(username + "再见!欢迎再来!");
  }
  %>
</body>

</html>

pageContext对象

描述 JSP 页面运行的上下文环境。

提供对所有其它内部对象及其属性的访问。

是 javax.servlet.jsp.PageContext 类的一个实例。

函数 功能
forward (String UrlPath) 页面重定向
getRequest() 返回当前的request对象
getResponse() 返回当前的response对象
getSession() 返回当前页面的session对象
getServletContext() 返回Servlet Context对象
setAttribute(String name,Object value) 设置属性
getAttribute(String name,int scope) 获得scope范围的属性

PageContextTest.jsp
<%
pageContext.setAttribute("name", new String("陈轶"));
pageContext.setAttribute("userId", new String("chan_yee"));
%>
<table align="center" border="2">
  <tr>
    <th bgcolor="#FF6600">参数</th>
    <th bgcolor="#FF6600"></th>
  </tr>
  <tr>
    <td>姓名</td>
    <td><%=pageContext.getAttribute("name")%></td>
  </tr>
  <tr>
    <td>用户号</td>
    <td><%=pageContext.getAttribute("userId")%></td>
  </tr>
</table>
源代码
PageContextTest.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <%
  pageContext.setAttribute("name", new String("陈轶"));
  pageContext.setAttribute("userId", new String("chan_yee"));
  %>
  <table align="center" border="2">
    <tr>
      <th bgcolor="#FF6600">参数</th>
      <th bgcolor="#FF6600"></th>
    </tr>
    <tr>
      <td>姓名</td>
      <td><%=pageContext.getAttribute("name")%></td>
    </tr>
    <tr>
      <td>用户号</td>
      <td><%=pageContext.getAttribute("userId")%></td>
    </tr>
  </table>
</body>

</html>

pageContext和session、ServletContext属性比较

pageContext设置的属性只在当前页面范围有效。

session设置的属性在当前session中是共享的。

ServletContext设置的属性对所有用户都是共享的。


application对象

表示 JSP 页面所属的应用程序

应用程序的 JSP 页面组合起来形成一个应用程序

javax.servlet.ServletContext接口实例

application对象最常用的方法有:

  • void setAttribute(String name,Object value)

    • 以键/值方式,将一个对象的值存放到application中
  • void getAttribute(String name)

    • 根据名称去获取application中存放对象的值

ApplicationTest.jsp
<%
int count = 1;
try {
  count = Integer.parseInt(application.getAttribute("counter").toString());
} catch (Exception e) {
  out.println("<p align=center>计数器没有发生作用!</p>");
}
out.println("<p align=center>自从服务器启动后,此页面已经访问了" + count + "次</p>");
count++;
application.setAttribute("counter", count);
%>

源代码
ApplicationTest.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <%
  int count = 1;
  try {
    count = Integer.parseInt(application.getAttribute("counter").toString());
  } catch (Exception e) {
    out.println("<p align=center>计数器没有发生作用!</p>");
  }
  out.println("<p align=center>自从服务器启动后,此页面已经访问了" + count + "次</p>");
  count++;
  application.setAttribute("counter", count);
  %>
</body>

</html>

servlet 对象

JSP引擎为每个JSP生成一个Servlet

Servlet对象提供了访问 Servlet 信息的方法和变量

Servlet 对象包括

  • page

  • config


page 对象

使用 page 对象可以访问 Servlet 类的所有变量和方法java.lang.Object类的一个实例

1
2
3
4
5
6
<% @ page info=我的信息 contentType=text/html;charset=GBK%>
<html>
<body>
   <%=((javax.servlet.jsp.HttpJspPage)page).getServletInfo()%>
</body>
</html>

config 对象

存储在编译 JSP 页面的过程中创建的 servlet 的信息

javax.servlet.servletConfig 接口的实例

提供了检索 servlet 初始化参数的方法

String propertyFile = (String)config.getInitParameter(”PropertyFile”);

ConfigTest/ConfigTest1.jsp
1
2
3
4
5
6
7
8
<%
Enumeration conenum = config.getInitParameterNames();
while (conenum.hasMoreElements()) {
  String str = (String) conenum.nextElement();
  out.println("<tr><td>" + str + "</td>");
  out.println("<td>" + config.getInitParameter(str) + "</td></tr>");
}
%>

源代码
ConfigTest/ConfigTest1.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8" import="java.util.*"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <table border="2">
    <th bgcolor="#FF6600">参数名</th>
    <th bgcolor="#FF6600"></th>
    <%
    Enumeration conenum = config.getInitParameterNames();
    while (conenum.hasMoreElements()) {
      String str = (String) conenum.nextElement();
      out.println("<tr><td>" + str + "</td>");
      out.println("<td>" + config.getInitParameter(str) + "</td></tr>");
    }
    %>
  </table>
</body>

</html>

ConfigTest/ConfigTest2.jsp
<%
int org = 0;
int count = 0;
try {
  org = Integer.parseInt(config.getInitParameter("counter"));
} catch (Exception e) {
}
try {
  count = Integer.parseInt(application.getAttribute("config_counter").toString());
} catch (Exception e) {
}
if (count < org)
  count = org;
out.println("此页面已经访问了" + count + "次");
count++;
application.setAttribute("config_counter", new Integer(count));
%>

源代码
ConfigTest/ConfigTest2.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>

<body>
  <%
  int org = 0;
  int count = 0;
  try {
    org = Integer.parseInt(config.getInitParameter("counter"));
  } catch (Exception e) {
  }
  try {
    count = Integer.parseInt(application.getAttribute("config_counter").toString());
  } catch (Exception e) {
  }
  if (count < org)
    count = org;
  out.println("此页面已经访问了" + count + "次");
  count++;
  application.setAttribute("config_counter", new Integer(count));
  %>
</body>

</html>

Exception对象

exception对象用于处理 JSP 页面中的错误

exception 对象用于访问执行 JSP 的过程中引发的异常

exception 对象是 java.lang.Throwable 类的实例

error.jsp
<%@ page isErrorPage="true" contentType="text/html; charset=utf-8"
  pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>错误页面</title>
</head>
<body>
  <h1>发生错误</h1>
  <p>
    错误类型:
    <%=exception.getClass().getName()%></p>
  <p>
    错误信息:
    <%=exception.getMessage()%></p>
</body>
</html>