标签:
一、Cookie详解
public void doGet(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); out.write( "上次访问的时间是:" ); //得到指定的cookie,该cookie中记录了上次访问的时间 Cookie[] cs = request.getCookies(); for ( int i=0;cs!= null &&i<cs. length ;i++){ Cookie c = cs[i]; if ( "lastTime" .equals(c.getName())){ String value = c.getValue(); //把cookie里面字符串转成long,再由Date转成可读格式 long time = Long. parseLong (value); String ti = new Date(time). toLocaleString() ; out.write(ti); } } //清除cookie out.write( "<a href=‘/my_exericse_day05/servlet/MyCookieDemo2‘>清除cookie</a>" ); //把当前时间写入到cookie里面 Cookie cookie = new Cookie( "lastTime" , System. currentTimeMillis ()+ "" ); //设置cookie的存货时间,单位是秒.如果是Long单位多半是毫秒 cookie.setMaxAge(1*30*24*60*60); //设置路径为当前应用的名称,意味着当前应用的任何资源都可以得到该cookie. cookie.setPath(request.getContextPath()); response.addCookie(cookie); }
删除指定的Cookie
//删除指定的cookie public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); Cookie c = new Cookie( "lastAccesTime" , "" ); //和上面的一样的 c.setMaxAge(0); c.setPath(request.getContextPath()); response.addCookie(c); out.write( "删除成功!" ); }
提供选项让用户设置是否记录登录名
//提供登陆界面 //显示记住的用户名 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); //显示记住的用户名 String username = "" ; String checked = "" ; //找到指定的cookie Cookie cs[] = request.getCookies(); for ( int i=0;cs!= null &&i<cs. length ;i++){ if (CookieStatics. LOGIN_USERNAME .equals(cs[i].getName())){ //找到了 String value = cs[i].getValue(); username = value; checked = "checked=‘checked‘" ; break ; //不希望程序继续往下运行 } } //提供登陆界面 out.write( "<form action=‘" +request.getContextPath()+ "/servlet/LoginServletDemo2‘ method=‘post‘>" ); out.write( "用户名:<input type=‘text‘ name=‘username‘ value=‘" +username+ "‘/><br/>" ); out.write( "密码:<input type=‘password‘ name=‘password‘/><br/>" ); out.write( "记住用户名:<input type=‘checkbox‘ name=‘remember‘ " +checked+ " /><br/>" ); out.write( "<input type=‘submit‘ value=‘登陆‘/>" ); out.write( "</form>" ); }
//验证用户名或密码 //根据用户是否需要记住用户名来处理cookie //是:添加cookie //否:删除cookie public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); //验证用户名或密码 String username = request.getParameter( "username" ); String remember = request.getParameter( "remember" ); //根据用户是否需要记住用户名来处理cookie //用一个借口,来定义一个常量。直接引用,不容易出错 Cookie c = new Cookie(CookieStatics. LOGIN_USERNAME , username); c.setPath(request.getContextPath()); if (remember== null ){ //否:删除cookie c.setMaxAge(0); } else { //是:添加cookie的失效时间为最大 c.setMaxAge(Integer. MAX_VALUE ); } response.addCookie(c); out.write( "登陆成功!" ); }
记录用户的浏览记录
//显示所有的书籍,并提供查看详细的链接 //显示用户最近的浏览记录:保留3 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); //显示所有的书籍,并提供查看详细的链接 out.write( "本站有以下好书,欢迎选购:<br/>" ); Map<String, Book> books = BookDB. findAllBooks (); for (Map.Entry<String, Book> me:books.entrySet()){ out.write(me.getValue().getName()+ " <a href=‘" +request.getContextPath()+ "/servlet/ShowBookDetailServlet?id=" +me.getValue().getId()+ "‘>详情</a><br/>" ); } //显示用户最近的浏览记录:保留3 bookHistory=3-2-1 out.write( "<hr/>您最近的浏览记录:<br/>" ); Cookie cs[] = request.getCookies(); for ( int i=0;cs!= null &&i<cs. length ;i++){ Cookie c = cs[i]; if ( "bookHistory" .equals(c.getName())){ String bookIds = c.getValue(); //3-2-1 String ids[] = bookIds.split( "\\-" ); for (String id:ids){ Book book = BookDB. findBookById (id); out.write(book.getName()+ "<br/>" ); } break ; } } }
//显示书籍的详细内容 //向客户端写cookie记录浏览历史 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); //显示书籍的详细内容 String bookId = request.getParameter( "id" ); out.write( "详情:" +BookDB. findBookById (bookId).toString()); out.write( "<br/><a href=‘" +request.getContextPath()+ "/servlet/ShowAllBooksServlet‘>继续购物</a>" ); //向客户端写cookie记录浏览历史 String ids = makeIds(request,bookId); //用-分隔 Cookie c = new Cookie( "bookHistory" , ids); c.setPath(request.getContextPath()); c.setMaxAge(Integer. MAX_VALUE ); response.addCookie(c); } //组织要写回的书的id // 当前情况 新看的书 应写回的id // cookie一个都没有 1 1 // cookie不为null,但没有bookHistory 1 1 // bookHistory=1 2 2-1 // bookHistory=2-1 1 1-2 // bookHistory=2-1 3 3-2-1 // bookHistory=2-1-3 3 3-2-1 // bookHistory=2-1-3 4 4-2-1 private String makeIds(HttpServletRequest request, String bookId) { // cookie一个都没有 1 1 Cookie cs[] = request.getCookies(); if (cs== null ||cs. length ==0) return bookId; // cookie不为null,但没有bookHistory 1 1 Cookie bookHistoryCookie = null ; for (Cookie c:cs){ if ( "bookHistory" .equals(c.getName())){ bookHistoryCookie = c; break ; } } if (bookHistoryCookie== null ){ return bookId; } // bookHistory=1 2 2-1 // bookHistory=2-1 1 1-2 // bookHistory=2-1 3 3-2-1 String id = bookHistoryCookie.getValue(); // 2-1 LinkedList<String> list = new LinkedList<String>(Arrays. asList (id.split( "\\-" ))); // 2 1 if (list.size()<3){ if (list.contains(bookId)){ list.remove(bookId); } list.addFirst(bookId); } else { // bookHistory=2-1-3 3 3-2-1 // bookHistory=2-1-3 4 4-2-1 if (list.contains(bookId)){ list.remove(bookId); } else { list.removeLast(); } list.addFirst(bookId); } //把list中的id组织成字符串 //3 2 1---->3-2-1 StringBuffer sb = new StringBuffer(); for ( int i=0;i<list.size();i++){ if (i>0) sb.append( "-" ); sb.append(list.get(i)); } return sb.toString(); }
HttpSession的案例:
//显示所有的产品。提供购买和显示已买产品的链接 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); request.getSession(); out.write( "本站有以下好书:<br/>" ); Map<String, Book> books = BookDB. findAllBooks (); for (Map.Entry<String, Book> me:books.entrySet()){ String url = request.getContextPath()+ "/servlet/BuyServlet?id=" +me.getKey(); url = response.encodeURL(url); out.write(me.getValue().getName()+ " <a href=‘" +url+ "‘>购买</a><br/>" ); } String url = request.getContextPath()+ "/servlet/ShowCartServlet" ; url = response.encodeURL(url); out.write( "<hr/><a href=‘" +url+ "‘>显示已购买商品</a>" ); }
//购买 Servlet :把购买的书籍放入购物车(容器)。提供继续购物的链接 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); String id = request.getParameter( "id" ); Book book = BookDB. findBookById (id); //放入购物车:一个客户端只有一个购物车,且不能被替换 HttpSession session = request.getSession(); List<Book> cart = (List<Book>) session.getAttribute( "cart" ) ; if (cart== null ){ cart = new ArrayList<Book>(); session.setAttribute( "cart" , cart); } cart.add(book); String url = request.getContextPath()+ "/servlet/ShowProductServlet" ; url = response.encodeURL(url); out.write(book.getName()+ "已放入您的购物车!<a href=‘" +url+ "‘>继续购物</a>" ); }
//显示购物车中的内容 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); //getSession()等于getSession(true),如果有Session,则返回,如果没有则创建. //getSession(false),如果有Session,则返回,如果没有Session,则返回null HttpSession session = request.getSession( false ); if (session== null ){ out.write( "哥们,你TMD真有才,什么都木有买就看看,SB" ); return ; } //session肯定创建过了:需要进一步显示 out.write( "您购买的商品如下:<br/>" ); List<Book> cart = (List<Book>) session.getAttribute( "cart" ) ; if (cart== null ){ out.write( "您还没有购买任何商品" ); } else for (Book b:cart){ out.write(b.getName()+ "<br/>" ); } String url = request.getContextPath()+ "/servlet/ShowProductServlet" ; url = response.encodeURL(url); out.write( "<a href=‘" +url+ "‘ target=‘_blank‘>继续购物</a>" ); }
< form action = "/day06_00_session/servlet/LoginServlet" method = "post" > 用户名: < input type = "text" name = "username" />< br /> 密码: < input type = "password" name = "password" />< br /> 验证码: < input type = "text" name = "code" size = "4" />< img id = "code" src = "/day06_00_session/servlet/ImageServlet" /> < a href = "javascript:changeNum()" > 看不清 </ a > < br /> < input type = "submit" value = "登陆" /> </ form > < script type = "text/javascript" > function changeNum(){ //alert("haha"); //地址如果相同,浏览器不会发出请求 document.getElementById( "code" ).src= "/day06_00_session/servlet/ImageServlet?" + new Date().getTime(); } </ script >
//用户登陆 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding( "UTF-8" ); response. setContentType ( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); //验证“验证码”是否正确:从session中取出,与用户提交过来的参数进行对比 HttpSession session = request.getSession(); String sCode = (String) session.getAttribute( "code" ); String pCode = request.getParameter( "code" ); if (!pCode.equalsIgnoreCase(sCode)){ response.setHeader( "Refresh" , "2;URL=" +request.getContextPath()+ "/login.html" ); out.write( "验证码有误!2秒后自动转向登陆页面" ); return ; } //验证用户名和密码 User user = new User(); user.setUsername(request.getParameter( "username" )); session.setAttribute( "user" , user); response.setHeader( "Refresh" , "2;URL=" +request.getContextPath()+ "/servlet/IndexServlet" ); out.write( "登陆成功!2秒后转向主页" ); }
//模拟默认主页 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType( "text/html;charset=UTF-8" ); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(); User user = (User)session.getAttribute( "user" ); if ( user == null ){ out.write( "<a href=‘" +request.getContextPath()+ "/login.html‘>登陆</a>" ); } else { out.write( "欢迎您:" +user.getUsername()+ " <a href=‘" +request.getContextPath()+ "/servlet/LogoutServlet‘>注销</a>" ); } out.write( "<hr/>这是主页内容" ); }
//注销 public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session = request.getSession(); session.invalidate(); //立即失效 }
3、防止表单重复提交
MD5加密
public static String md5Encode(String str){ try { //返回实现指定摘要算法的 MessageDigest 对象 MessageDigest md = MessageDigest. getInstance ( "md5" ); //进行MD5编码 byte b[] = md.digest(str.getBytes()); //得到加密后的字节码 //把b字节码转换成字符串 BASE64Encoder base64 = new BASE64Encoder(); return base64.encode(b); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }
标签:
原文地址:http://www.cnblogs.com/lulu638/p/4242409.html