uot;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";
session.setAttribute("Foo", 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 request scope
request.setAttribute("Foo", foo);
// Retrieve from request scope
String requestFoo = (String) request.getAttribute("Foo");
...
} catch (Throwable t) {
// All errors go to error page
throw new ServletException(t.g
|