Session方法
invalidate() 就是从session对象池中删除session
isNew() boolean; true刚刚创建的Session;false 不是新建的Session
session本地持久化
只要正常途径关闭tomcat服务器 就会把session内容存储到本地
注意,如果你在session存放对象,那这个对象想存储在磁盘上必须实现接口 java.io.Serializable
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/hello")
public class B extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Test test = new Test();
test.setName("小明");
session.setAttribute("Test", test);//通过对象的方式存储
RequestDispatcher requestDispatcher = request.getRequestDispatcher("a");
requestDispatcher.forward(request, response);
}
}
----
package com.sun.tomcat;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpSession;
@WebServlet("/a")
public class A extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
Test test = (Test) session.getAttribute("Test"); //将对象进行强制类型转化
System.out.println(test.getName());//用转换后的对象进行取值
}
}
----
package com.sun.tomcat;
import java.io.Serializable;
public class Test implements Serializable {//实现序列化技术
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Test{" +
"name='" + name + '\'' +
'}';
}
}