请选择 进入手机版 | 继续访问电脑版
我的账户
星点互联

自媒体资讯干货

亲爱的游客,欢迎!

已有账号,请

如尚未注册?

第74节:Java中的Cookie和Session

2019-2-18 11:40

第74节:Java中的Cookie和Session第74节:第74节:Java中的Cookie和SessionServletContext: 什么是ServletContext,有什么用哦,怎么用呢?

第74节:Java中的Cookie和Session

标题图

第74节:第74节:Java中的Cookie和Session

ServletContext:

什么是ServletContext,有什么用哦,怎么用呢?

启动服务器后,会给每个应用程序创建一个ServletContext,并且这个ServletContext对象只有一个。可以用于获取全局参数,工程下的资源,和存取数据,共享数据。

例子,如何获取全局参数,如何获取工程下的资源,如何进行存取数据,用例子代码进行展示。

getServletContext().getInitParams();getServletConfig().getInitParams();

getServletContext().getRealPath()
getServletContext().getReasourceAsStream()

InputStream is = getClass().getClassLoader().getReasourceAsStream();

相对路径和绝对路径

getServletContext().setAttribute()

getServletContext().getAttribute()

获取登录成功次数

HttpServletRequest:

请求对象,用于封装客户端提交过来的数据或者信息。
可以获取头信息,提交过来的数据:
`request.getParameter("name"); // dashucoding url连接拼接

中文乱码情况

HttpServletResponse:

响应对象,服务器要返回给客户端的数据

跳转页面:
response.setStatus(302);

response.setHeader("Location","success.html");

文件下载:输出流和输入流的对接

下载中文名字的资源:

效果

效果

// index.html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> 默认servlet去下载<br> <a href="download/aa.jpg">aa.jpg</a><br> <a href="download/bb.txt">bb.txt</a><br> <a href="download/cc.rar">cc.rar</a><br> <br>手动下载<br> <a href="Demo01?filename=aa.jpg">aa.jpg</a><br> <a href="Demo01?filename=bb.txt">bb.txt</a><br> <a href="Demo01?filename=cc.rar">cc.rar</a><br> <a href="Demo01?filename=达叔.png">达叔.png</a><br> </body> </html> // Demo01.java package com.dashucoding.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 获取要下载的文件名字 String fileName = request.getParameter("filename"); // 获取这个文件在tomcat里面的绝对路径地址 String path = getServletContext().getRealPath("download/"+fileName); // 用于用户下载 response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 转化成输入流 InputStream is = new FileInputStream(path); OutputStream os = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while( (len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.close(); is.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

浏览器

// Demo01.java package com.dashucoding.servlet; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // 获取要下载的文件名字 String fileName = request.getParameter("filename"); // get请求有中文 //byte[] bytes = fileName.getBytes("ISO-8859-1"); //new String(bytes, "UTF-8"); fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8"); System.out.println("fileName="+fileName); // 获取这个文件在tomcat里面的绝对路径地址 String path = getServletContext().getRealPath("download/"+fileName); // 对中文的名字进行编码处理 // 获取来访客户端的类型 String clientType = request.getHeader("User-Agent"); if (clientType.contains("Firefox")) { fileName = DownLoadUtil.base64EncodeFileName(fileName); }else { fileName = URLEncoder.encode(fileName, "UTF-8"); } // 用于用户下载 response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 转化成输入流 InputStream is = new FileInputStream(path); OutputStream os = response.getOutputStream(); int len = 0; byte[] buffer = new byte[1024]; while( (len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.close(); is.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } // DownLoadUtil package com.dashucoding.servlet; import java.io.UnsupportedEncodingException; import sun.misc.BASE64Encoder; public class DownLoadUtil { public static String base64EncodeFileName(String fileName) { BASE64Encoder base64Encoder = new BASE64Encoder(); try { return "=?UTF-8?B?" + new String(base64Encoder.encode(fileName .getBytes("UTF-8"))) + "?="; } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RuntimeException(e); } } }

效果

登录

效果

// LoginServlet package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // public void setContextType(String type) // 设置将发送到客户端的响应的内容类型,如果该响应尚未提交,给定内容类型可能包含字符编码规范,例如 // text/html;charseet=UTF-8,如果在调用 getWriter之前调用此方法,则只根据给定内容类型设置响应的字符编码 response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)) { response.getWriter().write("登录成功"); }else { response.getWriter().write("登录失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } // web <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>RequestRedirctionDemo</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.dashucoding.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app> // login <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="login"> 账号: <input type="text" name="username"/><br> 密码: <input type="text" name="password"/><br> <input type="submit" value="登录"/><br> </form> </body> </html>

效果

效果

效果

// LoginServlet package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // public void setContextType(String type) // 设置将发送到客户端的响应的内容类型,如果该响应尚未提交,给定内容类型可能包含字符编码规范,例如 // text/html;charseet=UTF-8,如果在调用 getWriter之前调用此方法,则只根据给定内容类型设置响应的字符编码 response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)) { // response.getWriter().write("登录成功"); response.setStatus(302); response.setHeader("Location", "login_success.html"); }else { response.getWriter().write("登录失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>登录成功!!!</h1> </body> </html>

效果

重定向

package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub // public void setContextType(String type) // 设置将发送到客户端的响应的内容类型,如果该响应尚未提交,给定内容类型可能包含字符编码规范,例如 // text/html;charseet=UTF-8,如果在调用 getWriter之前调用此方法,则只根据给定内容类型设置响应的字符编码 response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)) { // response.getWriter().write("登录成功"); /*response.setStatus(302); response.setHeader("Location", "login_success.html");*/ // 重定向写法,重新定位方向 // response.sendRedirect("login_success.html"); // 请求转发的写法 request.getRequestDispatcher("login_success.html").forward(request, response); }else { response.getWriter().write("登录失败"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

用于自动登录,浏览记录等,是服务器给客户端的.

Cookie cookie = new Cookie("a","b"); // 响应 response.addCookie(cookie);

获取Cookie

package com.dashucoding.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; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Cookie的简单使用。 //cookie 发送给客户端,并且保存在客户端上的一份小数据 response.setContentType("text/html;charset=utf-8"); //发送cookie给客户端 Cookie cookie = new Cookie("aa", "bb"); //给响应,添加一个cookie response.addCookie(cookie); response.getWriter().write("请求成功了..."); //获取客户端带过来的cookie Cookie[] cookies = request.getCookies(); if(cookies != null){ for (Cookie c : cookies) { String cookieName = c.getName(); String cookieValue = c.getValue(); System.out.println(cookieName + " = "+ cookieValue); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

Cookie是一份小数据,是服务器给客户端,存储在客户端上的一份小数据.

http请求是无状态的.

在响应的时候添加Cookie

Cookie cookie = new Cookie("name", "value"); // 添加cookie response.addCookie(cookie);

在客户端信息里,响应头中多了Set-Cookie

获取客户端带来的Cookie

Cookie[] cookies = request.getCookies(); if(cookies != null){ for(Cookie c : cookies){ String cookieName = c.getName(); String cookieValue = c.getValue(); System.out.println(cookieName + " = " + cookieValue); } }

cookie过期

public int getMaxAge()
返回以秒为单位指定的cookie的最大生存时间.

public void setMaxAge(int expiry)
设置cookie的最大生存时间,以秒为单位.

如何显示上次登录时间

可以进行判断账号密码,如果上次有登录过,那么显示上次的登录时间.这里分两种情况,获取带过来的cookie进行判断,第一种是没有cookie的,第一次登录,输出登录成功或者失败,然后给客户端添加cookie,new Cookie(),第二种的登录过的,还是要输出登录成功或者是失败,获取以前的cookie.时间戳要重置怎么理解?

package com.dashucoding.servlet; import java.io.IOException; 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 com.dashucoding.util.CookieUtil; /** * Servlet implementation class Demo03 */ public class Demo03 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); String userName = request.getParameter("username"); String password = request.getParameter("password"); if("admin".equals(userName) && "123".equals(password)){ //获取cookie last-name --- > Cookie [] cookies = request.getCookies(); //从数组里面找出我们想要的cookie Cookie cookie = CookieUtil.findCookie(cookies, "last"); //是第一次登录,没有cookie if(cookie == null){ Cookie c = new Cookie("last", System.currentTimeMillis()+""); c.setMaxAge(60*60); //一个小时 response.addCookie(c); response.getWriter().write("欢迎您, "+userName); }else{ //1. 去以前的cookie第二次登录,有cookie long lastVisitTime = Long.parseLong(cookie.getValue()); //2. 输出到界面, response.getWriter().write("欢迎您, "+userName +",上次来访时间是:"+new Date(lastVisitTime)); //3. 重置登录的时间 cookie.setValue(System.currentTimeMillis()+""); response.addCookie(cookie); } }else{ response.getWriter().write("登陆失败 "); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

如何显示商品浏览记录

获取提交过来的id,把id放入到cookie里,跳转界面.

servlet?id=1; servlet?id=2; 获取cookie 1 1#2 setValue("1#2");

jsp

效果

效果

// index.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <br>---------1------------<br> <%! int a = 123; %> <br>---------2------------<br> <% int b = 123456; %> <br>---------3------------<br> <%=a %><br> <%=b %> </body> </html>

浏览记录

package com.dashucoding.util; import javax.servlet.http.Cookie; public class CookieUtil { /** * 从一个cookie数组中找到具体我们想要的cookie对象 * @param cookies * @param name * @return */ public static Cookie findCookie(Cookie[] cookies , String name){ if(cookies != null){ for (Cookie cookie : cookies) { if(name.equals(cookie.getName())){ return cookie; } } } return null; } } <!-- 显示浏览记录 --> <% Cookie[] cookies = request.getCookies(); Cookie cookie = CookieUtil.findCookie(cookies, "history"); // 如果cookie是空,表明没有浏览商品 if(cookie == null){ %> <h2> 您还没有浏览任何商品! </h2> <% }else{ // 不是空,表明有浏览记录 String[] ids = cookie.getValue().split("#"); for(String id : ids){ %> <li style="width: 150px;height: 216;text-align: center;"><img src="products/1/cs1000<%=id %>.jpg" width="130px" height="130px" /></li> <% } } %> package com.dashucoding.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; import com.dashucoding.util.CookieUtil; public class ProductInfoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getParameter("id"); Cookie[] cookies = request.getCookies(); Cookie cookie = CookieUtil.findCookie(cookies, "history"); if (cookie==null) { Cookie cook = new Cookie("history", id); cook.setMaxAge(60*60*24*7); response.addCookie(cook); }else{ String id2 = cookie.getValue(); cookie.setValue(id+"#"+id2); cookie.setMaxAge(60*60*24*7); response.addCookie(cookie); } response.sendRedirect("product_info.htm"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

清除浏览记录

清除cookie

package com.dashucoding.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; /** * Servlet implementation class ClearHistory */ public class ClearHistory extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 清除cookie Cookie c = new Cookie("history", ""); c.setMaxAge(0); // c.setPath("/demo1"); response.addCookie(c); response.sendRedirect("product_list.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

获取cookie,添加cookie

request.getCookie(); response.addCookie();

Cookie分类

cookie.setMaxAge(0); // 删除 cookie.setMaxAge(100); // 100秒

Cloneable

创建一个cookie,cookieservlet发送到web浏览器中的少量信息,这些信息是由浏览器保存,然后发送回到服务器中.

cookie的值是唯一标识客户端的,可以用于cookie会话管理.一个cookie拥有一个名,值,可以有一些可选属性.但又cookie也存在一些问题.浏览器支持每个web服务器又20个cookie,共有300个cookie,每个限制在4KB.

安全隐患,大小与个数限制.

Session

会话,Session是基于Cookie的一种会话机制.Cookie是服务器返回一部分小数据在客户端,存放在客户端上.

Session是把数据存放在服务端.

interface httpsession

public interface httpSession

常用的方法

package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class Demo01 */ public class Demo01 extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(); // 得到会话ID session.getId(); // 存值 session.setAttribute(name, value); // 取值 session.getAttribute(name); // 移植 session.removeAttribute(name); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

效果

效果

// web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>SessionDemo02</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>LoginServlet</display-name> <servlet-name>LoginServlet</servlet-name> <servlet-class>com.dashucoding.servlet.LoginServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>LoginServlet</servlet-name> <url-pattern>/login</url-pattern> </servlet-mapping> </web-app> // LoginServlet package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); response.getWriter().write("收到请求了"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } // login.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> </head> <body> <form action="login"> 账号: <input type="text" name="username"/><br> 密码: <input type="text" name="password"/><br> <input type="submit" value="登录"/><br> </form> </body> </html>

session创建与销毁

创建 request.getSession(); 销毁 Redis session 存放在服务器内存中的数据 session关闭服务器销毁 session会话时间过期 // 可以改的 conf\web.xml 有效期30分钟 <session-config> <session-timeout>30</session-timeout> </session-config> package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class LoginServlet */ public class LoginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); String sessionid = request.getSession().getId(); System.out.println("sessionid="+sessionid); // cookid id -> sessionid response.getWriter().write("收到请求了"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }

session分析

商品列表添加商品,点击商品添加到购物车,到servlet.

获取点击商品标识id,存储到购物车,跳转界面.

判断购物车是否有商品,有数量加1,没有数量等于1.

购物车

效果

效果

效果

package com.dashucoding.servlet; import java.io.IOException; import java.util.LinkedHashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class CarServlet */ public class CarServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/html;charset=utf-8"); // 获取添加到购物车的商品id int id = Integer.parseInt(request.getParameter("id")); // cat dog big pig String [] names = {"cat","dog","big","pig"}; // 取到id对应商品 String name = names[id]; // 获取购物车存放东西的session // 把一个map 对象存放到session里面去,保证只有一次 Map<String, Integer> map = (Map<String, Integer>) request.getSession().getAttribute("cat"); if(map == null) { // value -> map map = new LinkedHashMap<String, Integer>(); request.getSession().setAttribute("cat", map); } // 判断购物车里有没有该商品 if(map.containsKey(name)) { // 在原来基础上 +1 map.put(name, map.get(name)+1); }else { map.put(name, 1); } response.getWriter().write("<a href='product_list.jsp'><h2>继续购物</h2></a>"); response.getWriter().write("<a href='cart.jsp'><h2>去购物车结算</h2></a>"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <a href="CarServlet?id=0"><h2>cat</h2></a><br> <a href="CarServlet?id=1"><h2>dog</h2></a><br> <a href="CarServlet?id=2"><h2>big</h2></a><br> <a href="CarServlet?id=3"><h2>pig</h2></a><br> </body> </html>

效果

效果

// cart.jsp <%@page import="java.util.Map"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> 您的购物车商品如下: <% // 获取到map Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cat"); // 遍历 if(map != null){ for(String key : map.keySet()){ int value = map.get(key); // key:商品名称 value:商品名称 // <h3>名称: 数量: </h3> %> <h3>名称: <%=key %> 数量: <%=value %></h3><br> <% } } %> </body> </html>

效果

package com.dashucoding.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * Servlet implementation class ClearCartServlet */ public class ClearCartServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub HttpSession session = request.getSession(); // cat购物车 session.removeAttribute("cat"); response.sendRedirect("cart.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } } <%@page import="java.util.Map"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> 您的购物车商品如下: <% // 获取到map Map<String,Integer> map = (Map<String,Integer>)session.getAttribute("cat"); // 遍历 if(map != null){ for(String key : map.keySet()){ int value = map.get(key); // key:商品名称 value:商品名称 // <h3>名称: 数量: </h3> %> <h3>名称: <%=key %> 数量: <%=value %></h3><br> <% } } %> <a href="ClearCartServlet"><h4>清空购物车</h4></a> </body> </html>

效果

public void invalidate() 使用,会话无效,取消对任何绑定到它的对象. // 强制干掉会话 // session.invalidate();

小结

cookie和session

Cookie
获取上一次访问时间,获取浏览记录,数据存放在客户端

Session
会话技术,数据存放在服务端

setAttribute 存放数据 getAttribute 取数据 removeAttribute 移除 getSessionId() 获取会话id invalidate() 让会话失效 response.addCookie(new Cookie()) request.getSession 创建

如果看了觉得不错

点赞!转发!

达叔小生:往后余生,唯独有你
You and me, we are family !
90后帅气小伙,良好的开发习惯;独立思考的能力;主动并且善于沟通
简书博客: 达叔小生
https://www.jianshu.com/u/c785ece603d1

结语

  • 下面我将继续对 其他知识 深入讲解 ,有兴趣可以继续关注
  • 小礼物走一走 or 点赞

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

这个人很懒,什么也没留下...
粉丝1 阅读402 回复0
上一篇:
java中的static关键字 学习总结发布时间:2019-02-18
下一篇:
java基础(二)-----java的三大特性之继承发布时间:2019-02-18
推荐资讯
精选资讯
阅读排行
精选案例展示
关注我们
星点互联关注时代变迁

客服电话:400-234-9000

客服邮箱:vip@neoconex.com

周一至周五 9:00-18:00

公司地址:威高广场迪尚大厦海景写字楼A座1988

Powered by Discuz!X3.4@ 2017-2018 蓝盘下载 |Archiver|手机版|小黑屋|( 豫ICP备17005739号-3 )