cookie

import java.io.IOException;

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

@WebServlet(urlPatterns="/cookie.do")
public class CookieServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -125045494438403062L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Cookie cookie=new Cookie("jsessionid","zhangsanlisi");
		cookie.setMaxAge(100);
		cookie.setPath(req.getContextPath());
		resp.addCookie(cookie);	
	}

}
package session_demo;

import java.io.IOException;
import java.io.PrintWriter;

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

@WebServlet(urlPatterns="/getcookie.do")
public class GetCookie extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = -6768741812361862809L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		Cookie[]cookie=req.getCookies();
		resp.setCharacterEncoding("UTF-8");
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out=resp.getWriter();
		for(Cookie c:cookie){
			out.print("cookie名称:"+c.getName()+"<br/>");
			out.print("cookie值:"+c.getValue()+"<br/>");
			out.print("cookie url:"+c.getPath()+"<br/>");
		}
	}

}


你可能感兴趣的:(cookie)