您的位置:首页 > 其它

servlet会话技术:Session

2016-04-19 20:01 645 查看
问题的引出

1.在网上购物时,张三和李四购买的商品不一样,他们的购物车中显示的商品也不一样,这是怎么实现的呢?

2.不同的用户登录网站后,不管该用户浏览该网站的那个页面,都可以显示登录人的名字,同时可以随时去查看购物车中的商品。

Session

Session是服务端技术,利用这个技术,服务器在运行时可以为每一个用户创建一个其独享的session对象,由于Session为用户独享,所以用户在访问服务器的web资源时,可以把各自的数据放在各自的sessio中,当用户再去访问服务器中华的其他web资源时,其他web资源再从用户各自的session中取出数据为用户服务。

当用户打开浏览器,访问某个网站操作session时,服务器会在服务器的内存为该浏览器分配一个session对象,该session对象被这个浏览器独占,这个session对象也可以看做是一个容器,session对象默认存在的时间是30min,当然你也可以修改。
对session的理解



public class User {

private String name;
private int age;

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}


Servlet1.java

public class Servlet1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
//获取session
/**
* getSession():returns the current session associated with this request,
* or if the request does not has a session,create one.
* 即第一次访问会自动创建
*/
HttpSession session = request.getSession();
//给该session放入属性
session.setAttribute("uname", "zhangsan");
session.setAttribute("uage", "30");
User user = new User();
user.setName("lisi");
user.setAge(20);
session.setAttribute("user",user);
//session的生命周期,默认是30min

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);

}
}


Servlet2.java

public class Servlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
///获取session
HttpSession session = request.getSession();
//获取session中的属性
String uname = (String) session.getAttribute("uname");

User user = (User) session.getAttribute("user");
out.println("user name = " + user.getName() + " age = " + user.getAge());
if (uname == null) {
out.println("session中没有uname");
} else {
out.println("uname = " + uname);
}

}

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


Session小结

--Session是存在服务器的内存中的。

--一个用户浏览器,独享一个session对象。

--Session中的属性的默认生命周期是30min,可以通过修改web.xml来修改。

这样修改
一个地方是:tomcat/conf/web.xml
<session-config>
<session-timeout>30</session-timeout>
</session-config>
对所有的web应用生效。


第二个地方是:在单个web应用下的web.xml文件下添加或修改ession-config

<session-config>
<session-timeout>10</session-timeout>
</session-config>
只对本web应用生效


如果两个配置文件冲突,就以单个web应用的配置为准。

第三种方法是:session.setMaxInactiveInterval(600); //以秒为单位
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: