在探讨Cookie之前,我们先看一下什么是URL重写和隐藏域
URL重写:URL重写是一种会话跟踪技术,它将一个或者多个token添加到URL的查询字符串汇总,每个token通常为key=value 形式。
url?key-1=value-1&key-2=value-2&key-3=value-3…&key-n=value-n
注:(1)若要传递值到下一个资源,需要将值插入到链接中, 即静态页面很难传值;
(2)URL重写需要在服务端上完成, 所有的链接都必须带值。
(3)所有的信息都是可见的,不太安全。
URL重写仅适合于信息仅在少量页面间传递, 且信息本身不敏感。
隐藏域:
类似于URL重写技术,但不是将值附加到URL上,而是反到HTML表单的隐藏域中。当表单提交时,隐藏域的值也同时提交到服务器端。隐藏域技术仅当网页有表单时有效。
该技术相对于URL重写的优势在于:
没有字符数限制,同时无需额外的编码。
Cookie:
因为URL重写和隐藏域仅适合保存无需跨越太多页面的信息。所以如果需要在多个页面之间传递信息,用以上两种技术实现成本高昂,因此不得不在每个页面都进行相应的处理。Cookies技术可以实现着一点。
Cookies是一个很少的信息片段,可自动地在浏览器和Web服务器间交互。
HTTP无状态,无记忆性。引入Cookie识别会话。Cookie保存在客户端
Cookie使用的实例:
CookieServlet类:
@WebServlet(urlPatterns = "/cookieServlet")
public class CookieServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
for(int i=0;i<3;i++){
Cookie cookie=new Cookie("cookieKey-"+i,"cookieValue-"+i);
response.addCookie(cookie);
cookie=new Cookie("PersistentCookieKey-"+i,"PersistentCookieValue-"+i);
cookie.setMaxAge(36000);
response.addCookie(cookie);
}
out.append("<html>")
.append("<head><title>CookieServlet</title></head>")
.append("<body>")
.append("<a href='showServlet'>Go To Show Cookie</a>")
.append("</body>")
.append("</html>");
}
}
其中: cookie.setMaxAge(36000):存活时间36000秒,即设置cookie36000秒后过期,也就是删除
ShowServlet类:
@WebServlet("/showServlet")
public class ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out=response.getWriter();
//显示cookie的状态
out.append("<html>")
.append("<head><title>CookieServlet</title></head>")
.append("<body>")
.append("<table border='1' align='center'>")
.append("<tr>")
.append("<td>CookieName</td>")
.append("<td>CookieValue</td>");
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
if(cookies != null){
for(int i = 0; i < cookies.length; i++){
cookie = cookies[i];
out.append("<tr>")
.append("<td>'"+cookie.getName()+"'</td>")
.append("<td>'"+cookie.getValue()+"'</td>")
.append("</tr>");
}
}
out.append("</tr>")
.append("</table>")
.append("</body>")
.append("</html>");
}
}
结果:
点击图片中这句话,
然后就会显示我们在ShowServlet类中写的内容
Session:
session保存在服务器端
sessionID 服务器和客户端各保存一份.客户端的这个通过cookie来
一个用户有且最多有一个HttpSession,并且不会被其它用户访问到。
HttpSession对象是在用户第一次访问网站的时候自动创建.
创建HttpSession:
(1) HttpSession httpSession = req.getSession(); 返回当前的HttpSession,如果没有,创建一个
(2)HttpSession httpSession = req.getSession(false); 返回当前的HttpSession,如果没有,返回null
(3)HttpSession httpSession = req.getSession(true);返回当前的HttpSession,如果没有,创建一个
HttpSession赋值:
httpSession.setAttribute(“zhang”,“xian”); setAttribute方法中第一个参数是String类型作为key,第二个参数是Object类型作为value
session代码实例:
ShowSessionServlet类
@WebServlet("/showSessionServlet")
public class ShowSessionServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out=resp.getWriter();
//测试Session
HttpSession httpSession=req.getSession(true);
String message=null;
Integer accessCount=(Integer)httpSession.getAttribute("accessCount");
if(accessCount==null) {
accessCount = new Integer(1);
message = "newer";
httpSession.setAttribute("accessCount", accessCount);
}
else{
accessCount=new Integer(accessCount.intValue()+1);
message="older";
httpSession.setAttribute("accessCount",accessCount);
}
out.append("<html>")
.append("<head><title>CookieServletDemo</title></head>")
.append("<body>")
.append("<h1>'"+message+"'</h1></br>")
.append("<table border='1' align='center'>")
.append("<tr>")
.append("<td>SessionID</td>")
.append("<td>'"+httpSession.getId()+"'</td>")
.append("</tr>")
.append("<tr>")
.append("<td>Session Create Time</td>")
.append("<td>'"+httpSession.getCreationTime()+"'</td>")
.append("</tr>")
.append("<tr>")
.append("<td>Session Access Lat Time</td>")
.append("<td>'"+httpSession.getLastAccessedTime()+"'</td>")
.append("</tr>")
.append("<tr>")
.append("<td>AccessCount</td>")
.append("<td>'"+accessCount+"'</td>")
.append("</tr>")
.append("</table>")
.append("</body>")
.append("</html>");
}
}
结果:
刷新页面:
当cookie打开,SessionID只有一个,当cookie关闭,每次都会更新。但是依然能访问到。
完整工程项目见ithub链接:
https://github.com/zhdfuture/Cookie-Servlet/commit/3133d981647a1cc5286e4d183c4d8f3cc9d4aa64
https://github.com/zhdfuture/SessionServlet/commit/8bcedd552c3ce95447702073d270edf3beefa1eb