Java EE开发第十三章:jsp基础、cookie、session

前言:本篇博客介绍jsp的基础用法,以及cookie和session的应用,以及两者的区别。

-----jsp基础---

概述:java server pages(java服务器页面),本质上jsp就是一个servlet在html代码中嵌套java代码,运行在服务器端,处理请求,生成动态的内容。对应的java和class文件在tomcat目录下的work目录,后缀名 .jsp。

执行流程:
1.浏览器发送请求,访问jsp页面
2.服务器接受请求,jspSerlvet会帮我们查找对应的jsp文件
3.服务器将jsp页面翻译成java文件.
4.jvm会将java编译成.class文件
5.服务器运行class文件,生成动态的内容.
6.将内容发送给服务器,
7.服务器组成响应信息,发送给浏览器
8.浏览器接受数据,解析展示

jsp的脚本:
<%...%> java程序片段
生成成jsp的service方法中
<%=...%> 输出表达式
生成成jsp的service方法中,相当于在java中调用out.print(..)
<%!...%> 声明成员
成员位置.

---cookie---

1、概述:cookie是由服务器生成,通过response将cookie写回浏览器(set-cookie),保留在浏览器上,下一次访问,浏览器根据一定的规则携带不同的cookie(通过request的头 cookie),我们服务器就可以接受cookie。

2、cookie的api:

//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的路径.
注意cookie手动设置路径:手动设置路径:以"/项目名"开始,以"/"结尾。

3、Demo:实现记录用户上次登陆时间(路径是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);
	}

}
运行截图:

4.Demo(记录用户浏览历史)

GetProductByIdServlet.java(路径是/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(路径是/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>
运行截图:






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

1.概述:Session是另一种记录客户状态的机制,不同的是Cookie保存在客户端浏览器中,而Session保存在服务器上。客户端浏览器访问服务器的时候,服务器把客户端信息以某种形式记录在服务器上。这就是Session。客户端浏览器再次访问时只需要从该Session中查找该客户的状态就可以了。

2.当我们第一次访问的服务器的时候,服务器获取id。

3.能获取id:要拿着这个id去服务器中查找有无此session,若查找到了:直接拿过来时候,将数据保存,需要将当前sessin的id返回给浏览器,若查找不到:创建一个session,将你的数据保存到这个session中,将当前session的id返回给浏览器

4.不能获取id:创建一个session,将你的数据保存到这个session中,将当前session的id返回给浏览器

5.获取一个session:HttpSession  request.getSession()

6.域对象:
xxxAttribute。

生命周期:创建:第一次调用request.getsession()创建,销毁:服务器非正常关闭,session超时:默认时间超时:30分钟  web.xml有配置,手动设置超时:setMaxInactiveInterval(int 秒) ,手动干掉session:session.invalidate()

存放的私有的数据。

7.Demo(添加到购物车):利用上一个案例继续完善添加到购物车:

Add2CartServlet.java(路径是/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(路径是/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>
运行截图:

---cookie和session区别-----

Cookie通过在客户端记录信息确定用户身份Session通过在服务器端记录信息确定用户身份。




发布了105 篇原创文章 · 获赞 74 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/qq_32306361/article/details/78175674
今日推荐