创建Cookie 的页面
- import java.io.IOException;
- import java.io.PrintWriter;
- 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 CookieRT01 extends HttpServlet {
- public void destroy() {
- super.destroy();
- }
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- //创建Cookie
- Cookie c=new Cookie("name","tom");
- //设置Cookie 的存活时间
- c.setMaxAge(60*60);
- //添加Cookie到响应
- // response.addCookie(c);
- response.setContentType("text/html;charset=UTF-8");
- PrintWriter out = response.getWriter();
- out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
- out.println("<HTML>");
- out.println(" <HEAD><TITLE>创建Cookie过程</TITLE></HEAD>");
- out.println(" <BODY>");
- out.println("Cookie已经创建");
- out.println(" </BODY>");
- out.println("</HTML>");
- out.flush();
- out.close();
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- public void init() throws ServletException {
- }
- }
获得Cookie 的页面
- import java.io.IOException;
- import java.io.PrintWriter;
- 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 CookieRT0 extends HttpServlet {
- public void destroy() {
- super.destroy(); // Just puts "destroy" string in log
- // Put your code here
- }
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- response.setContentType("text/html;charset=UTF-8");
- //获得Cookie
- Cookie [] cs=request.getCookies();
- PrintWriter out = response.getWriter();
- out.println("<HTML>");
- out.println(" <HEAD><TITLE>测试获得的Cookie</TITLE></HEAD>");
- out.println(" <BODY>");
- if (cs!=null&&cs.length>0) {
-
- for (int i = 0; i < cs.length; i++) {
-
- Cookie c = cs[i];
- String name=c.getName();
- String value=c.getValue();
- out.println("name:"+name+"value:"+value);
- out.println(c.getName()+c.getValue());
- }
- }
- out.println(" </BODY>");
- out.println("</HTML>");
- out.flush();
- out.close();
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- doGet(request, response);
- }
- public void init() throws ServletException {
- // Put your code here
- }
- }
转载于:https://blog.51cto.com/gnlgnl/707453