Назад | Начало урока | Вперед
Содержание

Глава 2


Source Code for Session Example

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SessionExample extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException
    {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        
        HttpSession session = request.getSession(true);

        // print session info

        Date created = new Date(session.getCreationTime());
        Date accessed = new Date(session.getLastAccessedTime());
        out.println("ID " + session.getId());
        out.println("Created: " + created);
        out.println("Last Accessed: " + accessed);

        // set session info if needed

        String dataName = request.getParameter("dataName");
        if (dataName != null && dataName.length() > 0) {
            String dataValue = request.getParameter("dataValue");
            session.setAttribute(dataName, dataValue);
        }

        // print session contents

        Enumeration e = session.getAttributeNames();
        while (e.hasMoreElements()) {
            String name = (String)e.nextElement();
            String value = session.getAttribute(name).toString();
            out.println(name + " = " + value);
        }
    }
}

Так выглядит страница sessions.html в браузере. Эта страница демонстрирует код сервлета. Запустить сервлет можно следующей командой: http://localhost:8080/servlets-examples/servlet/SessionExample Ниже на рисунке показана страница, которая образуется в результате работы этого сервлета.

Подсказка

Вот html-код этой страницы (то, что фактически сервер после обработки сервлета послал браузеру):


<html>
<body bgcolor="white">
<head>
<title>Sessions Example</title>
</head>
<body>
<a href="../sessions.html">
<img src="../images/code.gif" height=24 width=24 align=right border=0 alt="view code"></a>
<a href="../index.html">
<img src="../images/return.gif" height=24 width=24 align=right border=0 alt="return"></a>
<h3>Sessions Example</h3>
Session ID: B8AFE1A54AC3E3B60198E9D6D2F5941A
<br>
Created:
Sat May 01 13:34:21 MSD 2010<br>
Last Accessed:
Sat May 01 13:34:21 MSD 2010
<P>
The following data is in your session:<br>
<P>
<form action="SessionExample;jsessionid=B8AFE1A54AC3E3B60198E9D6D2F5941A" method=POST>
Name of Session Attribute:
<input type=text size=20 name=dataname>
<br>
Value of Session Attribute:
<input type=text size=20 name=datavalue>
<br>
<input type=submit>
</form>
<P>GET based form:<br>
<form action="SessionExample;jsessionid=B8AFE1A54AC3E3B60198E9D6D2F5941A" method=GET>
Name of Session Attribute:
<input type=text size=20 name=dataname>
<br>
Value of Session Attribute:
<input type=text size=20 name=datavalue>
<br>
<input type=submit>
</form>
<p><a href="SessionExample;jsessionid=B8AFE1A54AC3E3B60198E9D6D2F5941A?dataname=foo&datavalue=bar" >URL encoded </a>
</body>
</html>
</body>
</html>


Более точно код сервлета выглядит так:


import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

import util.HTMLFilter;

/**
* Example servlet showing request headers
*
* @author James Duncan Davidson <duncan@eng.sun.com>
*/

public class SessionExample extends HttpServlet {

ResourceBundle rb = ResourceBundle.getBundle("LocalStrings");
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<body bgcolor=\"white\">");
out.println("<head>");

String title = rb.getString("sessions.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body>");

// img stuff not req'd for source code html showing
// relative links everywhere!

// XXX
// making these absolute till we work out the
// addition of a PathInfo issue

out.println("<a href=\"../sessions.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");

out.println("<h3>" + title + "</h3>");

HttpSession session = request.getSession(true);
out.println(rb.getString("sessions.id") + " " + session.getId());
out.println("<br>");
out.println(rb.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "<br>");
out.println(rb.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()));

String dataName = request.getParameter("dataname");
String dataValue = request.getParameter("datavalue");
if (dataName != null && dataValue != null) {

session.setAttribute(dataName, dataValue);
}
out.println("<P>");
out.println(rb.getString("sessions.data") + "<br>");
Enumeration names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
String value = session.getAttribute(name).toString();
out.println(HTMLFilter.filter(name) + " = "
+ HTMLFilter.filter(value) + "<br>");
}
out.println("<P>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=POST>");
out.println(rb.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(rb.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");

out.println("<P>GET based form:<br>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=GET>");
out.println(rb.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(rb.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");

out.print("<p><a href=\"");
out.print(response.encodeURL("SessionExample?dataname=foo&datavalue=bar"));
out.println("\" >URL encoded </a>");

out.println("</body>");
out.println("</html>");

out.println("</body>");
out.println("</html>");

}


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {

doGet(request, response);
}


}



Назад | Начало урока | Вверх | Вперед
Содержание

Hosted by uCoz