Session会话_实现购物车功能
本篇博客记录Javaweb后端的会话技术Session的功能。
1.Session API:
long getCreationTime();【获取Session被创建时间】
String getId();【获取Session的id】
long getLastAccessedTime();【返回Session最后活跃的时间】
ServletContext getServletContext();【获取ServletContext对象】
void setMaxInactiveInterval(int var1);【设置Session超时时间】
int getMaxInactiveInterval();【获取Session超时时间】
Object getAttribute(String var1);【获取Session属性】
Enumeration getAttributeNames();【获取Session所有的属性名】
void setAttribute(String var1, Object var2);【设置Session属性】
void removeAttribute(String var1);【移除Session属性】
void invalidate();【销毁该Session】
boolean isNew();【该Session是否为新的】
2.测试项目:
此项目用于测试Session的功能,用到了Map集合与Set集合
用到了两个界面:1.表格界面 2.购物车界面(无UI优化)
第一个界面:
index.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<table>
<tr>
<td>书号</td>
<td>书名</td>
<td>价格</td>
<td>数量</td>
<td>操作</td>
</tr>
<tr>
<td>1</td>
<td>web</td>
<td>38</td>
<td>10</td>
<td><a href = "AddServlet?name=web">加入购物车</a></td>
</tr>
<tr>
<td>2</td>
<td>java</td>
<td>40</td>
<td>12</td>
<td><a href = "AddServlet?name=java">加入购物车</a></td>
</tr>
</table>
</body>
</html>
第二个界面:
cart.jsp
<%@page import="java.util.Map"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
Map<String,Integer> map = (Map<String,Integer>) session.getAttribute("cart"); // jsp照样要导包
if(map != null){
for(String key:map.keySet()){ // String key -> 遍历放入set集合的map夫妻值<key,value>
int value = map.get(key); // 返回key所匹配的值
%>
名称:<%=key %> 数量<%=value %><br>
<% }
}
%>
</body>
</html>
使用Map集合来存放购物车中的键值(商品名与数量)
Map<K,V> get()返回指定键K所带的值V put()将指定的值V与指定键K关联
使用put方法时,若指定的键(key)在集合中存在,则返回值为集合中键对应的值(该值为替换前的值),并把指定键所对应的值,替换成指定的新值。KeySet():
将Map中所有的键存入到set集合中。因为set具备迭代器。所有可以迭代方式取出所有的键,再根据get方法。获取每一个键对应的值。 keySet():迭代后只能通过get()取key
PS:Map集合与String key:map.keySet()参考下面文章回顾
continue
写两页Servlet代码:1.AddServlet 2.ClearServlet
1.AddServlet.java
package cn.edu.xit;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class AddServlet
*/
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("utf-8"); // 请求的中文乱码问题
response.setContentType("text/html;charset=utf-8"); // 输出的中文乱码问题
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
String name = request.getParameter("name"); //从jsp页面得到name:web or java
System.out.println(name);
// 1.获取购物车cart
Map<String,Integer> map = (Map<String,Integer>) session.getAttribute("cart");
if(map == null){
// 若空,初始化购物车
map = new HashMap<String,Integer>();
session.setAttribute("cart", map); // 设置一个关键词和关键值,把map<key,value>添加进session
}
if(map.containsKey(name)){
map.put(name, map.get(name)+1);
}else{
map.put(name, 1);
}
out.print("<a href = 'index.jsp'>继续购买</a><br/>");
out.print("<a href = 'cart.jsp'>返回购物车</a><br/>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
本页代码中,从index.jsp中获取name的值,再获取cart购物车的信息进行操作。
2.ClearServlet
package cn.edu.xit;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ClearServlet
*/
@WebServlet("/ClearServlet")
public class ClearServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ClearServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
HttpSession session = request.getSession();
session.invalidate(); // 使会话失效,清空购物车
response.sendRedirect("cart.jsp"); //要求访问购物车,查看清空结果
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
本页代码的功能为清空购物车。
项目为课上老师提供。
Session参考文章:
上一篇: 「NOIP2016」蚯蚓
下一篇: 【NOIP模拟赛】绿洲