JavaWeb study notes 4: Cookie & Session

1- request forwarding and redirection

Request forwarding
request forwarded worded as follows:

request.getRequestDispatcher("login_success.html").forward(request, response);

Strengths and weaknesses:

1, shows the address is the address of the request servlet returns the ok 200
2, number of requests only once, because it is an internal server to help clients perform follow-up work
3, can only jump resource path own projects
4, slightly higher efficiency , because only one request execution
request object 5, can be used on a

Redirection
redirection worded as follows: reorient i.e. jump location parameter

response.sendRedirect("login_success.html");

Strengths and weaknesses:

1, the address is displayed on the final path that resource address
2, at least twice the number of requests, the server after the first request, will return 302 and an address, the browser based on the address, perform a second visit
3 , can jump to any path, not just its own project file
4, slightly lower efficiency, performing two requests
5, subsequent requests, one can not use the data stored on the request, or the request not to use on a Object, because it is two different requests

About redirect, before what I wrote:

response.setStatus(302);
response.setHeader("Location","login_success.html");

So, now you can directly use a line instead of
forwarding the request and redirects fact well understood, may look:
Here Insert Picture Description

2-Cookie simple introduction and use

In fact, a small data server to the client and stored on the client: Cookie
scenarios:> automatic login, browsing history, shopping cart

Q: Why have a Cookie?
A: http request is stateless, client and server when communication is stateless. In fact, a client at the time of the second visit, the server does not know that the client previously had no access to before. The i order a better user experience, better interaction [Automatic Login], so there must Cookie to save the data before the user is, in fact, speaking from the corporate level, is to better collect user habits [big data].

Cookie usage and access:

response.setContentType("UTF-8");	//设置编码,否则响应在页面的中文会乱码
Cookie[] cookies = request.getCookies();	//获得Cookies,有可能为空对象
if(cookies==null){		//若为空对象则添加一次
	Cookie cookie = new Cookie("hpf","perfect");	//以key-value的形式保存
	response.addCookie(cookie);
	response.getWriter().write("Cookie添加成功!");
	System.out.println("Cookie添加成功!");
}else{
	for (Cookie cookie : cookies) {		//遍历
		String name = cookie.getName();
		String value = cookie.getValue();
		System.out.println("Cookie:"+name+"="+value);
	}
}

Cookie common API:

//关闭浏览器后,cookie就没有了 ---> 针对没有设置cookie的有效期
//expiry: 有效 以秒计算。
//正值: 表示在这个数字过后,cookie将会失效。
//负值: 关闭浏览器,那么cookie就失效, 默认值是 -1
cookie.setMaxAge(60 * 60 * 24 * 7);	 //使用Cookie对象来设置,表示七天有效期
//cookie.setValue(newValue);	//赋值新的值
//用于指定只有请求了指定的域名,才会带上该cookie
cookie.setDomain(".itheima.com");
//只有访问该域名下的cookieDemo的这个路径地址才会带cookie
cookie.setPath("/CookieDemo");
3-Cookie Gets Last

Here Cookie be a comprehensive example, the following codes (the main part):
the login.html:

<body>
	<h3>请登录</h3>
	<form action="Demo03">
		账号:<input type="text" name="username">
		密码:<input type="password" name="password">
		<input type="submit" value="登录">
	</form>
</body>

CookieUtil:

//获取指定name的Cookie
public static Cookie getCookie(Cookie[] cookies,String name){
	for (Cookie cookie : cookies) {
		if(cookie.getName().equals(name)){
			return cookie;
		}
	}
	return null;
}
//清空当前浏览器的Cookie
public static Cookie[] clearCookie(Cookie[] cookies,HttpServletResponse response){
	for (Cookie cookie : cookies) {
		cookie.setMaxAge(0);
		response.addCookie(cookie);
	}
	return cookies;
}

GetLastLoginTime:

response.setContentType("text/html;charset=UTF-8");
Date currenDate = null;
String currenTime = "";
String username = request.getParameter("username");
Cookie[] cookies = request.getCookies();
Writer writer = response.getWriter();
if(cookies!=null){
	//获取上一次登录的时间
	Cookie time = CookieUtil.getCookie(cookies, "time");
	if(time!=null){
		String value = time.getValue();
		writer.write("欢迎"+username+"登录,上一次的登录时间为:"+value);
		currenDate = new Date(System.currentTimeMillis());
		currenTime = currenDate.toLocaleString();
		time.setValue(currenTime);
		time.setMaxAge(60*5);
		response.addCookie(time);
	}else{
		CookieUtil.clearCookie(cookies,response);
		response.setHeader("refresh", "3;login.html");
		writer.write("Cookie已有数组,清空成功!");
	}
}else{
	currenDate = new Date(System.currentTimeMillis());
	currenTime = currenDate.toLocaleString();
	Cookie time = new Cookie("time", currenTime);
	time.setMaxAge(60*5);
	response.addCookie(time);
	response.setHeader("refresh", "3;login.html");
	writer.write("未找到Cookie,添加timeCookie成功!");
}

Summary and personal experience:
1, login.html not say more, or so simple
2, setContentType this method in the field, do not text wrong !!! / HTML; charset = UTF-8
3, this thing Writer best to write an object out, or every time get
4, although the first landing, but there may Cookie before, so take advantage of it Util empty
5 empty finished or finished adding cookie, must refresh to login.html
6, the code is the code, but it is not a one-time write out, and are twists and turns, not necessarily back, you know the idea!

4-Cookie merchandise History

First of all, I will prepare a html page of a commodity, placed in the WebContent.
Secondly, and then created a new jsp in the WebContent file, product_list.jsp, copy the contents to html to jsp.
Then, change it a commodity in which the jump address, change product_list.jsp.

Thought process record:
1, users enter a list of home merchandise, merchandise has not been selected, this time for the first time into the home
2, the user selects a commodity, jsp return a product id, Servlet based on the id record Cookie
3, the user is not the first times into the home, choose another commodity, Servlet add this to the last id in Cookie

Servlet code as follows:

String id = request.getParameter("id");
Cookie[] cookies = request.getCookies();
Cookie history = CookieUtil.getCookie(cookies, "history");
if(history==null){//第一次进网站,没有cookie保存
	Cookie h = new Cookie("history",id);
	h.setMaxAge(60*1);
	//设置访问这个工程的时候,才带cookie过来
	h.setPath("/CookieDemo02");
	response.addCookie(h);
}else{//非第一次浏览,输出cookie并更新
	System.out.println(history.getValue());
	history.setValue(id+"#"+history.getValue());	//拼接Cookie
	history.setMaxAge(60*1);
	history.setPath("/CookieDemo02");
	response.addCookie(history);
}
//跳转到具体的info页面
response.sendRedirect("product_info.htm");

Here are what jsp, ava Server Pager -> eventually translated into a class, is a Servlet. That can be written in the jsp java code.

  • Define global variables
    <!% Int a = 99; %>
  • Define local variables
    <% int b = 999;% >
  • In jsp pages, displays the values of a and b
    <= a%%>
    <% b =%>

product_list.jsp Java code as follows:

<% 
	Cookie[] cookies = request.getCookies();
	Cookie history = null;
	if(cookies==null){
		history = null;
	}else{
		history = CookieUtil.getCookie(cookies, "history");
	}
	String[] ids = null;
	//若history为空的话
	if(history==null){
%>
		<h1>您的浏览记录为空!</h1>
<%
	}else{
		ids = history.getValue().split("#");
		for(String id : ids){
%>
			<li style="width: 150px;height: 216;float: left;margin: 0 8px 0 0;padding: 0 18px 15px;text-align: center;"><img src="products/<%=id%>.jpg" width="130px" height="130px" /></li>
<%
		}
	}
%>

Note: The
first pair <%>, if the cookies are not judged, it is possible to enter the page will report null pointer error, so to judge.
Here's id to use to get into the picture file in the directory products.
So all of the above function code is implemented: enter the mall and you can select items, and finally the ability to view history

Delete browsing history to achieve:
First div below the picture of history to write a h2, h2 nested < A href = "ClearHistory"> Clear browsing history </ A >
Then write ClearHistory, is actually very simple, the main code is as follows:

Cookie[] cookies = request.getCookies();
Cookie history = CookieUtil.getCookie(cookies,"history");
Cookie cookie = new Cookie("history", "");
cookie.setMaxAge(0);
cookie.setPath("/CookieDemo02");
response.addCookie(cookie);
response.sendRedirect("product_list.jsp");

Note In summary:
1, delete the cookie is no delete method, only maxAge set to 0
2 because set to 0, the intention is clear only after the browser is closed, it can not immediately see
3, delete when deleted do not always out, in general, or not careful enough in History, a non-first browsing when you add a Cookie, forget to set the path , leading to Cookie added later is not / CookieDemo02 below, focus! ! !

Cookie Summary:
  1. Cookie is sent from the server to the client a small portion of data, and stored on the client

  2. Get cookie, add cookie

    request.getCookie();
    response.addCookie();
    
  3. Cookie classification
    Session Cookie
    By default, closes the browser, the cookie will disappear

    Cookie persistence
    over time, they are valid and will be saved on the client

    cookie.setMaxAge(0); //设置立即删除
    cookie.setMaxAge(100); //100 秒
    
  4. Cookie security issues
    1, due to the Cookie will be stored on the client, so there are safety problems
    2, and, Cookie size and the number is limited, in order to solve this problem -> on the introduction of Session

5-Session presentation and simple to use

Session session is based on a mechanism of Cookie
Cookie similarities and differences with the Session:
Cookie is a small portion of the data returned by the server to the client, and stored on the client, the data are Session, but stored on the server side

Session common API:

//得到会话ID
String id = session.getId();
//存值
session.setAttribute(name, value);
//取值
session.getAttribute(name);
//移除值
session.removeAttribute(name);

Session's lifecycle:
creation: If this method in the servlet which calls request.getSession (), it creates the Session
destruction: Session data is stored in a server's memory, even off the browser, session also not destroy
destroy ways:
1, shut down the server
2, session session time expired, and so the end of the period. The default is valid for 30 minutes

6-Session achieve pages cart

Examples of Session cart (analysis):
1, data storage cart for this example can also do with Cookie and so on, but with more security Session
2, first the general structure: Product page -> Count.Servlet-> billing page
3, the second is the familiar method uses Session and the inside of the can

Session cart example (page display):
product_list.jsp:

<body>
	<h1>请选择以下商品购买!</h1>
	<a href="Count?id=0"><h3>iphone7</h3></a>
	<a href="Count?id=1"><h3>小米10</h3></a>
	<a href="Count?id=2"><h3>华为p30pro</h3></a>
	<a href="Count?id=3"><h3>魅族3</h3></a>
	<a href="Count?id=4"><h3>联想y7000p</h3></a>
	<a href="Count?id=5"><h3>戴尔外星人</h3></a>
</body>

Count:

response.setContentType("text/html;charset=utf-8");
String[] names = {"iphone7","小米10","华为p30pro","魅族3","联想y7000p","戴尔外星人"};	//所有的商品名
Integer id = Integer.parseInt(request.getParameter("id"));		//获取传过来的id
String name = names[id];	//取出id所对应的商品名
Writer writer = response.getWriter();	//获取输出流
HttpSession session = request.getSession();		//获得Session
Map<String, Integer> cart = (Map<String, Integer>)session.getAttribute("cart");
if(cart==null){	//以大化小,先化大的
	cart = new LinkedHashMap<String, Integer>();
	request.getSession().setAttribute("cart", cart);
}
if(!cart.containsKey(name)){	//第一次选择商品,并且购物车里面没东西
	cart.put(name, 1);
}else{	//不是第一次选择商品,要叠加数量并显示
	cart.put(name, (cart.get(name)+1));
}
writer.write("<a href='product_list.jsp'><h2>继续购物</h2></a>");
writer.write("<a href='cart.jsp'><h2>进行结算</h2></a>");

cart.jsp:

<body>
	<h1>以下为所选商品以及数量</h1>
	<%
		Map<String,Integer> cart = (Map<String,Integer>)request.getSession().getAttribute("cart");
		for(String name : cart.keySet()){
	%>
		<h3>商品名:<%=name %>	数量:<%=cart.get(name)%></h3>
	<%
		}
	%>
		<a href="ClearCart"><h2>清空购物车</h2></a>
</body>

Session cart example (Empty Cart):

HttpSession session = request.getSession();
//写法二:移除整个session
session.invalidate();

//写法一:移除cart这个map
session.removeAttribute("cart");
response.sendRedirect("cart.jsp");

Cart summary example:
1 so that they better understand the Cookie and Session usage, benefit a lot
2, by using the Map on unskilled and have been consolidated, have strengthened
3, add the code of goods Count, I learned Dahua small idea, put a large (cart) judgment, and do small (add)
4, <%> uses have been strengthened, and gradually will be used to write jsp page code, forEach loop has also been strengthen
5, the underlying Web project implementation has been profound understanding and development, and thanked their efforts!

Published 15 original articles · won praise 18 · views 4575

Guess you like

Origin blog.csdn.net/oZuoShen123/article/details/105096255