• 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>
    

      

  • 相关阅读:
    数据结构C语言实现----折半查找
    数据结构C语言实现----顺序查找
    数据结构C语言实现----图
    数据结构C语言实现----树
    数据结构C语言实现----循环队列
    数据结构C语言实现----销毁一个队列
    数据结构C语言实现----出队伍操作
    数据结构C语言实现----入队列操作
    数据结构C语言实现----创建一个队列
    数据结构C语言实现----栈的实例
  • 原文地址:https://www.cnblogs.com/linlf03/p/7691370.html
Copyright © 2020-2023  润新知