import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class Session extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(true);//从request对象中取出当前的session对象
//打印当前的Session的具体属性信息
Date created = new Date(session.getCreationTime());//取出session的创建时间
Date accessed = new Date(session.getLastAccessedTime());//取出上次被访问的时间
out.println("Session的ID为: "+session.getId()+"<br>");
out.println("Session的创建时间为: "+ created+"<br>");
out.println("Session的上次访问时间为: "+accessed+"<br>");
//在这里可以设置一个Session
session.setAttribute("msg", "Hello");
//打印Session的具体内容
Enumeration e = session.getAttributeNames();//取出Session的所有属性
out.println("Session的内容如下:");
while(e.hasMoreElements()){
String name=(String)e.nextElement();
String value= session.getAttribute(name).toString();
out.println(name+"="+value+"<br>");
}
}
}
Servlet 中Session操作,布布扣,bubuko.com
原文:http://07252717.blog.51cto.com/4975763/1390900