Cookie和Session和Filter学习笔记

目录:

  1. Cookie传送
  2. Session传送
  3. Filter过滤器传送

Cookie学习

返回目录
1、Cookie 饼干
a)什么是Cookie?
1、Cookie 翻译过来是饼干的意思。
2、Cookie 是服务器通知客户端保存键值对的一种技术。
3、客户端有了Cookie 后,每次请求都发送给服务器。
4、每个Cookie 的大小不能超过4kb
b)如何创建Cookie
在这里插入图片描述
Servlet 程序中的代码:

protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	//1 创建Cookie 对象
	Cookie cookie = new Cookie("key4", "value4");
	//2 通知客户端保存Cookie
	resp.addCookie(cookie);
	//1 创建Cookie 对象
	Cookie cookie1 = new Cookie("key5", "value5");
	//2 通知客户端保存Cookie
	resp.addCookie(cookie1);
	resp.getWriter().write("Cookie 创建成功");

c)服务器如何获取Cookie
服务器获取客户端的Cookie 只需要一行代码:req.getCookies():Cookie[]
在这里插入图片描述
Cookie 的工具类:

public class CookieUtils {
/**
* 查找指定名称的Cookie 对象
* @param name
* @param cookies
* @return
*/
	public static Cookie findCookie(String name , Cookie[] cookies){
	if (name == null || cookies == null || cookies.length == 0) {
			return null;
			}
			for (Cookie cookie : cookies) {
			if (name.equals(cookie.getName())) {
			return cookie;
			}
		}
		return null;
	}
}

Servlet 程序中的代码:

protected void getCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	Cookie[] cookies = req.getCookies();
	for (Cookie cookie : cookies) {
	// getName 方法返回Cookie 的key(名)
	// getValue 方法返回Cookie 的value 值
	resp.getWriter().write("Cookie[" + cookie.getName() + "=" + cookie.getValue() + "] <br/>");
}
	Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
	// for (Cookie cookie : cookies) {
	// if ("key2".equals(cookie.getName())) {
	// iWantCookie = cookie;
	// break;
	// }
	// }
	// 如果不等于null,说明赋过值,也就是找到了需要的Cookie
	if (iWantCookie != null) {
	resp.getWriter().write("找到了需要的Cookie");
	}
}

d)Cookie 值的修改
方案一:
1、先创建一个要修改的同名(指的就是key)的Cookie 对象
2、在构造器,同时赋于新的Cookie 值。
3、调用response.addCookie( Cookie );

// 方案一:
// 1、先创建一个要修改的同名的Cookie 对象
// 2、在构造器,同时赋于新的Cookie 值。
Cookie cookie = new Cookie("key1","newValue1");
// 3、调用response.addCookie( Cookie ); 通知客户端保存修改
resp.addCookie(cookie);

方案二:
1、先查找到需要修改的Cookie 对象
2、调用setValue()方法赋于新的Cookie 值。
3、调用response.addCookie()通知客户端保存修改

// 方案二:
// 1、先查找到需要修改的Cookie 对象
Cookie cookie = CookieUtils.findCookie("key2", req.getCookies());
if (cookie != null) {
// 2、调用setValue()方法赋于新的Cookie 值。
cookie.setValue("newValue2");
// 3、调用response.addCookie()通知客户端保存修改
resp.addCookie(cookie);
}

e)浏览器查看Cookie:
谷歌浏览器如何查看Cookie:
在这里插入图片描述
火狐浏览器如何查看Cookie:

在这里插入图片描述
f) Cookie 生命控制

  • Cookie 的生命控制指的是如何管理Cookie 什么时候被销毁(删除)
  • setMaxAge()
    • 正数,表示在指定的秒数后过期
    • 负数,表示浏览器一关,Cookie 就会被删除(默认值是-1)
    • 零,表示马上删除Cookie
/**
* 设置存活1 个小时的Cooie
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	Cookie cookie = new Cookie("life3600", "life3600");
	cookie.setMaxAge(60 * 60); // 设置Cookie 一小时之后被删除。无效
	resp.addCookie(cookie);
	resp.getWriter().write("已经创建了一个存活一小时的Cookie");
}
/**
* 马上删除一个Cookie
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	// 先找到你要删除的Cookie 对象
	Cookie cookie = CookieUtils.findCookie("key4", req.getCookies());
	if (cookie != null) {
	// 调用setMaxAge(0);
	cookie.setMaxAge(0); // 表示马上删除,都不需要等待浏览器关闭
	// 调用response.addCookie(cookie);
	resp.addCookie(cookie);
	resp.getWriter().write("key4 的Cookie 已经被删除");
	}
}
/**
* 默认的会话级别的Cookie
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	Cookie cookie = new Cookie("defalutLife","defaultLife");
	cookie.setMaxAge(-1);//设置存活时间
	resp.addCookie(cookie);
}

g)Cookie 有效路径Path 的设置
在这里插入图片描述

protected void testPath(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
Cookie cookie = new Cookie("path1", "path1");
// getContextPath() ===>>>> 得到工程路径
cookie.setPath( req.getContextPath() + "/abc" ); // ===>>>> /工程路径/abc
resp.addCookie(cookie);
resp.getWriter().write("创建了一个带有Path 路径的Cookie");
}

h) Cookie 练习—免输入用户名登录
在这里插入图片描述
login.jsp 页面:

<form action="http://localhost:8080/13_cookie_session/loginServlet" method="get">
	用户名:<input type="text" name="username" value="${cookie.username.value}"> <br>
	密码:<input type="password" name="password"> <br>
	<input type="submit" value="登录">
</form>

LoginServlet 程序:

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	String username = req.getParameter("username");
	String password = req.getParameter("password");
	if ("wzg168".equals(username) && "123456".equals(password)) {
	//登录成功
	Cookie cookie = new Cookie("username", username);
	cookie.setMaxAge(60 * 60 * 24 * 7);//当前Cookie 一周内有效
	resp.addCookie(cookie);
	System.out.println("登录成功");
	} else {
	// 登录失败
	System.out.println("登录失败");
	}
}

Session会话

返回目录
i) 什么是Session 会话?
1、Session 就一个接口(HttpSession)。
2、Session 就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个Session 会话。
4、Session 会话中,我们经常用来保存用户登录之后的信息。
j) 如何创建Session 和获取(id 号,是否为新)
在这里插入图片描述
k)Session 域数据的存取

/**
* 往Session 中保存数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	req.getSession().setAttribute("key1", "value1");
	resp.getWriter().write("已经往Session 中保存了数据");
}
/**
* 获取Session 域中的数据
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	Object attribute = req.getSession().getAttribute("key1");
	resp.getWriter().write("从Session 中获取出key1 的数据是:" + attribute);
}

l) Session 生命周期控制
在这里插入图片描述
如果说。你希望你的web 工程,默认的Session 的超时时长为其他时长。你可以在你自己的web.xml 配置文件中做以上相同的配置。就可以修改你的web 工程所有Seession 的默认超时时长。

<!--表示当前web 工程。创建出来的所有Session 默认是20 分钟超时时长-->
<session-config>
	<session-timeout>20</session-timeout>
</session-config>

如果你想只修改个别Session 的超时时长。就可以使用上面的API。setMaxInactiveInterval(int interval)来进行单独的设置。
session.setMaxInactiveInterval(int interval)单独设置超时时长。
Session 超时的概念介绍:
在这里插入图片描述
示例代码:

protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	// 先获取Session 对象
	HttpSession session = req.getSession();
	// 设置当前Session3 秒后超时
	session.setMaxInactiveInterval(3);
	resp.getWriter().write("当前Session 已经设置为3 秒后超时");
}

Session 马上被超时示例:

protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	// 先获取Session 对象
	HttpSession session = req.getSession();
	// 让Session 会话马上超时
	session.invalidate();
	resp.getWriter().write("Session 已经设置为超时(无效)");
}

m) 浏览器和Session 之间关联的技术内幕
Session 技术,底层其实是基于Cookie 技术来实现的。
在这里插入图片描述

Filter过滤器

返回目录

1、Filter 什么是过滤器

1、Filter 过滤器它是JavaWeb 的三大组件之一。三大组件分别是:Servlet 程序、Listener 监听器、Filter 过滤器
2、Filter 过滤器它是JavaEE 的规范。也就是接口
3、Filter 过滤器它的作用是:拦截请求,过滤响应。
拦截请求常见的应用场景有:
1、权限检查
2、日记操作
3、事务管理
……等等

2、Filter 的初体验

要求:在你的web 工程下,有一个admin 目录。这个admin 目录下的所有资源(html 页面、jpg 图片、jsp 文件、等等)都必须是用户登录之后才允许访问。

思考:根据之前我们学过内容。我们知道,用户登录之后都会把用户登录的信息保存到Session 域中。所以要检查用户是否登录,可以判断Session 中否包含有用户登录的信息即可!!!

<%
Object user = session.getAttribute("user");
// 如果等于null,说明还没有登录
if (user == null) {
request.getRequestDispatcher("/login.jsp").forward(request,response);
return;
}
%>

Filter 的工作流程图:
在这里插入图片描述
Filter 的代码:

public class AdminFilter implements Filter {
/**
* doFilter 方法,专门用于拦截请求。可以做权限检查
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain
filterChain) throws IOException, ServletException {
	HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
	HttpSession session = httpServletRequest.getSession();
	Object user = session.getAttribute("user");
	// 如果等于null,说明还没有登录
	if (user == null) {
	servletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
			return;
		} else {
	// 让程序继续往下访问用户的目标资源
		filterChain.doFilter(servletRequest,servletResponse);
		}
	}
}

web.xml 中的配置:

<!--filter 标签用于配置一个Filter 过滤器-->
<filter>
	<!--给filter 起一个别名-->
	<filter-name>AdminFilter</filter-name>
	<!--配置filter 的全类名-->
	<filter-class>com.atguigu.filter.AdminFilter</filter-class>
</filter>
<!--filter-mapping 配置Filter 过滤器的拦截路径-->
<filter-mapping>
	<!--filter-name 表示当前的拦截路径给哪个filter 使用-->
	<filter-name>AdminFilter</filter-name>
	<!--url-pattern 配置拦截路径
	/ 表示请求地址为:http://ip:port/工程路径/ 映射到IDEA 的web 目录
	/admin/* 表示请求地址为:http://ip:port/工程路径/admin/*
	-->
	<url-pattern>/admin/*</url-pattern>
</filter-mapping>

Filter 过滤器的使用步骤:
1、编写一个类去实现Filter 接口
2、实现过滤方法doFilter()
3、到web.xml 中去配置Filter 的拦截路径
完整的用户登录
login.jsp 页面== 登录表单

这是登录页面。login.jsp 页面<br>
<form action="http://localhost:8080/15_filter/loginServlet" method="get">
	用户名:<input type="text" name="username"/> <br>
	密码:<input type="password" name="password"/> <br>
	<input type="submit" />
</form>

LoginServlet 程序

public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
	resp.setContentType("text/html; charset=UTF-8");
	String username = req.getParameter("username");
	String password = req.getParameter("password");
	if ("wzg168".equals(username) && "123456".equals(password)) {
	req.getSession().setAttribute("user",username);
	resp.getWriter().write("登录成功!!!");
	} else {
	req.getRequestDispatcher("/login.jsp").forward(req,resp);
		}
	}
}

3、Filter 的生命周期

Filter 的生命周期包含几个方法
Filter 的生命周期包含几个方法
1、构造器方法
2、init 初始化方法
第1,2 步,在web 工程启动的时候执行(Filter 已经创建)
3、doFilter 过滤方法
第3 步,每次拦截到请求,就会执行
4、destroy 销毁
第4 步,停止web 工程的时候,就会执行(停止web 工程,也会销毁Filter 过滤器)

4、FilterConfig 类

  • FilterConfig 类见名知义,它是Filter 过滤器的配置文件类。
  • Tomcat 每次创建Filter 的时候,也会同时创建一个FilterConfig 类,这里包含了Filter 配置文件的配置信息。
  • FilterConfig 类的作用是获取filter 过滤器的配置内容
    • 获取Filter 的名称filter-name 的内容
    • 获取在Filter 中配置的init-param 初始化参
    • 获取ServletContext 对象

java 代码:

@Override
public void init(FilterConfig filterConfig) throws ServletException {
	System.out.println("2.Filter 的init(FilterConfig filterConfig)初始化");
	// 1、获取Filter 的名称filter-name 的内容
	System.out.println("filter-name 的值是:" + filterConfig.getFilterName());
	// 2、获取在web.xml 中配置的init-param 初始化参数
	System.out.println("初始化参数username 的值是:" + filterConfig.getInitParameter("username"));
	System.out.println("初始化参数url 的值是:" + filterConfig.getInitParameter("url"));
	// 3、获取ServletContext 对象
	System.out.println(filterConfig.getServletContext());
}

web.xml 配置:

<!--filter 标签用于配置一个Filter 过滤器-->
<filter>
	<!--给filter 起一个别名-->
	<filter-name>AdminFilter</filter-name>
	<!--配置filter 的全类名-->
	<filter-class>com.atguigu.filter.AdminFilter</filter-class>
	<init-param>
		<param-name>username</param-name>
		<param-value>root</param-value>
	</init-param>
	<init-param>
		<param-name>url</param-name>
		<param-value>jdbc:mysql://localhost3306/test</param-value>
	</init-param>
</filter>

5、FilterChain 过滤器链

Filter           过滤器
Chain         链,链条
FilterChain 就是过滤器链(多个过滤器如何一起工作)
在这里插入图片描述

6、Filter 的拦截路径

–精确匹配

<url-pattern>/target.jsp</url-pattern>

以上配置的路径,表示请求地址必须为:http://ip:port/工程路径/target.jsp

–后缀名匹配

<url-pattern>*.html</url-pattern>

以上配置的路径,表示请求地址必须以.html 结尾才会拦截到

<url-pattern>*.do</url-pattern>

以上配置的路径,表示请求地址必须以.do 结尾才会拦截到

<url-pattern>*.action</url-pattern>

以上配置的路径,表示请求地址必须以.action 结尾才会拦截到
Filter 过滤器它只关心请求的地址是否匹配,不关心请求的资源是否存在!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CharmDeer

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值