首页(显示用户上次访问的时间)
response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); out.write("您上次访问时间是:"); //1.获取用户上次访问的时间,显示 Cookie cookies[] = request.getCookies(); for(int i=0;cookies!=null && i<cookies.length;i++){ Cookie cookie = cookies[i]; if(cookie.getName().equals("lastAccessTime")){ long time = Long.parseLong(cookie.getValue()); Date date = new Date(time); out.write(DateFormat.getDateInstance(DateFormat.FULL).format(date)); } } //2.把本次的时间以cookie的形式回写给客户机 (lastAccessTime) Cookie cookie = new Cookie("lastAccessTime",System.currentTimeMillis()+""); response.addCookie(cookie);
public class CookieDemo1 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); //1.显示网站所有商品 out.print("本网站有如下书籍:<br/>"); Map<String,Book> map = DB.getMap(); for(Map.Entry<String, Book> entry : map.entrySet()){ Book book = entry.getValue(); out.print("<a href='/com/servlet/CookieDemo2?id="+book.getId()+"' target='_blank'>"+book.getName()+"</a><br/>"); } out.print("您曾经看过如下商品:<br/>"); //2.显示用户曾经浏览过的商品 // bookHistory Cookie cookie = null; Cookie cookies[] = request.getCookies(); for(int i=0;cookies!=null && i<cookies.length;i++){ if(cookies[i].getName().equals("bookHistory")){ cookie = cookies[i]; } } if(cookie!=null){ //找到了bookHistory这个cookie String bookHistory = cookie.getValue(); //4_6_1 String ids[] = bookHistory.split("\\_"); for(String id: ids){ Book book = (Book) DB.getMap().get(id); out.print(book.getName() + "<br/>"); } } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } class DB{ private static Map<String,Book> map = new HashMap<String, Book>(); static{ map.put("1", new Book("1","图书1","张三")); map.put("2", new Book("2","图书2","李四")); map.put("3", new Book("3","图书3","王五")); map.put("4", new Book("4","图书4","赵六")); map.put("5", new Book("5","图书5","韩七")); } public static Map<String, Book> getMap(){ return map; } } class Book{ private String id; private String name; private String author; public Book() { super(); // TODO Auto-generated constructor stub } public Book(String id, String name, String author) { super(); this.id = id; this.name = name; this.author = author; } 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 class CookieDemo3 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
//1.根据用户带过来的id值,显示相应商品的信息
out.print("您想看的书的详细信息为:<br/>");
String id = request.getParameter("id");
Book book = (Book) DB.getMap().get(id);
out.print(book.getId() + "<br/>");
out.print(book.getName() + "<br/>");
out.print(book.getAuthor() + "<br/>");
//2.以cookie的形式回写该商品的id号给浏览器
String bookHistory = makeCookie(book.getId(),request);
Cookie cookie = new Cookie("bookHistory",bookHistory);
cookie.setMaxAge(10000);
response.addCookie(cookie);
}
//根据用户原来看过的书,以及现在看的书的id,构建新的cookie值
private String makeCookie(String id, HttpServletRequest request) {
//bookHistory=null 3 bookHistory=3
//bookHistory=2_1_5 3 bookHistory=3_2_1
//bookHistory=2 3 bookHistory=3_2
//bookHistory=2_3 3 bookHistory=3_2
//1.得到用户曾经看过的书
String bookHistory = null;
Cookie cookies[] = request.getCookies();
for(int i=0;cookies!=null && i<cookies.length;i++){
if(cookies[i].getName().equals("bookHistory")){
bookHistory = cookies[i].getValue();
}
}
if(bookHistory==null){
bookHistory = id;
return bookHistory;
}
//bookHistory=1_2_5 代表用户曾经看一些书,接着程序要得到用户曾经看过什么书
String ids[] = bookHistory.split("_");
//为了检测数组中是否包含当前id,我们应该把数据转成集合,并且还要转成链表结构的集合
LinkedList<String> idList = new LinkedList(Arrays.asList(ids));
/*if(idList.contains(id)){
//bookHistory=2_3 3 bookHistory=3_2
idList.remove(id);
idList.addFirst(id);
}else{
//bookHistory=2_1_5 3 bookHistory=3_2_1
if(idList.size()>=3){
idList.removeLast();
idList.addFirst(id);
}else{
//bookHistory=2 3 bookHistory=3_2
idList.addFirst(id);
}
}*/
if(idList.contains(id)){
idList.remove(id);
}else{
if(idList.size()>=3){
idList.removeLast();
}
}
idList.addFirst(id);
StringBuffer sb = new StringBuffer();
for(String lid: idList){ //1_2_3_
sb.append(lid + "_");
}
return sb.deleteCharAt(sb.length()-1).toString();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
public static String md5(String plainText) { try { MessageDigest md = MessageDigest.getInstance("MD5"); md.update(plainText.getBytes()); byte b[] = md.digest(); int i; StringBuffer buf = new StringBuffer(""); for (int offset = 0; offset < b.length; offset++) { i = b[offset]; if (i < 0) i += 256; if (i < 16) buf.append("0"); buf.append(Integer.toHexString(i)); } System.out.println("result: " + buf.toString());// 32位的加密 return buf.toString(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
class TokenProcessor{ //1. 把构造方法私有 //2. 自己产生一个类的对象 //3. 定义一个方法返回上面产生的对象 private TokenProcessor(){}; public static final TokenProcessor instance = new TokenProcessor(); public static TokenProcessor getInstance(){ return instance; } public String generateToken(){ //3843849384 9849238402840243802 983434 String token = System.currentTimeMillis() + "" + new Random().nextInt(99999999); //数据指纹 数据摘要 md5 try { MessageDigest md = MessageDigest.getInstance("md5"); byte md5[] = md.digest(token.getBytes()); //128位 16【12,23,34,544543543543,】 //base64编码 SABDSSDSD BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(md5); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } }
<form action="/com/servlet/FormSubmitServlet" method="post" onsubmit="return dosubmit()"> 用户名:<input type="text" name="username"><br/> <input id="submit" type="submit" value="提交"> </form>
function dosubmit(){ document.getElementById("submit").disabled = 'disabled'; return true; }
response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); String token = TokenProcessor.getInstance().generateToken(); request.getSession().setAttribute("token", token); out.print("<form action='/com/servlet/FormSubmitServlet' method='post'>"); out.print("<input type='hidden' name='token' value='"+token+"'>"); out.print("<input type='text' name='username'>"); out.print("<input type='submit' value='提交'>"); out.print("</form>");
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { boolean b = isToken(request); if(!b){ //用户带过来的令牌无效,阻止提交 System.out.println("你是重复提交!!"); return; } //用户带过来的令牌有效,处理提交 request.getSession().removeAttribute("token"); String username = request.getParameter("username"); //把用户提交的数据保存到数据库中 System.out.println("处理提交请求,把" + username + "保存到数库中!!"); } //判断用户带过来的令牌是否有效 private synchronized boolean isToken(HttpServletRequest request) { String client_token = request.getParameter("token"); if(client_token==null){ return false; } String server_token = (String) request.getSession().getAttribute("token"); if(server_token==null){ return false; } if(!client_token.equals(server_token)){ return false; } return true; }