码迷,mamicode.com
首页 > 其他好文 > 详细

Servlet之Cookie

时间:2014-11-25 16:28:49      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:servlet   cookie   

1、对于Cookie的理解,在我看来其实就是存储客户端的一些个性化信息,简单一点的就是username、password之类的

2、在servlet中编程实现Cookie

code

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 CookieServlet extends HttpServlet {

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

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//super.doPost(req, resp);
		PrintWriter out=resp.getWriter();
		Cookie ck=new Cookie("username","cjc");
		//expired time 5 hours
		ck.setMaxAge(3600*5);
		resp.addCookie(ck);
		Cookie[] cookies=req.getCookies();
		out.println("<html>");
		out.println("<head><title>Cookie</title></head>");
		out.println("<body><font size=\"+4\"><b>");
		if(cookies==null){
			out.println("<hr><br>There is no cookie!");
		}else{
			out.println("<hr><br>");
			for(int i=0;i<cookies.length;i++){
				out.println("name:"+cookies[i].getName());
				out.println("value:"+cookies[i].getValue());
			}
		}
		out.println("</b></font></body>");
		out.println("</html>");
	}

}

第一次运行

bubuko.com,布布扣

第二次运行

bubuko.com,布布扣

Servlet之Cookie

标签:servlet   cookie   

原文地址:http://blog.csdn.net/cjc211322/article/details/41482537

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!