基于session对象实现购物车应用

样例跳转:样例六<–点此跳转
(ps.这是完全照搬慕课实训里的代码,感觉这种实现方式特苯,特臃肿。)
简易版:
login.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/22
Time: 21:50
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录界面</title>
</head>
<body>
<p>欢迎来到本网站,请输入您的性名</p>
<form method="get" action="main.jsp">
<input name="userName" type="test" size="24"><br>
<input type="submit" value="登录">
</form>
</body>
</html>
main.jsp
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/22
Time: 22:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>主界面</title>
</head>
<body>
<%
String username1=(String)session.getAttribute("userName1")
if(username1==null){
request.setCharacterEncoding("UTF-8")
String username=request.getParameter("userName")
if(username==null)
response.sendRedirect("login.jsp")
else {
session.setAttribute("userName1",username)
out.println(username+"!欢迎您来到主页面,请选择您要购买的商品:")
}
}
else{
out.println(username1+"!欢迎您来到主页面,请选择您要购买的商品:")
}
%>
<form action="shoppingCart.jsp" method="post">
<p>商品信息</p>
<table border="1">
<tr>
<td><input type="checkbox" name="choice" value="U盘"></td>
<td>U盘</td>
</tr>
<tr>
<td><input type="checkbox" name="choice" value="移动硬盘"></td>
<td>移动硬盘</td>
</tr>
<tr>
<td><input type="checkbox" name="choice" value="鼠标"></td>
<td>鼠标</td>
</tr>
<tr>
<td><input type="checkbox" name="choice" value="键盘"></td>
<td>键盘</td>
</tr>
</table>
<input type="submit" value="增加购物车">
</form>
</body>
</html>
shoppingCart.jsp
<%@ page import="java.util.Vector" %><%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2020/4/22
Time: 22:36
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>购物车</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8")
String username1=(String)session.getAttribute("userName1")
Vector goods=(Vector)session.getAttribute("shoppingCart")
if(goods==null)
goods=new Vector()
String[] g=request.getParameterValues("choice")
if(g!=null){
for(int i=0i<g.lengthi++)
goods.add(g[i])
}
session.setAttribute("shoppingCart",goods)
out.println("<br>您的性名:"+username1)
out.println("<br>购物车中的商品:<br>")
for(int j=0j<goods.size()j++)
out.print(goods.get(j)+"<br>")
%>
<p><a href="main.jsp">返回主页面继续购物</a> </p>
</body>
</html>








Comments NOTHING