java session操作

不設限發表於2011-12-14
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.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 DemoSessionServlet extends HttpServlet {
private static final long serialVersionUID = 3144436730239445373L;


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


@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Integer counter = (Integer) session.getAttribute("counter");
if (counter == null) {
counter = new Integer(1);
} else {
counter = new Integer(counter.intValue() + 1);
}
session.setAttribute("counter", counter);
session.setMaxInactiveInterval(3600);


response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>session demo servlet</title></head>");
out.println("<body>");
out.println("<h1>使用session的演示</h1>");
out.println("你已經訪問了" + counter + "次.<br><br>");
if (session.isNew()) {
out.println("這是您第一次訪問本站<br><br>");
} else {
out.println("歡迎再次回來.<br><br>");
}
out.println("jsessionid: " + session.getId() + "<br><br>");
out.println("LastAccessedTime: " + session.getLastAccessedTime()
+ "<br>");
out.println("格式轉換以後的LastAccessedTime: "
+ new Date(session.getLastAccessedTime()) + "<br><br>");
out.println("CreationTime: " + session.getCreationTime() + "<br>");
out.println("格式轉換以後的CreationTime: "
+ new Date(session.getCreationTime()) + "<br><br>");
out.println("MaxInactiveInterval: " + session.getMaxInactiveInterval()
+ "秒<br>");
out.println("<br>使用Session物件的getAttributeNames<br>");
Enumeration<String> enumer = session.getAttributeNames();
String name = null;
while (enumer.hasMoreElements()) {
name = (String) enumer.nextElement();
out.println("Session name:" + name + "<br>");
out.println("Session value:" + session.getAttribute(name) + "<br>");
}
//移除指定的元素
session.removeAttribute("counter");
//讓session失效
session.invalidate();
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
}

相關文章