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创建成功");
}
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
Cookie iWantCookie = CookieUtils.findCookie("key1", cookies);
// 如果不等于null,说明赋过值,也就是找到了需要的Cookie
if (iWantCookie != null) {
resp.getWriter().write("找到了需要的Cookie");
}
}
protected void setAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().setAttribute("key1", "value1"); resp.getWriter().write("已经往Session中保存了数据"); } protected void getAttribute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object attribute = req.getSession().getAttribute("key1"); resp.getWriter().write("从Session中获取出key1的数据是:" + attribute); }
<session-config> <session-timeout>30</session-timeout> </session-config>
<!--表示当前 web 工程。创建出来 的所有 Session 默认是 20 分钟 超时时长--> <session-config> <session-timeout>20</session-timeout> </session-config>
protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 先获取Session对象 HttpSession session = req.getSession(); // 设置当前Session3秒后超时 session.setMaxInactiveInterval(3); resp.getWriter().write("当前Session已经设置为3秒后超时"); }
protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 先获取Session对象 HttpSession session = req.getSession(); // 让Session会话马上超时 session.invalidate(); resp.getWriter().write("Session已经设置为超时(无效)"); }
1.目录结构
2.CookieServlet类
package com.atguigu.servlet; import com.atguigu.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 { /** * 创建Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ 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创建成功"); } /** * 获取Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ 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 Cookie iWantCookie = CookieUtils.findCookie("key1", cookies); // 如果不等于null,说明赋过值,也就是找到了需要的Cookie if (iWantCookie != null) { resp.getWriter().write("找到了需要的Cookie"); } } /** * 修改Cookie * @param req * @param resp * @throws ServletException * @throws IOException */ 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); //方案二: //1、先查找到需要修改的Cookie对象 Cookie cookie = CookieUtils.findCookie("key4", req.getCookies()); if (cookie != null) { //2、调用setValue()方法赋于新的Cookie值。 cookie.setValue("newValue4"); //3、调用response.addCookie()通知客户端保存修改 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); } /** * 马上删除一个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已经被删除"); } } /** * 设置存活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"); } 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"); } }
3.BaseServlet类
package com.atguigu.servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.lang.reflect.Method; public abstract class BaseServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 解决post请求中文乱码问题 // 一定要在获取请求参数之前调用才有效 req.setCharacterEncoding("UTF-8"); // 解决响应中文乱码问题 resp.setContentType("text/html; charset=UTF-8"); String action = req.getParameter("action"); try { // 获取action业务鉴别字符串,获取相应的业务 方法反射对象 Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class); // System.out.println(method); // 调用目标业务 方法 method.invoke(this, req, resp); } catch (Exception e) { e.printStackTrace(); } } }
4.LoginServlet类
package com.atguigu.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("登录 失败"); } } }
5.CookieUtils类
package com.atguigu.util; import javax.servlet.http.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; } }
6.web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <servlet> <servlet-name>CookieServlet</servlet-name> <servlet-class>com.atguigu.servlet.CookieServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CookieServlet</servlet-name> <url-pattern>/cookieServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.atguigu.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/loginServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>SessionServlet</servlet-name> <servlet-class>com.atguigu.servlet.SessionServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>SessionServlet</servlet-name> <url-pattern>/sessionServlet</url-pattern> </servlet-mapping> <!--表示当前web工程。创建出来 的所有Session默认是20分钟 超时时长--> <session-config> <session-timeout>20</session-timeout> </session-config> </web-app>
7.cookie.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>Cookie</title> <base href="http://localhost:8080/cookie_session/"> <style type="text/css"> ul li { list-style: none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="float: left;"></iframe> <div style="float: left;"> <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>
8.login.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2020/2/10 Time: 11:34 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/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>
9.SessionServlet类
package com.atguigu.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 { /** * 往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中保存了数据"); } protected void defaultLife(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 获取了Session的默认超时时长 int maxInactiveInterval = req.getSession().getMaxInactiveInterval(); resp.getWriter().write("Session的默认超时时长为:" + maxInactiveInterval + " 秒 "); } protected void life3(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 先获取Session对象 HttpSession session = req.getSession(); // 设置当前Session3秒后超时 session.setMaxInactiveInterval(3); resp.getWriter().write("当前Session已经设置为3秒后超时"); } protected void deleteNow(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 先获取Session对象 HttpSession session = req.getSession(); // 让Session会话马上超时 session.invalidate(); 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 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 /> "); } }
10. 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/cookie_session/"> <style type="text/css"> ul li { list-style: none; } </style> </head> <body> <iframe name="target" width="500" height="500" style="float: left;"></iframe> <div style="float: left;"> <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="sessionServlet?action=life3" target="target">Session3秒超时销毁</a></li> <li><a href="sessionServlet?action=deleteNow" target="target">Session马上销毁</a></li> </ul> </li> <li><a href="" target="target">浏览器和Session绑定的原理</a></li> </ul> </div> </body> </html>
原文:https://www.cnblogs.com/wuwuyong/p/14855893.html