在程序里怎么保存用户的数据?
数据存在客户端:cookie
可以用购物车的功能类比。
cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器。当用户再去访问服务器中的web资源时,就会带着各自的数据去。这样web资源处理的就是用户各自的数据了。
下面写一个简单的例子,使用cookie显示上一次的访问时间:
// 显示上一次的访问时间
private void showLastAccessTime(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.print("您上次访问的时间是:");
//获得用户的时间cookie
Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if(cookies[i].getName().equals("lastAccessTime")){
long cookieValue = Long.parseLong(cookies[i].getValue());
SimpleDateFormat format = new SimpleDateFormat("hh:mm:ss");
Date date = new Date(cookieValue);
out.print(format.format(date));
}
}
//给用户返回最新的访问时间
Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
cookie.setMaxAge(1*30*24*3600);
cookie.setPath("/cookies");
response.addCookie(cookie);
}
Cookie细节:
- Cookie是map
- web站点可以发送多个cookie,浏览器可存储多个cookie
- 浏览器一般可存放300个cookie,每个站点最多存放20个。每个cookie的大小限制为4kb。
- 如果创建一个cookie发送给浏览器,默认情况是一个会话级别的cookie,用户退出浏览器后即被删除。若希望将浏览器存储到硬盘上,需要设置maxAge,并给出一个以秒为单位的时间。设为0,则是删除该cookie。
- 注意,删除cookie时path必须一致,否则不会删除。
删除cookie:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+"");
cookie.setMaxAge(0);
cookie.setPath("/cookies");
response.addCookie(cookie);
response.sendRedirect("/cookies");
}
下面是一个使用cookie完成购物车的实例:
首页
/**
* Created by yun on 2017/5/6.
* 代表购物车网站首页
*/
public class CookieDemo1 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
//输出网站所有商品
out.write("本网站有如下商品:<br/>");
Map<String, Book> map = DB.getAll();
for (Map.Entry<String, Book> entry : map.entrySet()) {
Book book = entry.getValue();
out.print("<a href='/CookieDemo2?id=" + book.getId() + "' target='_blank'>" + book.getName() + "</a><br/>");
}
//显示用户曾经看到过的商品
out.write("<br/>"+"您曾经看过如下商品有如下商品:<br/>");
Cookie[] cookies = request.getCookies();
for (int i = 0; cookies != null && i < cookies.length; i++) {
if(cookies[i].getName().equals("bookHistory")){
String[] ids = cookies[i].getValue().split("a"); //转义,是为了防止,和正则表达式中的定义冲突
for(String id:ids){
Book book = (Book) DB.getAll().get(id);
out.print(book.getName()+"</br>");
}
}
}
}
}
class DB {
private static LinkedHashMap<String,Book> map = new LinkedHashMap(); //链表map,方便按序列输出
static {
map.put("1", new Book("1", "heinika的编程之路", "陈利津", "一场有趣的旅程!"));
map.put("2", new Book("2", "javaweb开发", "张孝祥", "好书"));
map.put("3", new Book("3", "全栈工程师之路", "Terry", "全栈!!全栈!!"));
map.put("4", new Book("4", "shell大全", "陈利津", "一场有趣的旅程!"));
map.put("5", new Book("5", "heinika的成神之路", "陈利津", "一场有趣的旅程!"));
}
public static Map<String,Book> getAll() {
return map;
}
}
class Book {
private String id;
private String name;
private String author;
private String description;
public Book() {
}
public Book(String id, String name, String author, String description) {
this.id = id;
this.name = name;
this.author = author;
this.description = description;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
详情页
/**
* Created by yun on 2017/5/6.
* 物品详情页
*/
public class CookieDemo2 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//根据用户带货来的id,显示商品的详细信息
String id = request.getParameter("id");
Map<String, Book> map = DB.getAll();
Book book = map.get(id);
PrintWriter out = response.getWriter();
out.print(book.getId() + "<br/>");
out.print(book.getName() + "<br/>");
out.print(book.getAuthor() + "<br/>");
out.print(book.getDescription() + "<br/>");
//构建cookie,写回给浏览器
String cookieValue = buildCookie(id, request);
Cookie cookie = new Cookie("bookHistory", cookieValue);
cookie.setMaxAge(1 * 30 * 24 * 3600);
cookie.setPath("/");
response.addCookie(cookie);
out.print("<a href='/CookieDemo1'>返回首页</a>");
}
private String buildCookie(String id, HttpServletRequest request) {
//bookHistory=null 1 1
//bookHistory=2,1,5 1 1,2,5
//bookhistory=2,5,4 1 1,2,5
//bookHistory=2,5 1 1,2,5
Cookie[] cookies = request.getCookies();
String bookHistory = null;
for (int i = 0; cookies != null && i < cookies.length; i++) {
if (cookies[i].getName().equals("bookHistory")) {
bookHistory = cookies[i].getValue();
}
}
if (bookHistory == null) {
return id;
}
String[] ids = bookHistory.split("a");
LinkedList<String> idList = new LinkedList(Arrays.asList(ids)); //为增删改查提高性能
if (idList.contains(id)) {
idList.remove(id);
} else {
if (idList.size() == 3) {
idList.removeLast();
}
}
idList.addFirst(id);
StringBuffer sb = new StringBuffer();
for (String bid : idList) {
sb.append(bid + "a");
}
return sb.deleteCharAt(sb.length() - 1).toString();
}
}
网友评论