g) Cookie 有效路径Path的设置
Cookie的path属性可以有效的过滤哪些Cookie可以发送给服务器。哪些不发。
path属性是通过请求的地址来进行有效的过滤。
CookieA path=/工程路径
CookieB path=/工程路径/abc
请求地址如下:
http://ip:port/工程路径/a.html
CookieA发送
CookieB不发送
http://ip:port/工程路径/abc/a.html
CookieA发送
CookieB发送
修改 cookie.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.O1 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" kontent="no-cache" /> <meta http-equiv="Expires" content="0" /> <meta http-equiv="content-Type" content="text/html; charset=UTF-8"> <title>Cookie</title> <base href="http://localhost:8080/13_cookie_session/"> <style type="text/css"> ul li{ list-style:none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="..."></iframe> <div style="..."> <ul> <li><a href="cookieServlet?action=createCookie" target="target">Cookie的创建</a></li> <li><a href="cookieServlet?action=getCookie" target="target">cookie的获取</a></li> <li><a href="cookieServlet?action=updateCookie" target="target">cookie值的修改</a></li> <li>cookie的存活周期</li> <li> <ul> <li><a href="cookieServlet?action=defaultLife" target="target">cookie的默认存活时间(会话)</a></li> <li><a href="cookieServlet?action=deleteNow" target="target">Cookie立即删除</a></li> <li><a href="cookieServlet?action=life3600" target="target">Cookie存活3600秒(1小时)</a></li> </ul> </li> <li><a href="cookieServlet?action=testPath" target="target">Cookie的路径设置</a></li> <li><a href="" target="target">Cookie的用户免登录练习</a></li> </ul> </div> </body> </html>
修改
package com.servlet; import com.util.CookieUtils; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class CookieServlet extends BaseServlet { protected void createCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1 创建Cookie对象 Cookie cookie = new Cookie("key1", "value1"); //2 通知客户端保存Cookie resp.addCookie(cookie); //1 创建Cookie对象 Cookie cookie2 = new Cookie("key2", "value2"); //2 通知客户端保存Cookie resp.addCookie(cookie2); //1 创建Cookie对象 Cookie cookie3 = new Cookie("key3", "value3"); //2 通知客户端保存Cookie resp.addCookie(cookie3); resp.getWriter().write("Cookie创建成功"); } 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"); } } protected void updateCookie(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 方案一 1、先创建一个要修改的同名的Cookie对象 2、在构造器,同时赋于新的Cookie值。 // Cookie cookie=new Cookie("key1","newValue1"); 3、调用response.addCookie( Cookie );//通知客户端保存修改 // resp.addCookie(cookie); // resp.getWriter().write("key1的Cookie已经修改好"); // 方案二: // 1、先查找到需要修改的Cookie对象 Cookie cookie=CookieUtils.findCookie("key2",req.getCookies()); if (cookie!=null){ // 2、调用setValue()方法赋于新的Cookie值。 cookie.setValue("newValue2"); // 3、调用response.addCookie()通知客户端保存修改 resp.addCookie(cookie); } resp.getWriter().write("key2的Cookie已经修改好"); } protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cookie=new Cookie("defaultLife","defaultLife"); cookie.setMaxAge(-1);//设置存活时间 resp.addCookie(cookie); } protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //先找到你要删除的Cookie对象 Cookie cookie=CookieUtils.findCookie("key3",req.getCookies()); if (cookie!=null){ //调用setMaxAge(0) cookie.setMaxAge(0);//表示马上删除,都不需要等待浏览器关闭 //调用response.addCookie( Cookie ) resp.addCookie(cookie); resp.getWriter().write("key3的Cookie已经被删除"); } } protected void life3600(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //先找到你要删除的Cookie对象 Cookie cookie=new Cookie("life3600","life3600"); cookie.setMaxAge(60*60);//设置Cookie一小时之后被删除,无效 resp.addCookie(cookie); resp.getWriter().write("已经创建了一个存活一小时的Cookie"); } 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 练习——免输入用户名登录
创建 LoginServlet,并配置web.xml
package com.servlet; 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 java.io.IOException; public class LoginServlet extends HttpServlet { @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("登录失败"); } } }
创建 login.jsp
<%-- Created by IntelliJ IDEA. User: lenovo Date: 2021/8/24 Time: 下午 02:47 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <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> </body> </html>
结果
访问http://localhost:8080/13_cookie_session/login.jsp
登录成功以后关闭浏览器,再次访问
2、Session 会话
准备
创建web/session.html
<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Session</title> <style type="text/css"> ul li{ list-style:none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="..."></iframe> <div style="..."> <ul> <li><a href="" target="target">Session的创建和获取(id号、是否为新创建)</a></li> <li><a href="" target="target">session域数据的存储</a></li> <li><a href="" target="target">Session域数据的获取</a></li> <li>session的存活</li> <li> <ul> <li><a href="" target="target">Session的默认超时及配置</a></li> <li><a href="" target="target">session3秒超时销毁</a></li> <li><a href="" target="target">Session马上销毁</a></li> </ul> </li> <li><a href="" target="target">浏览器和Session绑定的原理</a></li> </ul> </div> </body> </html>
i) 什么是Session会话?
1、Session就一个接口(Httpsession)。
2、Session就是会话。它是用来维护一个客户端和服务器之间关联的一种技术。
3、每个客户端都有自己的一个session会话。
4、Session会话中,我们经常用来保存用户登录之后的信息。
j) 如何创建Session和获取(id号,是否为新) 如何创建和获取session。它们的API是一样的。
request.getSession()
第一次调用是:创建Session会话
之后调用都是:获取前面创建好的Session会话对象。
isNew();判断到底是不是刚创建出来的〈新的)
true表示刚创建
false表示获取之前创建
每个会话都有一个身份证号。也就是ID值。而且这个ID是唯一的。
getld()得到Session的会话id值。
创建SessionServlet,并在web.xml配置
package com.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionServlet extends BaseServlet{ protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建和获取Session会话对象 HttpSession session = req.getSession(); //判断 当前session回滚,是否是新创建出来的 boolean isNew = session.isNew(); //获取session会话的唯一标识 id String id = session.getId(); resp.getWriter().write("得到的Session,它的id是:"+id+"<br/>"); resp.getWriter().write("这个Session是否是新创建的:"+isNew+"<br/>"); } }
修改 session.html
<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Session</title> <base href="http://localhost:8080/13_cookie_session/"> <style type="text/css"> ul li{ list-style:none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="..."></iframe> <div style="..."> <ul> <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li> <li><a href="" target="target">session域数据的存储</a></li> <li><a href="" target="target">Session域数据的获取</a></li> <li>session的存活</li> <li> <ul> <li><a href="" target="target">Session的默认超时及配置</a></li> <li><a href="" target="target">session3秒超时销毁</a></li> <li><a href="" target="target">Session马上销毁</a></li> </ul> </li> <li><a href="" target="target">浏览器和Session绑定的原理</a></li> </ul> </div> </body> </html>
结果
首次点击
之后点击
k)Session 域数据的存取
修改 SessionServlet
package com.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionServlet extends BaseServlet{ protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建和获取Session会话对象 HttpSession session = req.getSession(); //判断 当前session回滚,是否是新创建出来的 boolean isNew = session.isNew(); //获取session会话的唯一标识 id String id = session.getId(); resp.getWriter().write("得到的Session,它的id是:"+id+"<br/>"); resp.getWriter().write("这个Session是否是新创建的:"+isNew+"<br/>"); } /** * 在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); } }
修改 session.html
<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Session</title> <base href="http://localhost:8080/13_cookie_session/"> <style type="text/css"> ul li{ list-style:none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="..."></iframe> <div style="..."> <ul> <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li> <li><a href="sessionServlet?action=setAttribute" target="target">session域数据的存储</a></li> <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li> <li>session的存活</li> <li> <ul> <li><a href="" target="target">Session的默认超时及配置</a></li> <li><a href="" target="target">session3秒超时销毁</a></li> <li><a href="" target="target">Session马上销毁</a></li> </ul> </li> <li><a href="" target="target">浏览器和Session绑定的原理</a></li> </ul> </div> </body> </html>
结果
l)Session 生命周期控制
Session的默认超时及配置
public void setMaxInactiveInterval(int interval) 设置Session的超时时间(以秒为单位),超过指定的时长,Session就会被销毁。
值为正数时候,设定Session的超时时长
负数表示用不超时(极少使用)
public int getMaxInactiveInterval(int interval) 设置Session的超时时间。
public void invalidate() 让当前Session会话马上超时无效。
Session的默认超时时长是多少?
Session的默认超时时长是:1800秒(30分钟)
因为在Tomcat服务区器中默认有以下的配置,它就表示配置了当前Tomcat服务器下所有的Session超时配置默认时长为:30分钟。
<session-config> <session-timeout>30</session-timeout> </session-config>
修改 session.html
<!DocTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//en" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="pragma" content="no-cache" /> <meta http-equiv="cache-control" content="no-cache"/> <meta http-equiv="Expires" content="0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Session</title> <base href="http://localhost:8080/13_cookie_session/"> <style type="text/css"> ul li{ list-style:none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="..."></iframe> <div style="..."> <ul> <li><a href="sessionServlet?action=createOrGetSession" target="target">Session的创建和获取(id号、是否为新创建)</a></li> <li><a href="sessionServlet?action=setAttribute" target="target">session域数据的存储</a></li> <li><a href="sessionServlet?action=getAttribute" target="target">Session域数据的获取</a></li> <li>session的存活</li> <li> <ul> <li><a href="sessionServlet?action=defaultLife" target="target">Session的默认超时及配置</a></li> <li><a href="" target="target">session3秒超时销毁</a></li> <li><a href="" target="target">Session马上销毁</a></li> </ul> </li> <li><a href="" target="target">浏览器和Session绑定的原理</a></li> </ul> </div> </body> </html>
修改 SessionServlet
package com.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class SessionServlet extends BaseServlet{ protected void createOrGetSession(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //创建和获取Session会话对象 HttpSession session = req.getSession(); //判断 当前session回滚,是否是新创建出来的 boolean isNew = session.isNew(); //获取session会话的唯一标识 id String id = session.getId(); resp.getWriter().write("得到的Session,它的id是:"+id+"<br/>"); resp.getWriter().write("这个Session是否是新创建的:"+isNew+"<br/>"); } /** * 在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); } protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取了Session的默认超时时长 int maxInactiveInterval = req.getSession().getMaxInactiveInterval(); resp.getWriter().write("Session的默认超时时长是:"+maxInactiveInterval+"秒"); } }