显式地声明它们。 可以使用的隐含变量包括:
session:实现 HttpSession 接口的类的一个实例
application:实现 HttpSession 接口的类的一个实例
request:实现 HttpServletRequest 接口的类的一个实例
pageContext: PageContext 类的一个实例
清单 31 显示了如何在 JSP scriptlet 中针对不同的范围添加和删除对象。
清单 31. JSP 页面中的状态管理
<%@ page contentType="text/html; charset=iso-8859-1" language="java" session="true" %>
<%
String foo = "I am a Foo";
// Place object in session scope
session.setAttribute("Foo", foo);
// Retrieve from session scope
String sessionFoo = (String) session.getAttribute("Foo");
// Place object in application scope
application.setAttribute("Foo", foo);
// Retrieve from application scope
String applicationFoo = (String) application.getAttribute("Foo");
// Place object in page scope
pageContext.setAttribute("Foo", foo);
// Retrieve from page scope
String pageFoo = (String) application.getAttribute("Foo");
// Place object in request scope
request.setAttribute("Foo", foo);
// Retrieve from request scope
String requestFoo = (String) request.getAttribute("Foo");
%>
....
清单 31 中的例子的第一行是 page 指令,它允许您定义整个页面的属性。请注意 session 属性的使用,它决定了该页面是否要使得会话可用。如果将它设置为 true 却还没 有建立会话,那么新的会话就会自动为您创建。如果将它设置为 false,那么会话范围将在 该 JSP 页面中不可用。(这个属性的面默认设置是 true,因此这里使用它是多余的,只是 出于说明目的。)
清单 32 是使用各种可用范围来存储和检索数据的 servlet 的一个例子。
清单 32. servlet 中的状态管理
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
performTask(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
performTask(request, response);
}
/**
* Handles all HTTP GET and POST requests
*
* @param request Object that encapsulates the request to the servlet
* @param response Object that encapsulates the response from the servlet
*/
public void performTask(
javax.servlet.http.HttpServletRequest req,
javax.servlet.http.HttpServletResponse res)
throws ServletException, IOException {
try {
// This is how you create a session if is has not been created yet
// Note that this will return the existing session if you''ve
// already created it
HttpSession session = req.getSession();
//This is how the application context is retrieved in a servlet
ServletContext application = getServletContext();
String foo = "I am a Foo";
// Place object in session scope
session.setAttribute("Foo", foo);
// Retrieve from session scope
String sessionFoo = (String) session.getAttribute("Foo");
|