Session其實就是一個Map
設置tomcat維護的session的個數:
同時還要設置一個類,可以將一個類添加到sesson中去。
第一步:必須要是配置的方式發佈項目
第二步:配置session的保存目錄
<ContextdocBase="D:\\programfiles\\eclipse\\wk01\\05123\\WebContent">
<ManagerclassName="org.apache.catalina.session.PersistentManager"
saveOnRestart="true">
<StoreclassName="org.apache.catalina.session.FileStore"
directory="e:/a">[微軟用戶1] 指定保存目錄,
</Store>
</Manager>
</Context>
第三步:配置一個bean實現接口
public class Person implements HttpSessionActivationListener, Serializable{[微軟用戶1]
private String name;
public Person() {
}
public Person(String nm) {
this.name = nm;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sessionWillPassivate(HttpSessionEventse) {
System.err.println("這個類與Session一塊保存到文件中了:" + this.getName());
}
public void sessionDidActivate(HttpSessionEventse) {
System.err.println("這個類與Session一塊活了:" + this.getName());
}
}
第四步:顯示頁面
<body>
05123...<br/>
<%=session.getId()%>
<hr/>
<%
if(session.getAttribute("pp")==null){
Random r = new Random();
int a = r.nextInt(2000);
Person p = new Person("Jack"+a);
session.setAttribute("pp",p);
}
Cookiec = new Cookie("JSESSIONID",session.getId()); //關了瀏覽器也能找回來,保存Cookie關閉了tomcat也能再啓動tomcat後找回session。
c.setPath("/");
c.setMaxAge(60*60);
response.addCookie(c);
%>
<hr/>
${pp.name}
</body>