会话:用户打开一个浏览器,点击多个超链接,访问服务器多个web资源,然后关闭浏览器,整个过程称之为一个会话。
会话过程中要解决的一些问题:
javax.servlet.http.Cookie类用于创建一个Cookie,response接口也定义了一个addCookie方法,它用于在其响应头中增加一个相应的Set-Cookie
头字段。同样在request接口中也定义了一个getCookies方法,它用于获取客户端提交的Cookie。
Cookie类的方法有(最好查看其API):
一个Cookie是一个键值对。
通过Cookie可以保存用户的信息,示例:保存用户的上次的访问的时间并显示出来(通过request获取请求头中带有的Cookie,再通过response的响应头将Cookie值返回给浏览器):
package com.hsx.cookie;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.hsx.constant.MyConstant;
/**
* 保存用户的上次的访问的时间并显示出来
* @author hsx
*
*/
public class CookieDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("您上次获取的时间是:");
// 从客户端的请求获取指定的cookie
Cookie[] cookies = request.getCookies();
System.out.println(cookies); // 第一次访问时cookie的值可能为null
for (int i = 0; cookies != null && i < cookies.length; i++) {
Cookie cookie = cookies[i];
System.out.println(cookie.getName());
if (MyConstant.LAST_ACCESS_TIME.equals(cookie.getName())) {
long value = Long.parseLong(cookie.getValue());
out.println(new Date(value).toLocaleString());
}
}
// 把当前的时间写给客户端
Cookie cookie1 = new Cookie(MyConstant.LAST_ACCESS_TIME, System.currentTimeMillis() + "");
cookie1.setPath(request.getContextPath());
cookie1.setMaxAge(10 * 24 * 60 * 60); //存活的时间,默认浏览器的进程
response.addCookie(cookie1);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
}
}
--------------------------------------------------------
/**
* 常量接口设计模式(这里只是设置了Cookie的name值)
* @author hsx
*
*/
public interface MyConstant {
String LAST_ACCESS_TIME = "lastAccessTime";
}
cookie.setPath(request.getContextPath())
这条语句设置的Cookie是本身这个应用的。由此可得:request.getContextPath()
是获取该应用[项目]的路径。cookie.setPath("http://localhost:8080/")
或者cookie.setPath("/")
这条语句设置的Cookie能被”http://localhost:8080/“下的所有的应用访问。cookie.setPath("http://localhost:8080/ServletCS/servlet/")
这条语句设置的Cookie能只能被该Servlet访问;即某个Servlet的url-pattern
配置是servlet2,则该servlet2都不能访问其Cookie。//--- 删除指定的cookie cookie.setMaxAge(0);---//
// 先获取指定的Cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (MyConstant.LAST_ACCESS_TIME.equals(cookie.getName())) {
//设置其maxAge(0):必须有path一致
cookie.setMaxAge(0);
cookie.setPath(request.getContextPath());
//写个客户端
response.addCookie(cookie);
}
}
/*---------------CookieDemo2---------------------*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = "";
String rem = "";
// 从Cookie中获取用户名
Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
Cookie cookie = cookies[i];
if (MyConstant.USER_NAEM.equals(cookie.getName())) {
name = cookie.getValue();
rem = "checked='checked'";
}
}
// 显示出登陆页面
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("");
out.println("用户登陆 ");
out.println("");
out.println(");
out.println("");
out.println("");
out.println("用户名 ");
out.println(" ");
out.println(" ");
out.println("");
out.println("密码 ");
out.println(" ");
out.println(" ");
out.println("");
out.println(" + rem + " />记住用户名 ");
out.println(" ");
out.println("");
out.println(" ");
out.println(" ");
out.println("
");
out.println("");
out.println("");
out.println("");
}
/*------------------CookieDemo3--------------------------*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Cookie cookie = null;
String remember = request.getParameter("remember");
System.out.println(remember);
if (remember != null) {
cookie = new Cookie(MyConstant.USER_NAEM, request.getParameter("username"));
cookie.setPath(request.getContextPath());
cookie.setMaxAge(Integer.MAX_VALUE); //永久保存
response.addCookie(cookie);
}
out.println(cookie.getName() + "
");
out.println(cookie.getValue());
}
/*--------------------常量接口设计模式------------------------*/
public interface MyConstant {
String USER_NAEM = "username";
}
在Web开发中,服务器可以为每一个用户浏览器创建一个会话对象(Session对象),注意:一个浏览器独占一个Session对象(默认情况下)。因此,在需要保存用户数据时,服务器程序可以把用户数据写到用户浏览器独占的Session中,当用户使用浏览器访问其他程序时,其他程序可以从用户的Session中取出该用户的数据,为用户服务。
<session-config>
<session-timeout>1ssession-timeout>
session-config>
注意:
request.getSession(); // 要是没有Session对象,就立马创建Session对象
request.getSession(false); // 设置了false,要是没有Session对象,不会创建session对象。
String url1 = request.getContextPath() + "/PayServlet";
url1 = response.encodeURL(url1);
out.println("
结账");
/*-----IndesServlet-----显示所有的商品,提供购买链接 -- 放入购物车*/
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("");
out.println("商品 ");
out.println("");
// 显示所有的商品
List productList = Product.getAllProduct();
out.println("本站有以下好商品:
");
for (String product : productList) {
out.println(product);
String url = request.getContextPath() + "/BuyServlet?name=" + product;
url = response.encodeURL(url); //禁用浏览器的Cookie时使用的
out.println("购买
");
}
// 转向结账
String url1 = request.getContextPath() + "/PayServlet";
url1 = response.encodeURL(url1);
out.println("
结账");
out.println("");
out.println("");
out.close();
/*-----BuyServlet-----购买的Servlet,将商品加入购物车*/
String productName = request.getParameter("name");
productName = new String(productName.getBytes("ISO-8859-1"), "UTF-8");
// 查看Session中是否有购物车
HttpSession session = request.getSession();
Object object = session.getAttribute(MyConstant.MY_CART);
if (null != object) {// 有:取出来,放商品
List cartList = (List) object;
cartList.add(productName);
}
else {// 没有,先构件购物车
List cartList = new ArrayList();
cartList.add(productName);
session.setAttribute(MyConstant.MY_CART, cartList);
}
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("您已经购买了:" + productName);
String url = request.getContextPath() +"/IndesServlet";
url = response.encodeURL(url);
out.println("
继续购买");
/*-----PayServlet-----显示购物车中的商品*/
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false); //只是取
if (session == null) {
out.println("您还未购物");
}
else {
List myCartList = (List) session.getAttribute(MyConstant.MY_CART);
out.println("您购买了以下商品:
");
for (Object object : myCartList) {
out.println(object + "
");
}
}
out.close();