黑马程序员技术交流社区
标题:
分享一下javaWeb中的cookie
[打印本页]
作者:
血剑无痕
时间:
2013-10-19 19:21
标题:
分享一下javaWeb中的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 SaxAgeCookie extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//输出到浏览器
PrintWriter out = response.getWriter();
//读取cookie
Cookie[] cookies = request.getCookies();
if(cookies != null){
for(Cookie c : cookies){
out.print(c.getName() + ":" + c.getValue() + "<br/>");
}
} else {
//不存在cookie
out.print("不存在cookie");
}
//设置cookie的有效时间,使会话级cookie变成持久化cookie
// * 创建cookie
Cookie cookie = new Cookie("lin","林妹妹");
// * 设置有效时间
cookie.setMaxAge(60 * 60 * 24);
// * 通知浏览器
response.addCookie(cookie);
}
}
作者:
吴光新
时间:
2013-10-21 00:11
刚好学习到
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2