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>
    

      

  • 相关阅读:
    Nginx+Keepalived实现站点高可用
    强(strong)、软(soft)、弱(weak)、虚(phantom)引用
    Linux SSH 连接不上
    ExtJs Column 显示文字内容过长 使用Tootip显示全部内容
    史上最清晰的红黑树讲解(上)
    MySQL Cluster 集群
    分析《统计学习方法第2版》PDF+习题部分代码+部分课件讨论
    Case Styles: Camel, Pascal, Snake, and Kebab Case
    为什么EXE不能超过4GB
    But How Do It Know 关于人工智能的思考
  • 原文地址:https://www.cnblogs.com/linlf03/p/7691370.html
Copyright © 2011-2022 走看看