您的位置:首页 > 编程语言 > Java开发

javaWeb中Cookie,Session原理

2018-03-08 10:34 465 查看
一.概述

初步了解javaweb项目的Cookie、Session,重点认识其原理。

二、示例

1.Cookie

1.1 服务器往客户端写入Cookie,ServeltSetCookies

@WebServlet("/ServeltSetCookies")
public class ServeltSetCookies extends HttpServlet {
private static final long serialVersionUID = 1L;

public ServeltSetCookies() {
super();
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Cookie cookie = new Cookie("cache-cookie", "cache");
response.addCookie(cookie);
Cookie cookie2 = new Cookie("file-cookie", "file");
cookie2.setMaxAge(3600);
response.addCookie(cookie2);
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("addCookie Ok");
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}


1.2 显示写入的Cookie ServeltShowCookies

@WebServlet("/ServeltShowCookies")
public class ServeltShowCookies extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ServeltShowCookies() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<html><head>");
pw.print("<title>Cookie Info</title>");
pw.print("</head><body>");
pw.print("<h2>Cookie Information</h2>");

Cookie[] cookies = request.getCookies();
pw.print("<table  border='1'>");
pw.print("<tr>");
pw.print("<th>");
pw.print("CookieName");
pw.print("</th>");
pw.print("<th>");
pw.print("CookieValue");
pw.print("</th>");
pw.print("</tr>");
if(cookies!=null&&cookies.length>0)
{
for (Cookie cookie : cookies) {
pw.print("<tr>");
pw.print("<td>");
pw.print(cookie.getName());
pw.print("</td>");
pw.print("<td>");
pw.print(cookie.getValue());
pw.print("</td>");
pw.print("</tr>");
}
}
pw.print("</table>");
pw.print("</body></html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}


2.Session

2.1 客户端获取服务器的Session,ServeltInfoSession

@WebServlet("/ServeltInfoSession")
public class ServeltInfoSession extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ServeltInfoSession() {
super();
}

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
*  response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession mysession = request.getSession(true);

response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<html><head>");
pw.print("<title>Session Info</title>");
pw.print("</head><body>");
pw.print("<h2>Session Information</h2>");
pw.print("New Session: " + mysession.isNew());
pw.print("<br />SessionID:" + mysession.getId());
pw.print("<br />Session created time:" + new Date(mysession.getCreationTime()));
pw.print("<br />Session last access time:" + new Date(mysession.getLastAccessedTime()));
pw.print("<h2>Request Information</h2>");
pw.print("<br />SessionID from request:" + request.getRequestedSessionId());
pw.print("<br />SessionID via cookie:" + request.isRequestedSessionIdFromCookie());
pw.print("<br /> SessionID via rewrite URL" + request.isRequestedSessionIdFromURL());
pw.print("<br /> Valid Session" + request.isRequestedSessionIdValid());

pw.print("<br /> <a href = 'ServeltInfoSession'>refresh</a>");
// 重写url encodeURL括号里面写的是类名。
pw.print("<br /> <a href =" + response.encodeURL("ServeltInfoSession") + ">refresh</a>");
pw.print("</body></html>");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}


2.2 显示Session,ServeltShowSession

@WebServlet("/ServeltShowSession")
public class ServeltShowSession extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* @see HttpServlet#HttpServlet()
*/
public ServeltShowSession() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession(true);
String head;

response.setContentType("text/html");
PrintWriter pw = response.getWriter();

Integer count = (Integer) session.getAttribute("access");

if (count == null) {
count = new Integer(0);
head = "hi,newcommer!";
} else {
count = new Integer(count.intValue() + 1);
head = "welcome back";
}
session.setAttribute("access", count);
pw.print("<html><body><h2>" + head + "</h2>" + count + "</body></html>");

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}


三、总结

Cookie存在于客户端,Session存在于服务器。

Cookie:

服务器可以往客户端写入数据

只能是key-value的键值对的文本内容

客户端可以阻止服务器写入

不同的webApplication只能拿自己写入的内容

Cookie有两种类型:属于窗口(内容),属于文本(文件)

一个servlet/jsp设置的cookie能够被同一路径下面或者子路径下面的servlet/jsp读到(路径=URL)(路径 !=真实文件路径)

Session:

两种方式实现(客户端可获取Session):session-id写在临时cookie中,重写URL(response.encodeURL())

Session有过期时间,服务器根据session-timeout时间判断是否清除该Session,tomcat中的通用session过期时间设置为:conf–>web.xml里面的里面的(时间单位为分钟)。

<session-config>
<session-timeout>30</session-timeout>
</session-config>


Session不像Cookie拥有路径访问的问题,同一个application下的servlet/jsp可以共享同一个session,前提是同一个客户端窗口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: