33、Cookie的简单使用

33、Cookie的简单使用_第1张图片
新建一个Servlet
CookieServlet.java

package com.atguigu.login.servlet;

import java.io.IOException;

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

/**
 * Servlet implementation class CookieServlet
 */
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//演示Cookie
		Cookie cookie = new Cookie("username", "Admin") ;
		
		//保存到浏览器端
		response.addCookie(cookie) ;
		
		//cookie的默认时效 就是当前浏览器的内存
		
		//设置cookie的保存时间
		//cookie.setMaxAge()
		//设置cookied的路径
		//cookie.setPath(uri);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}

修改index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>



	
	My First Jsp Page
	
	
	
	
	

	
		

我是HTML代码

<% String str = "Abc" ; System.out.println("Abc") ; %> <%=5>3?"大于":"小于"%>
${1+1}
${2>3 }
${empty a }
复杂的事情简单做,简单的事情重复做

Test Cookie

新建一个Servlet
GetCookieServlet.java

package com.atguigu.login.servlet;

import java.io.IOException;

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

/**
 * Servlet implementation class GetCookieServlet
 */
public class GetCookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获取cookie
		
		Cookie [] cookies = request.getCookies() ;
		
		if(cookies!=null){
			for (Cookie cookie : cookies){
				System.out.println(cookie.getName() + " : " + cookie.getValue());
			}
		}else {
			System.out.println("沒有Cookie");
		}
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

}

你可能感兴趣的:(Java-Web)