zoukankan      html  css  js  c++  java
  • Jsp Cookie

    cookie它是用户访问Web服务器时,服务器在用户硬盘上存放的信息。

    1.使用Servlet实现cookie

    @WebServlet("/CookieServlet")
    public class CookieServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        
    	private int count1;
    	private int count2;
    	
        public CookieServlet() {
            super();
        }
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		Cookie cookie = new Cookie("cookieName" +count1++, "cookieValue" +  count2++);
    		cookie.setMaxAge(15);
    		response.addCookie(cookie);
    		
    		Cookie[] cookies = request.getCookies();
    		if (cookies == null) {
    			return;
    		}
    		for(Cookie cook : cookies){
    			System.out.println("cookie name: " +cook.getName());
    			System.out.println("cookie value: " +cook.getValue());
    		}
    		
    	}
    
    	/**
    	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    	 */
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		// TODO Auto-generated method stub
    		doGet(request, response);
    	}
    
    }
    

       cookie的设值方法: response.addCookie(cookie)  

           cookie的取值方法:Cookie[] cookies = request.getCookies();

    2. 使用Jsp实现Cookie

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
    	<%! int count1 = 0;
    		int count2 = 0;
    	%>
    	<%
    		 Cookie cookie = new Cookie("cookieName"+ count1++, "cookieValue" +count2++);
    	     cookie.setMaxAge(15);
    	     response.addCookie(cookie);
    	%>
    	<%
    		Cookie[] cookies = request.getCookies();
    		if(null == cookie){
    			return;
    		}
    		for(Cookie c : cookies){
    			
    		
    	%>
    		<p>
    			<b>cookie name: <%= c.getName() %><b><br>
    			<b>cookie value: <%= c.getValue() %></b>
    		</p>
    	<%
    		}
    	%>
    </body>
    </html>
    

      

  • 相关阅读:
    xen虚拟机管理命令
    ipmi
    http://classworlds.codehaus.org/apiusage.html
    maven编译问题之 -The POM for XXX is invalid, transitive dependencies (if any) will not be available
    SSM项目web.xml等配置文件中如何查找类的全路径名?
    shiro安全框架学习-1
    ht-8 对arrayList中的自定义对象排序( Collections.sort(List<T> list, Comparator<? super T> c))
    ht-7 treeSet特性
    ht-6 hashSet特性
    ht-5 treemap特性
  • 原文地址:https://www.cnblogs.com/linlf03/p/7691370.html
Copyright © 2011-2022 走看看