第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 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
,cookie
是servlet
发送到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 点赞
第74节:Java中的Cookie和Session的更多相关文章
- 第77节:Java中的事务和数据库连接池和DBUtiles
第77节:Java中的事务和数据库连接池和DBUtiles 前言 看哭你,字数:8803,承蒙关照,谢谢朋友点赞! 事务 Transaction事务,什么是事务,事务是包含一组操作,这组操作里面包含许 ...
- 第83节:Java中的学生管理系统分页功能
第83节:Java中的学生管理系统分页功能 分页功能一般可以做成两种,一种是物理分页,另一种是逻辑分页.这两种功能是有各自的特点的,物理分页是查询的时候,对数据库进行访问,只是查一页数据就进行返回,其 ...
- 第82节:Java中的学生管理系统
第82节:Java中的学生管理系统 学生管理系统的删除功能 删除,点击超链接,点击弹出对话框式是否进行删除,如果确定,就删除,超链接执行的是js方法,在js里访问,跳转servlet,,servlet ...
- 第80节:Java中的MVC设计模式
第80节:Java中的MVC设计模式 前言 了解java中的mvc模式.复习以及回顾! 事务,设置自动连接提交关闭. setAutoCommit(false); conn.commit(); conn ...
- 第79节:Java中一些要点
第79节:Java中一些要点 前言 一些知识点忘了没,可以通过一个点引出什么内容呢?做出自己的思维导图,看看自己到了哪一步了呢 内容 如果有人问jre,jdk,jvm是什么,你怎么回答呢? jre的英 ...
- 第78节:Java中的网络编程(上)
第78节:Java中的网络编程(上) 前言 网络编程涉及ip,端口,协议,tcp和udp的了解,和对socket通信的网络细节. 网络编程 OSI开放系统互连 网络编程指IO加网络 TCP/IP模型: ...
- 第76节:Java中的基础知识
第76节:Java中的基础知识 设置环境,安装操作系统,安装备份,就是镜像,jdk配置环境,eclipse下载解压即可使用,下载tomcat 折佣动态代理解决网站的字符集编码问题 使用request. ...
- 第71节:Java中HTTP和Servlet
第71节:Java中HTTP和Servlet 前言 哭着也要看完!!!字数: 学习xml和TomCat 会写xml,看懂xml 解析对象 SAXReader reader = new SAXReade ...
- 第70节:Java中xml和tomcat
第70节:Java中xml和tomcat 前言: 哭着也要看完,字数: jdbc crud - statement dao java.sql.Driver The interface that eve ...
随机推荐
- PHP整理--PHP语句流程
PHP跟JS一样是从上往下的执行语句:同样的PHP也有if语句.循环.数组和函数. 一.条件语句 if..else... swich (1)多条if语句 $name=30; if($nam ...
- springboot使用Redis,监听Redis键过期的事件设置与使用代码
我使用的是Windows下的Redis服务,所以一下Redis设置都是在Windows平台进行. 1.修改Redis配置文件 1.1:Windows下的Redis存在两个配置文件 修改带有servic ...
- Connection failed Flowsocketconnector Failed to connect to target addressWindows error10061:由于目标计算机积极拒绝,无法连接
使用bitbise时报上面错误 : 解决方法 :卸载软件并删除相关的文件 (包含bitvise 及注册表中的文件)重新安装后能连接
- Codeforces 524 解题报告
打的很快乐的一次比赛hiahiahia, 才A掉4题rating就涨了100+ 距离比赛\(3\)天了, 由于博主实在太颓, 又补掉了\(E\)题, 到现在才发解题报告 A. 语法题, 读入输出就行了 ...
- identityserver4 代码系列
链接:https://pan.baidu.com/s/1ePLwUxGpIPObwA8nnfDT9w 提取码:gr0x
- 《修炼之道:.NET开发要点精讲》读书笔记(一)
CLR 公共语言运行库 没有CLR的存在,就不能讲该中间件转换成对应操作系统中的机器指令. 程序集是非完全编译的产物,它兼备了源代码和本地代码的特性,是一种介于源代码和本地代码之间的独立存在的一种数据 ...
- 第二阶段第八次spring会议
昨天我对软件进行了植物网站的添加. 今天我将对软件进行宠物信息的添加. 清屏功能 private void button5_Click(object sender, EventArgs e) { te ...
- [Java]异常在项目中的使用
自己经历过的两个项目都有自定义异常,网上找了项目中自定义异常的例子: https://blog.csdn.net/aiyaya_/article/details/78989226. 这个例子基本上来说 ...
- win10下使用powershell来获取文件MD5的命令
Get-FileHash 文件路径 -Algorithm MD5| Format-List
- flume1.4.0源码结构剖析
flume基本思想: source负责收集数据,channel负责缓存数据,sink负责消费channel中的数据,具体使用方式这里不赘述 生命周期管理: 生命周期相关代码在flume-ng-core ...