Java EE development Chapter XIII: jsp basis, cookie, session

Preface: This blog describes the basic usage of jsp, as well, and the differences between a cookie and a session of the application.

----- JSP basis ---

Overview: java server pages (java server page), is essentially a jsp java servlet code nested html code runs on the server side, request processing, generation of dynamic content. Corresponding java class files and directories under the work tomcat directory, extension .jsp.

Flow of execution:
1. The browser sends a request to access jsp page
2. The server accepts the request, jspSerlvet will help us to find the corresponding jsp file
3. The server will translate into java jsp page document.
4.jvm will be compiled into a java .class file
the server runs the class file, generation of dynamic content.
6. sends the content to the server
7 in response to information servers, transmits to the browser
8. browser to accept data, parsing show

jsp script: <% ...%> Java program fragment

Generating a service method to jsp
<% = ...%> output expression
Jsp generated into the service process, equivalent to calling Out.print (..) in java
<%! ...%> declaration members
Member location.

---cookie---

1. Overview: cookie is generated by the server, the response the cookie to write back to the browser (set-cookie), remains on the browser, the next visit, the browser carry different cookie according to certain rules (by head cookie request of ), our server can accept cookie.

2, cookie 的 fire:

//cookie的api:
new Cookie(String key,String value)
//写回浏览器:
response.addCookie(Cookie c)
//获取cookie:
Cookie[] request.getCookies()
//cookie的常用方法:
getName()://获取cookie的key(名称)
getValue://获取指定cookie的值
//常用方法:
setMaxAge(int 秒)://设置cookie在浏览器端存活时间  以秒为单位,若设置成 0:删除该cookie(前提必须路径一致)
setPath(String path)://设置cookie的路径.
Note cookie manually set path: Manually set the path: the "/ project name" begins with "/" at the end.

3, Demo: to achieve record the user's last login time (path rem), RemServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Request;

/**
 * 记录上次访问时间
 */
public class RemServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 0设置编码
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();

		// 1获取指定的名称的cookie
		Cookie c = getCookieByName("lastTime", request.getCookies());

		// 2判断cookie是否为空
		if (c == null) {
			// cookie为空 提示 第一次访问
			writer.print("你是第一次访问");
		} else {
			// cookie不为空 获取value 展示上一次访问的时间
			String value = c.getValue();// lastTime=121545466
			long time = Long.parseLong(value);
			Date date = new Date(time);
			writer.print("你上次访问的时间是:" + date.toLocaleString());
		}

		// 3当前访问的时间记录
		// 3.1创建cookie
		c = new Cookie("lastTime", new Date().getTime() + "");

		// 持久化cookie
		c.setMaxAge(3600);
		// 设置路径
		c.setPath(request.getContextPath() + "/");
		// 3.2写会浏览器
		response.addCookie(c);
	}

	/**
	 * 通過名称在cookie数组获取指定的cookie
	 * 
	 * @param name
	 * @param cookies
	 * @return
	 */
	private Cookie getCookieByName(String name, Cookie[] cookies) {
		if (cookies != null) {
			for (Cookie c : cookies) {
				// 通过名称获取
				if (name.equals(c.getName())) {
					// 返回
					return c;
				}
			}
		}
		return null;
	}

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

}
Run shot:

4.Demo (recording user browsing history)

GetProductByIdServlet.java (path / getProductById):

package com.fly.web.servlet;

import java.io.IOException;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fly.utils.CookieUtils;

/**
 * 记录商品浏览历史
 */
public class GetProductByIdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 0设置编码
		// 0.1获取当前访问的商品id
		String id = request.getParameter("id");

		// 1获取指定的cookie ids
		Cookie c = CookieUtils.getCookieByName("ids", request.getCookies());

		String ids = "";
		// 2判断cookie是否为空
		if (c == null) {
			// 若cookie为空 需要将当前的商品id放入ids中
			ids = id;
		} else {
			// 若cookie不为空 继续判断ids中是否已经该id // ids=2-11-21
			// 获取值
			ids = c.getValue();
			String[] arr = ids.split("-");
			// 将数组转成集合 此list长度不可变化
			List<String> asList = Arrays.asList(arr);
			// 将aslist放入一个新的list中去
			LinkedList<String> list = new LinkedList<>(asList);

			if (list.contains(id)) {
				// 若ids中包含id 将id移除 放到最前面
				list.remove(id);
				list.addFirst(id);
			} else {
				// 若ids中不包含id 继续判断长度是否大于2
				if (list.size() > 2) {
					// 长度>=3 移除最后一个 将当前的放入最前面
					list.removeLast();
					list.addFirst(id);
				} else {
					// 长度小于3将当前的id放入最前面
					list.addFirst(id);
				}
			}

			ids = "";

			// 将list转换成字符串
			for (String s : list) {
				ids += (s + "-");
			}
			ids = ids.substring(0, ids.length() - 1);
		}

		// 将ids写会去
		c = new Cookie("ids", ids);
		// 设置访问路径
		c.setPath(request.getContextPath() + "/");
		// 设置存活时间
		c.setMaxAge(3600);

		// 写回浏览器
		response.addCookie(c);

		// 跳转到指定的商品页面上
		response.sendRedirect(request.getContextPath() + "/product_info" + id + ".htm");
	}

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

}
ClearHistroyServlet.java (path / clearHistory):
package com.fly.web.servlet;

import java.io.IOException;
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 ClearHistroyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 创建一个cookie
		Cookie c = new Cookie("ids", "");
		c.setPath(request.getContextPath() + "/");

		// 设置时间
		c.setMaxAge(0);

		// 写回浏览器
		response.addCookie(c);

		// 页面跳转
		response.sendRedirect(request.getContextPath() + "/product_list.jsp");
	}

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

		doGet(request, response);
	}

}
product_list.jsp:
<%@page import="com.fly.utils.CookieUtils"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!doctype html>
<html>

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>

</head>

<body>

	<table align="center">
		<tr>
			<td><a href="/Day1111/getProductById?id=1"> <img
					src="products/cs10001.jpg" width="170" height="170"
					style="display: inline-block;">
			</a> </br> <a href="/Day1111/getProductById?id=1" style='color: green'>衣服</a></td>

			<td><a href="/Day1111/getProductById?id=2"> <img
					src="products/cs10002.jpg" width="170" height="170"
					style="display: inline-block;">
			</a> </br> <a href="/Day1111/getProductById?id=2" style='color: green'>眼镜</a></td>

			<td><a href="/Day1111/getProductById?id=3"> <img
					src="products/cs10003.jpg" width="170" height="170"
					style="display: inline-block;">
			</a> </br> <a href="/Day1111/getProductById?id=3" style='color: green'>包</a></td>

			<td><a href="/Day1111/getProductById?id=4"> <img
					src="products/cs10004.jpg" width="170" height="170"
					style="display: inline-block;">
			</a> </br> <a href="/Day1111/getProductById?id=4" style='color: green'>手机</a></td>

		</tr>
	</table>

	<h4 style="width: 50%;  font: 14px/30px"微软雅黑 ";">
		浏览记录<small><a href="/Day1111/clearHistroy">清空</a></small>
	</h4>
	<br />
	<div style="overflow: hidden;">

		<ul style="list-style: none;">

			<%
				//获取指定名称的cookie ids
				Cookie c = CookieUtils.getCookieByName("ids", request.getCookies());

				//判断ids是否为空
				if (c == null) {
			%>
			<h2>暂无浏览记录</h2>
			<%
				} else {//ids=3-2-1
					String[] arr = c.getValue().split("-");
					for (String id : arr) {
			%>
			<li
				style="width: 150px; height: 216; float: left; margin: 0 8px 0 0; padding: 0 18px 15px; text-align: right;"><img
				src="products/cs1000<%=id%>.jpg" width="130px" height="130px" /></li>
			<%
				}
				}
			%>
		</ul>

	</div>

</body>

</html>
product_info1.htm:(product_info2、3、4省略)
<!doctype html>
<html>

<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>详情页面</title>
</head>

<body align="center">
	这是衣服的详情页面
	<br>
	<img src="products/cs10001.jpg" width="300" height="300"
		style="display: inline-block;">
	</br>
	<a href="/Day1111/add2Cart?name=衣服" style='color: red'>加入购物车</a>
</body>

</html>
Run shot:






------session-----

1. Overview: Session state is another mechanism for a customer record, except that the Cookie stored in the client browser, and Session saved on the server. The client browser access to the server, the server to the client information recorded on the server in some form. This is the Session. Just look for the Session of the client when the client browser access again from the state on it.

2. When we first visit the server, the server get id.

3. can get id:'re looking for there is no such session took the id to the server, if it can find: the direct take over when the data is saved, the current needs of sessin id returned to the browser, if it can find not: create a session, save your data to the session, the current session id returned to the browser

4. Can not get id: create a session, save your data to the session, the current session id returned to the browser

5. Obtain a session: HttpSession request.getSession ()

6. domain objects:
xxxAttribute.

Life Cycle: Created: first call request.getsession () to create, destroy: the server is shut down abnormally, session timeout: The default timeout time: 30 minutes web.xml have configured manually set the timeout: setMaxInactiveInterval (int seconds), manually kill session: session.invalidate ()

Storage of private data.

7.Demo (Add to cart): use on a case continue to improve Add to cart:

Add2CartServlet.java (path / add2Cart):

package com.fly.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 添加到购物车
 */
public class Add2CartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 0设置编码
		response.setContentType("text/html;charset=utf-8");
		PrintWriter writer = response.getWriter();

		// 1获取商品的价格
		String name = request.getParameter("name");
		name = new String(name.getBytes("iso8859-1"), "utf-8");

		// 2将商品添加到购物车
		// 2.1从session中获取购物车
		Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cart");

		Integer count = null;

		// 2.2判断购物车是否为空
		if (map == null) {
			// 第一次购物 创建购物车
			map = new HashMap<>();

			// 将购物车放入session中
			request.getSession().setAttribute("cart", map);

			count = 1;
		} else {
			// 购物车不为空 继续判断购物车中是否有该商品
			count = map.get(name);
			if (count == null) {
				// 购物车没有商品
				count = 1;
			} else {
				// 购物车中有该商品
				count++;
			}
		}

		// 将该商品放入购物车中
		map.put(name, count);

		// 3.提示信息
		writer.print("已经将<b>" + name + "</b>添加到购物车中<hr>");
		writer.print("<a href='" + request.getContextPath() + "/product_list.jsp'>继续购物</a>    ");
		writer.print("<a href='" + request.getContextPath() + "/cart.jsp'>查看购物车</a>    ");

	}

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

}
ClearCartServlet.java (path / clearCart):
package com.fly.web.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 清空购物车
 */
public class ClearCartServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		//1.清空session
		request.getSession().invalidate();
		
		//2.重定向
		response.sendRedirect(request.getContextPath()+"/cart.jsp");
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
Cart.jsp:
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<table border="1" align = "center" width = "20%">

	<tr>
		<td>商品名称</td>
		<td>商品数量</td>
	</tr>
	<%
		//1.获取购物车
		Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cart");
		
	//2.判断购物车是否为空
	if(map == null){
		//2.1若为空
		out.print("<tr><td colspan='2'>亲,购物车空空,先去逛逛~~</td></tr>");
	}else{
		//2.2若不为空:遍历购物车
		for(String name:map.keySet()){
			out.print("<tr>");
			out.print("<td>");
			out.print(name);
			out.print("</td>");
			out.print("<td>");
			out.print(map.get(name));
			out.print("</td>");
			out.print("</tr>");
		}
	}
	%>
</table>
<hr>
	<center>
		<a href="/Day1111/product_list.jsp">继续购物</a>   
		<a href="/Day1111/clearCart">清空购物车</a>
	</center>
</body>
</html>
Run shot:

--- the cookie and session difference -----

Cookie information recorded by the client to determine the identity of the user , the Session by recording the information on the server side to determine the user's identity.




Published 105 original articles · won praise 74 · views 70000 +

Guess you like

Origin blog.csdn.net/qq_32306361/article/details/78175674