Friday, February 10, 2012

java - Sessions

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

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 && dateName.length() > 0) {
            String dataValue = request.getParameter("dataValue");
            session.putValue(dataName, dataValue);
        }

        // print session contents

        String[] valueNames = session.getValueNames();
        if (valueNames != null && valueNames.length > 0) {
            for (int i = 0; i < valueNames.length; i++) {
                String name = valueNames[i];
                String value = session.getValue(name).toString();
                out.println(name + " = " + value);
            }
        }
    }
}

No comments: