程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> 具體進修Java Cookie技巧(用戶登錄、閱讀、拜訪權限)

具體進修Java Cookie技巧(用戶登錄、閱讀、拜訪權限)

編輯:關於JAVA

具體進修Java Cookie技巧(用戶登錄、閱讀、拜訪權限)。本站提示廣大學習愛好者:(具體進修Java Cookie技巧(用戶登錄、閱讀、拜訪權限))文章只能為提供參考,不一定能成為您想要的結果。以下是具體進修Java Cookie技巧(用戶登錄、閱讀、拜訪權限)正文


本章文章具體講授:
1、Cookie根本用法演示
2、演示Cookie的拜訪權限
3、演示Cookie的刪除
4、應用Cookie顯示用戶前次登錄的時光
5、應用Cookie技巧顯示用戶比來閱讀的若干個圖片
6、測試火狐閱讀器究竟支撐若干個Cookie和一個Cookie最年夜為多年夜

1、Cookie根本用法演示

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 </head>

 <body>
 <h1>演示Cookie技巧</h1>
 <a href="CookieDemo">Cookie根本用法演示</a><br/>

 </body>
</html>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
 <display-name></display-name>
 <servlet>
 <servlet-name>CookieDemo</servlet-name>
 <servlet-class>cn.hncu.servlets.CookieDemo</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>CookieDemo</servlet-name>
 <url-pattern>/CookieDemo</url-pattern>
 </servlet-mapping> 
 <welcome-file-list>
 <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>
</web-app>

CookieDemo.java:

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieDemo extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

 response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();

 //向客戶端寫cookie
 Random r = new Random();
 int n =r.nextInt(100);
 String name = "jack";//cookie的格局:key=value
 Cookie c = new Cookie("name", name+n);
 c.setMaxAge(60*60);//設置過時時光,以秒為單元
 c.setPath( request.getContextPath() );//該途徑是: /項目名
 //Cookie機制中,是經由過程path來掌握權限的。只要<url-pattern>和該path雷同或是它的子途徑的servlet能力夠拜訪該cookie
 //假如把一個cookie的path設為項目根目次,那末該項面前目今的一切servlet都可以或許拜訪它
 response.addCookie(c);

 //這一段演示cookie帶中文
 String str = "我帶中文";
 str = URLEncoder.encode(str, "utf-8");//中文設置編碼!!!urlencode編碼
 Cookie cStr = new Cookie("str", str);
 //假如不設置setMaxAge,則閱讀器一封閉就過時
 cStr.setPath("/");
 response.addCookie(cStr);

 //讀取客戶端發過去的cookie
 Cookie cs[] = request.getCookies();//讀取cookie
 if(cs!=null){//防備一下
  for(Cookie cc:cs){
  String name2 = cc.getName();
  String val = cc.getValue();
  val = URLDecoder.decode(val, "utf-8");//本來是怎樣編碼的,就怎樣解碼! 中文解碼,ascii是原樣的!
  out.print(name2+"="+val+"<br/>");
  }
 }

 out.print("Cook保留勝利!");
 }

}

演示成果:

第一次點擊時!session下次講!tomcat主動生成發給客戶真個!

再次進入時!
name+n–由於前面的n一向在隨機生成,這個點擊老是顯示的是前一個的信息!

2、演示Cookie的拜訪權限

index.jsp:

<a href="servlet/CookieDemo2">演示Cookie的拜訪權限</a><br/>

web.xml:

<servlet>
 <servlet-name>CookieDemo2</servlet-name>
 <servlet-class>cn.hncu.servlets.CookieDemo2</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>CookieDemo2</servlet-name>
 <url-pattern>/servlet/CookieDemo2</url-pattern>
 </servlet-mapping> 

 CookieDemo2.java:

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieDemo2 extends HttpServlet {


 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();

 //向客戶端寫Cookie
 Random r = new Random();
 int n =r.nextInt(100);
 Cookie c = new Cookie("age", ""+n);
 c.setMaxAge(60*60);//過時時光
 c.setPath( request.getContextPath()+"/servlet/CookieDemo2" );//Cookie機制中,是經由過程path來掌握權限的
 //因為CookieDemo的url-pattern是項目根目次/CookieDemo,不是以後cookie所設途徑的子目次,是以沒法拜訪到該cookie

 //留意!!!path紛歧樣,那末cookie是分歧的對象,也就是不會覆誰人名字雷同的cookie!
 response.addCookie(c);

 //讀取從客戶端發來的cookie
 Cookie cs[] = request.getCookies();
 if(cs!=null){
  for(Cookie cc:cs){
  String name = cc.getName();
  String val = cc.getValue();
  out.print("22222--"+name+"="+val+"<br/>");
  }
 }
 out.print("Cookie保留勝利!");

 }
}

演示成果:

先輩入CookieDemo2的頁面,能拜訪到CookieDemo的name-cookie

再進入CookieDemo的頁面,不克不及拜訪到CookieDemo2的age-cookie

3、演示Cookie的刪除

index.jsp:

<a href="servlet/DelCookieDemo"> 演示Cookie的刪除 </a><br/>

web.xml:

<servlet>
 <servlet-name>DelCookieDemo</servlet-name>
 <servlet-class>cn.hncu.servlets.DelCookieDemo</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>DelCookieDemo</servlet-name>
 <url-pattern>/servlet/DelCookieDemo</url-pattern>
 </servlet-mapping>

DelCookieDemo.java:

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DelCookieDemo extends HttpServlet {

 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

 response.setContentType("text/html;charset=utf-8");
 PrintWriter out = response.getWriter();
 Cookie cs[] = request.getCookies();
 if(cs!=null){
  for(Cookie c:cs){
 //要想遍歷到"name"這個cookie,以後servlet必需要有讀的權限,即servlet的url-pattern必需是該cookie所設途徑或許是其所設途徑的子途徑
  //刪除name這個cookie
  if("name".equals(c.getName())){
   c.setPath( request.getContextPath() );//刪除時是經由過程這一句來斷定權限的!這裡必需和本來所設的途徑完整一樣能力刪除,不然不克不及刪除!
   //關於上句,我的小我懂得是:由於假如你這個途徑設置分歧了,其實只是相當與新開了一個cookie,這個新cookie的到期時光是0,name是"name"

   c.setMaxAge(0);//到期時見設為0,等於刪除---此處只是設置刪除標識
   response.addCookie(c);
  }
  }
 }
 }
}

演示成果:

這個時刻,name還存在的。

我們拜訪DelCookieDemo.

再去第一個鏈接看:

name曾經沒有了!

火狐會主動刪除過時的cookie:

4、應用Cookie顯示用戶前次登錄的時光

index.jsp:

<a href="LoginServlet">應用Cookie顯示用戶前次登錄的時光</a>

web.xml:

 <servlet>
 <servlet-name>LoginServlet</servlet-name>
 <servlet-class>cn.hncu.servlets.LoginServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>LoginServlet</servlet-name>
 <url-pattern>/LoginServlet</url-pattern>
 </servlet-mapping>

LoginServlet.java:

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
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;

public class LoginServlet 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("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
 out.println("<HTML>");
 out.println(" <HEAD><TITLE>演示應用Cookie顯示用戶前次登錄的時光</TITLE></HEAD>");
 out.println(" <BODY>");

 //讀取客戶真個cookie
 Cookie cs[] = request.getCookies();
 boolean boo = false;
 if(cs!=null){
  for(Cookie c:cs){
  //遍歷
  if("loginTime".equals(c.getName())){
   String val =c.getValue();
   long dt = Long.parseLong(val);
   Date d = new Date(dt);
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
   out.print("您前次登錄時光是:"+sdf.format(d));
   boo=true;
   break;
  }
  }
 }
 if(boo==false){//表現之前1年沒有拜訪記載!由於上面我們保留的過時時光是一年
  out.print("您比來一年是第一次拜訪。。。");
 }

 //不管是新舊用戶,都邑以比來的時光倆創立一個Cookie,寫到客戶端。本來有了的,就是更新時光
 Date d = new Date();
 Cookie c = new Cookie("loginTime", ""+d.getTime() );
 c.setPath(request.getContextPath());
 c.setMaxAge(60*60*24*30*12);
 response.addCookie(c);

 out.println(" </BODY>");
 out.println("</HTML>");
 out.flush();
 out.close();
 }

}

演示成果:

第一次拜訪;

再次拜訪:

5、應用Cookie技巧顯示用戶比來閱讀的若干個圖片

index.jsp:

<a href="jsps/show.jsp">看美男--應用Cookie技巧顯示用戶比來閱讀的若干個圖片</a>

web.xml:

 <servlet>
 <servlet-name>ShowServlet</servlet-name>
 <servlet-class>cn.hncu.servlets.ShowServlet</servlet-class>
 </servlet>
<servlet-mapping>
 <servlet-name>ShowServlet</servlet-name>
 <url-pattern>/showImg</url-pattern>
 </servlet-mapping>

show.jsp:

<%@page import="java.io.File"%>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <style type="text/css">
 .span{
  border:0px solid #000;
  width:100px; 
  height:100px;
  overflow:hidden;
 }
 .span img{
  max-width:100px;
  _width:expression(this.width > 100 ? "100px" : this.width);
 }
 .spans{
  border:0px solid #000;
  width:50px; 
  height:50px;
  overflow:hidden;
 }
 .spans img{
  max-width:50px;
  _width:expression(this.width > 50 ? "50px" : this.width);
 }

 </style>

 </head>

 <body>
 <h1>看美男--應用Cookie技巧顯示用戶比來閱讀的若干個圖片</h1>

 <a href="/myCookieWeb/jsps/show.jsp">看美男--應用Cookie技巧顯示用戶比來閱讀的若干個圖片</a>
 <h3>比來閱讀的圖片:</h3>

 <!-- 添加比來3次閱讀的圖片 -->
 <%
 String str =null;
 Cookie cs[] = request.getCookies();
 if(cs!=null){
  for(Cookie c:cs){
  if("images".equals(c.getName())){
   str=c.getValue();// ***.jpg
   break;
  }
  }
 }
 if(str!=null){
  String strs[] = str.split(",");
  for(String s:strs){
  %>
   <span class="spans">
   <img src="<%=request.getContextPath()%>/imgs/<%=s%>" />
   </span> 
  <%
  }
 }
 %>

 <br/><hr/><br/>

 <% 
 //應用file遍歷一切的圖片,顯示出來。
 String path = getServletContext().getRealPath("/imgs");
 //System.out.printf(path);//D:\apache-tomcat-7.0.30\webapps\myCookieWeb\jsps
 File file = new java.io.File(path);
 File[] files = file.listFiles();
 if(files!=null){
 %>

 <%
 for(File f:files){
  String imgName = f.getName();
  %>
  <span class="span">
   <a href="<%=request.getContextPath() %>/showImg?img=<%=imgName %>">
   <img src="<%=request.getContextPath()%>/imgs/<%=imgName%>" />
   </a>
  </span>
  <%
 }
 %>

 <%

 }
 %>

 </body>
</html>


 

ShowServlet.java:

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ShowServlet extends HttpServlet {


 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
 out.println("<HTML>");
 out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
 out.println(" <BODY>");

 String img = request.getParameter("img");
 String imgStr = "<img src='"+request.getContextPath()+"/imgs/"+img+"'/>";
 out.print(imgStr);

 //用Cookie記載用戶拜訪過的圖片信息
 Cookie cs[] = request.getCookies();
 boolean boo = false;
 if(cs!=null){
  for(Cookie c:cs){
  if("images".equals(c.getName())){//曾經有了images這個cookie
   String imgs = c.getValue();
   String imgStrs[] = imgs.split(",");
   boolean booStr = false;
   //防備點擊反復的圖片
   for(int i=0;i<imgStrs.length;i++){
   if(imgStrs[i].equals(img)){
    if(i==1&&imgStrs.length==2){
    imgs=imgStrs[i]+","+imgStrs[0];
    }else if(i==2&&imgStrs.length==3){
    imgs=imgStrs[i]+","+imgStrs[0]+","+imgStrs[1];
    }else if(i==2&&imgStrs.length==3){
    imgs=imgStrs[i]+","+imgStrs[0]+","+imgStrs[1];
    }
    booStr=true;
    break;
   }
   }
   if(!booStr){

   imgs = img+","+imgs;//采取以下方法會費事一點:imgs+","+img
   if(imgs.split(",").length>3){//假如拜訪的圖片跨越3次了
    imgs = imgs.substring(0, imgs.lastIndexOf(","));//左包括,右不包括
   }

   /*//假如如許寫了,最好把下面的防備反復的圖片,誰人添加次序倒過去
   //imgs+","+img 方法:
   imgs = imgs+","+img;
   if(imgs.split(",").length>3){//假如拜訪的圖片跨越3次了
    imgs = imgs.substring(imgs.indexOf(",")+1, imgs.length());
   }
   */
   }
   c.setValue(imgs);//更新
   c.setMaxAge(60*60*24*30);
   c.setPath("/");//相當於把拜訪權限完整攤開,即一切的項目都能拜訪
   response.addCookie(c);
   boo=true;
   break;
  }
  }
 }
 if(boo==false){//表現初次拜訪,即閱讀器中沒有圖片閱讀的cookie
  Cookie c = new Cookie("images", img);
  c.setMaxAge(60*60*24*30);
  c.setPath("/");
  response.addCookie(c);
 }


 out.println(" </BODY>");
 out.println("</HTML>");
 out.flush();
 out.close();
 }

}


 

演示成果:

6、測試火狐閱讀器究竟支撐若干個Cookie和一個Cookie最年夜為多年夜

index.jsp:

<a href="servlet/HowManyCookieServlet">測試火狐閱讀器究竟支撐若干個Cookie和一個Cookie最年夜為多年夜 </a><br/>

web.xml:

 <servlet>
 <servlet-name>HowManyCookie</servlet-name>
 <servlet-class>cn.hncu.servlets.HowManyCookie</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>HowManyCookie</servlet-name>
 <url-pattern>/servlet/HowManyCookieServlet</url-pattern>
 </servlet-mapping>

HowManyCookie.java:

package cn.hncu.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HowManyCookie extends HttpServlet {


 public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
 PrintWriter out = response.getWriter();

 /*
 //測試個數--火狐47.0.1 最年夜支撐110個
 for(int i=1;i<=110;i++){
  Cookie c = new Cookie("textNum"+i, ""+i);
  c.setMaxAge(60*15);
  c.setPath("/");
  response.addCookie(c);
 }
 */

 //測試年夜小 ---4092字節為最年夜支撐的單個cookie存儲
 String s ="";
 for(int i=0;i<4092;i++){
  s+="1";
 }
 Cookie c = new Cookie("test", s);
 c.setMaxAge(60*15);
 c.setPath("/");
 response.addCookie(c);

 Cookie cs[] = request.getCookies();//讀取cookie
 if(cs!=null){//防備一下
  for(Cookie cc:cs){
  String key = cc.getName();
  String val = cc.getValue();
  out.print(key+"="+val+" ");
  }
 }

 }

}

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved