Set Session:
public class SessionDome01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存东西
session.setAttribute("name",new Person("张三",50));
//获取Session中的id
String sessionid = session.getId();
//判断Session是不是新创建
if (session.isNew()) {
resp.getWriter().write("session创建成功,ID:" + sessionid);
} else {
resp.getWriter().write("session已经在服务中存在了,ID:"+sessionid);
}
//Session创建的时候做了什么事情
// Cookie cookie = new Cookie("JSESSIONID",sessionid);
// resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Get Session:
public class SessionDome02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
Person person = (Person) session.getAttribute("name");
PrintWriter writer = resp.getWriter();
writer.write(person.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手动注销Session:
public class SessionDome03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//手动注销Session
HttpSession session = req.getSession();
session.removeAttribute("name");//删除session
session.invalidate();//注销方法
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
封装类:
public class Person {
public Person() {
}
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name=‘" + name + ‘\‘‘ +
", age=" + age +
‘}‘;
}
}
webxml 方式设置session有效时间:
<!--设置session默认失效时间-->
<session-config>
<!--1分钟后session自动消失,以分钟为单位-->
<session-timeout>1</session-timeout>
</session-config>
原文:https://www.cnblogs.com/huhao2000/p/11980781.html