思路

查看代码注解

实现

代码

Servlet

package Co;
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;
public class CookiesTest01 extends HttpServlet {
private static final long serialVersionUID = 1L;   
 	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//Cookie保存信息(key.value)
	Cookie useranme=new Cookie("useranme","admin");
	Cookie password=new Cookie("password","123456");
	//Cookie手动设置路径
	useranme.setPath(request.getContextPath()+"/bbb");
	password.setPath(request.getContextPath()+"/bbb");
	//Cookie设置时效(秒 * )
	useranme.setMaxAge(60 * 60);
	password.setMaxAge(60 * 60 * 60);
	//把Cookies添加到浏览器
	response.addCookie(useranme);
	response.addCookie(password);
	//得到浏览器发送过来的Cookies(数组)
	Cookie[] cookies=request.getCookies();
	if(cookies == null) {
		System.out.println("0");
	}else {
		for(Cookie c: cookies) {
			System.out.println("name="+ c.getName());
			System.out.println("value="+ c.getValue());
		}
	}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {	
	doGet(request, response);
}
}

XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"   id="WebApp_ID" version="2.5">
<display-name>Cookies01</display-name>
<welcome-file-list>
  <welcome-file>index.html</welcome-file>
  <welcome-file>index.htm</welcome-file>
  <welcome-file>index.jsp</welcome-file>
  <welcome-file>default.html</welcome-file>
  <welcome-file>default.htm</welcome-file>
  <welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
  <description></description>
  <display-name>CookiesTest01</display-name>
  <servlet-name>CookiesTest01</servlet-name>
  <servlet-class>Co.CookiesTest01</servlet-class>
</servlet>
<servlet-mapping>
  <servlet-name>CookiesTest01</servlet-name>
  <url-pattern>/CookiesTest01</url-pattern>
</servlet-mapping>
</web-app>