项目很小,就几个界面,主要是通过servlet作为中间层进行请求的处理。
实现了商品添加到购物车,购物车内的商品查看,商品数量的更改,结账时生成订单。
一‘、数据库设计:
--用户表
create table shop.userinfo(
userid number(4) primary key,
logname varchar2(20) unique not null,
keyword varchar2(20) check(length(keyword)>=3) not null
);
--商品表
create table shop.commodity(
cid varchar(10) primary key,
cname varchar(50) not null,
cutil varchar2(10) not null,
cprice number(9,2) check(cprice>=0) not null,
cimg varchar2(50) default'../Images/moren.gif' not null
);
--订单表
create table shop.orderinfo(
orderid varchar2(30) primary key,
userid number(4) references shop.userinfo(userid)not null,
odate date default sysdate not null
);
alter table shop.orderinfo add(
ostate number(2) default 1 not null
)
--订单明细表
create table shop.orderlist(
olid varchar(50) primary key,
cid varchar(10) references shop.commodity(cid) not null,
orderid varchar2(30) references shop.orderinfo(orderid) not null,
comnum number(5) check(comnum>0) not null
);
--=========================================================================
insert into shop.userinfo values(1,'sdd','sdd');
insert into shop.userinfo values(2,'tom','tom');
insert into shop.userinfo values(3,'111','111');
insert into shop.userinfo values(4,'222','222');
insert into shop.commodity values('DR1','百事可乐','罐',2,'moren.gif');
insert into shop.commodity values('DR2','康师傅绿茶','瓶',2.5,'moren.gif');
insert into shop.commodity values('COM1','华硕笔记本','台',4000,'moren.gif');
insert into shop.commodity values('NOOD1','老坛酸菜泡面','包',3,'moren.gif');
insert into shop.commodity values('BOOK1','葵花宝典','本',22222,'moren.gif');
insert into shop.commodity values('ARM1','轩辕剑','柄',55555,'moren.gif');
insert into shop.commodity values('SAD1','时光机','台',66666,'moren.gif');
insert into shop.commodity values('LOVE1','至尊宝的眼泪','滴',77777,'moren.gif');
insert into shop.orderinfo values ('OR201201',1,to_date('2012-07-07','yyyy-MM-dd'));
insert into shop.orderinfo values ('OR201202',2,to_date('2012-08-08','yyyy-MM-dd'));
insert into shop.orderinfo values ('OR201203',3,to_date('2012-09-09','yyyy-MM-dd'));
insert into shop.orderlist values ('OL201201','DR2','OR201201',4);
insert into shop.orderlist values ('OL201202','ARM1','OR201202',1);
insert into shop.orderlist values ('OL201203','SAD1','OR201202',1);
insert into shop.orderlist values ('OL201204','LOVE1','OR201203',1);
commit;
select * from shop.userinfo;
select * from shop.commodity order by cid;
select * from shop.orderinfo;
select * from shop.orderlist;
二、类设计(实体类我就不发了,大家都该知道):
1.连接池:
package com.shop.tool;
import java.beans.PropertyVetoException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DBHelper {
private static ComboPooledDataSource cpds=new ComboPooledDataSource();
//private static OracleDispose od=new OracleDispose("f:/config.properties");
static {
try {
// 驱动器
cpds.setDriverClass("oracle.jdbc.OracleDriver");
// 数据库url
cpds.setJdbcUrl("jdbc:oracle:thin:@127.0.0.1:1521:ORCL");
//cpds.setJdbcUrl(od.jdbcurl);通过properties动态获取文件中存储的jdbcurl
//用户名
cpds.setUser("shop");
//cpds.setUser(od.username);通过properties动态获取文件中存储的用户名称
//密码
cpds.setPassword("sa");
//cpds.setPassword(od.userpwd);通过properties动态获取文件中存储的用户密码
//初始化连接池的大小
cpds.setInitialPoolSize(30);
//最小连接数
cpds.setMinPoolSize(20);
//最大连接数
cpds.setMaxPoolSize(100);
} catch (PropertyVetoException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 用于数据库的链接
* @return 返回Connection
*/
public static Connection getConnection(){
try {
return cpds.getConnection();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 用于关闭数据库的关闭
* @param rs ResultSet对象
* @param st Statement对象
* @param con Connection对象
*/
public static void closeJDBC(ResultSet rs,Statement st,Connection con){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(st!=null){
try {
st.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* 用于获取指定表明的列对应JAVA中的数据类型。
* @param tablename 指定的表名
* @return 列数据类型的数组
*/
public Class[] getTypeOfJava(String tablename){
Connection con=DBHelper.getConnection();
if(con==null){
return null;
}
Statement st=null;
ResultSet rs=null;
Class[] types=null;
try {
st=con.createStatement();
rs=st.executeQuery("select * from "+tablename);
int count=rs.getMetaData().getColumnCount();
types=new Class[count];
for (int i = 0; i < types.length; i++) {
types[i]=Class.forName(rs.getMetaData().getColumnClassName(i+1));
}
return types;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBHelper.closeJDBC(rs, st, con);
}
return null;
}
}
2.抽象管理父类(定义标准,提取共性方法,供子类继承和使用):
package com.shop.manager;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.shop.tool.DBHelper;
import com.sun.corba.se.spi.orbutil.fsm.State;
abstract class Manager {
public abstract boolean insertInfo(Object entity);
public abstract boolean deleteInfo(Object id);
public abstract boolean updateInfo(Object entity);
public abstract Object getAllInfoById(Object id);
public abstract List getAllInfo();
/**
* 根据传入的每页行数返回分页数
* @param tname 要分页的表名
* @param rowcount 每页行数
* @return 分页数
*/
int getPageSize(String tname,int rowcount){
Connection con=DBHelper.getConnection();
if(con==null){
return -1;
}
Statement st=null;
ResultSet rs=null;
try {
st=con.createStatement();
rs=st.executeQuery("select count(*) from "+tname);
int size=-1;
if(rs.next()){
size=rs.getInt(1);
if(size%rowcount==0){
return (size/rowcount);
}
return (size/rowcount)+1;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBHelper.closeJDBC(rs, st, con);
}
return -1;
}
/**
* 用于父类 封装 子类根据对象属性查询的方法
* @param tname 表名
* @param clname 要查询的列名
* @param clvalue 传入的列名的值
* @param cl 用于 指定 实体类 类文件
* @return 查询结果集封装的数据(实体类对象集合)
*/
List getInfoByproperty(String tname,String[] clname,String[] clvalue,Class cl){
String sql="select * from "+tname+" where 0=0 ";
for (int i = 0; i < clname.length; i++) {
sql+=" and "+clname[i]+"=?";
}
return this.getAllInfo(sql, clvalue, cl);
}
/**
* 用于父类 封装 增删改 的方法,以外部传取connection作为连接(可控制事务) 不需要关闭connection
* 本方方多用于批处理(结合其他业务一起进行操作)
* @param con 外部获取的connection连接
* @param sql 操作的sql指令
* @param args 参数数组
* @return
*/
boolean updateDB(Connection con,String sql,String[] args){
//获取操作指令装置,并执行sql(可赋值)
PreparedStatement ps=null;
try {
ps=con.prepareStatement(sql);
if(args!=null&&args.length>0){
for (int i = 0; i < args.length; i++) {
ps.setString(i+1, args[i]);
}
}
return ps.executeUpdate()>0 ? true:false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBHelper.closeJDBC(null, ps, null);
}
return false;
}
/**
* 用于父类 封装 增删改 的方法,直接利用重载进行dml的操作(多用于单独执行)
* @param sql 操作的sql指令
* @param args 参数数组
* @return
*/
boolean updateDB(String sql,String[] args){
Connection con=DBHelper.getConnection();
try {
return updateDB(con, sql, args);
} catch (Exception e) {
// TODO: handle exception
}finally{
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
/**
* 用于父类 封装 查询 的方法,供子类调用。
* @param sql 查询语句(select .......)
* @param args 查询条件值(可以为null——基本查询)
* @param cl 用于 指定 集合中封装的 实体类 类文件
* @return 查询结果集封装的数据(实体类对象集合)
*/
List getAllInfo(String sql,String[] args,Class cl){
//获取连接并判断
Connection con=DBHelper.getConnection();
//Connection con=DB_helper.getInstance().getConnection();
if(con==null){
return null;
}
//获取操作指令装置,并执行sql(可赋值)
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps=con.prepareStatement(sql);
if(args!=null){
for (int i = 0; i < args.length; i++) {
ps.setString(i+1, args[i]);
}
}
rs=ps.executeQuery();
//获取 rs 的源数据,从中得到操作表的 列数
int colcount=rs.getMetaData().getColumnCount();
//准备构造方法所用参数的数组,长度为 表 列数
Object[] canshu=new Object[colcount];
//封装返回值的容器
List list=new ArrayList();
//遍历 所有指定 实体类的构造方法,用 参数数组去获取 实体类 对象(如成功,则列值被封装成 对象 属性值)
Object ob=null;
//封装返回值的容器
while(rs.next()){
//将一行 表的数据 封装到 参数数组中
for (int i = 0; i < canshu.length; i++) {
canshu[i]=rs.getObject(i+1);
//可用于查看 Oracle数据库对应的 java 数据类型
//System.out.println(canshu[i].getClass());
}
//
ob=getObject(cl, canshu);
//如成功,则将封装有属性值的对象,放入 list 集合
if(ob==null){
return null;
}
//如成功,则将封装有属性值的对象,放入 list 集合
list.add(ob);
}
return new ArrayList(list);
} catch (Exception e) {
}finally{
DBHelper.closeJDBC(rs, ps, con);
//DBHelper.closeJDBC(rs, ps, null);
}
return null;
}
/**
* 用于自动封装 行数据成为 指定类对象的方法
* @param cl 传进返回的实体类型
* @param canshu 进行参数匹配的数组
* @return 实体类型
*/
private Object getObject(Class cl,Object[] canshu){
Constructor[] cons=cl.getConstructors();
Object ob=null;
for (int i = 0; i < cons.length; i++) {
try {
ob=cons[i].newInstance(canshu);
return ob;
} catch (Exception e) {
continue;
}
}
return null;
}
}
3.为每一个表设计一个管理类。继承管理父类,实现其抽象方法,并按需求定义自己的方法(这里我只给出用户管理类和订单明细管理类)
①用户管理类:
package com.shop.manager;
import java.util.List;
import com.shop.bean.UserInfoEntity;
public class UserInfoManager extends Manager{
public List<UserInfoEntity> getUserInfoByProPerty(UserInfoEntity user){
return this.getInfoByproperty("shop.userinfo", new String[]{"logname","keyword"}, new String[]{user.getLogname(),user.getKeyword()}, UserInfoEntity.class);
}
@Override
public boolean deleteInfo(Object id) {
String sql="delete from shop.userinfo where userid=?";
String[] args=new String[]{id+""};
return this.updateDB(sql, args);
}
@Override
public List<UserInfoEntity> getAllInfo() {
return this.getAllInfo("select * from shop.userinfo", null, UserInfoEntity.class);
}
@Override
public UserInfoEntity getAllInfoById(Object id) {
String sql="select * from shop.userinfo where userid=?";
String[] args=new String[]{id+""};
List<UserInfoEntity> list=this.getAllInfo(sql, args, UserInfoEntity.class);
return list!=null&&list.size()>0?list.get(0):null;
}
@Override
public boolean insertInfo(Object entity) {
UserInfoEntity user=(UserInfoEntity) entity;
String sql="insert into shop.userinfo values(?,?,?)";
String[] args=new String[]{user.getUserid()+"",user.getLogname(),user.getKeyword()};
return this.updateDB(sql, args);
}
@Override
public boolean updateInfo(Object entity) {
UserInfoEntity user=(UserInfoEntity) entity;
String sql="update shop.userinfo set keyword=? where userid=?";
String[] args=new String[]{user.getKeyword(),user.getUserid()+""};
return this.updateDB(sql, args);
}
}
②订单明细管理类:
package com.shop.manager;
import java.sql.Connection;
import java.util.List;
import com.shop.bean.OrderListEntity;
public class OrderListManager extends Manager{
@Override
public boolean deleteInfo(Object id) {
// TODO Auto-generated method stub
return false;
}
@Override
public List getAllInfo() {
// TODO Auto-generated method stub
return null;
}
@Override
public Object getAllInfoById(Object id) {
// TODO Auto-generated method stub
return null;
}
@Override
public boolean insertInfo(Object entity) {
// TODO Auto-generated method stub
return false;
}
public boolean insertInfo(Connection con,Object entity) {
OrderListEntity ol=(OrderListEntity) entity;
String sql="insert into shop.orderlist values(?,?,?,?)";
String[] args=new String[]{ol.getOlid(),ol.getCommodity().getCid(),ol.getOrder().getOid(),ol.getComnum()+""};
return this.updateDB(con, sql, args);
}
@Override
public boolean updateInfo(Object entity) {
// TODO Auto-generated method stub
return false;
}
}
4.业务操作类供界面使用(BossManager):
package com.shop.boss;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.List;
import com.shop.bean.OrderInfoEntity;
import com.shop.bean.OrderListEntity;
import com.shop.bean.UserInfoEntity;
import com.shop.bean.CommodityEntity;
import com.shop.manager.OrderInfoManager;
import com.shop.manager.OrderListManager;
import com.shop.manager.UserInfoManager;
import com.shop.manager.CommodityManager;
import com.shop.tool.DBHelper;
public class BossManager {
private static UserInfoManager um=new UserInfoManager();
private static CommodityManager cm=new CommodityManager();
private static OrderInfoManager om=new OrderInfoManager();
private static OrderListManager olm=new OrderListManager();
public static OrderInfoEntity getOrderInfoById(String id){
return om.getAllInfoById(id);
}
//用户操作
public static boolean addNewUserInfo(UserInfoEntity user){
return um.insertInfo(user);
}
public static boolean delUserInfo(String userid){
return um.deleteInfo(userid);
}
public static boolean updUserInfo(UserInfoEntity user){
return um.updateInfo(user);
}
public static UserInfoEntity getUserInfoById(String userid){
return um.getAllInfoById(userid);
}
public static List<UserInfoEntity> getAllUserInfo(){
return um.getAllInfo();
}
public static List<UserInfoEntity> getAllUserInfoByPagesize(int pagesize,int rowcount){
//return um.getUserInfoByPage(pagesize, rowcount);
return null;
}
public static int getUserPageSize(int rowcount){
//return um.getPageSize(rowcount);
return -1;
}
public static UserInfoEntity checkLogin(UserInfoEntity user){
List<UserInfoEntity> list=um.getUserInfoByProPerty(user);
return (list!=null&&list.size()>0)?list.get(0):null;
}
//商品操作
public static boolean addNewCommodityInfo(CommodityEntity com){
return cm.insertInfo(com);
}
public static boolean delCommodityInfo(String cid){
return cm.deleteInfo(cid);
}
public static boolean updCommodityInfo(CommodityEntity com){
return cm.updateInfo(com);
}
public static CommodityEntity getCommodityInfoById(String cid){
return cm.getAllInfoById(cid);
}
public static List<CommodityEntity> getAllCommodityInfo(){
return cm.getAllInfo();
}
public static List<CommodityEntity> getAllCommodityInfoByPagesize(int pagesize,int rowcount){
return cm.getCommodityInfoByPage(pagesize, rowcount);
}
public static int getCommdityPageSize(int rowcount){
return cm.getPageSize(rowcount);
}
//获得订单ID
public static String getOrderID(String userid){
return "or_"+userid+new Date().getTime();
}
//通过控制事务
public static String createOrder(UserInfoEntity user,List<OrderListEntity> car){
Connection con=DBHelper.getConnection();
if(con==null){
return null;
}
try {
con.setAutoCommit(false);
String oid=BossManager.getOrderID(user.getUserid()+"");
OrderInfoEntity order=new OrderInfoEntity();
order.setOid(oid);
order.setUser(user);
boolean f1=om.insertInfo(con, order);
if(!f1){
con.rollback();
}
for (int i = 0; i < car.size(); i++) {
OrderListEntity ol=car.get(i);
ol.setOlid(oid+"_"+(i+1));
ol.setOrder(order);
boolean f2=olm.insertInfo(con, ol);
if(!f2){
con.rollback();
return null;
}
}
con.commit();
return oid;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
DBHelper.closeJDBC(null, null, con);
}
return null;
}
}
5.servlet类(按照业务需要,servlet类,servlet的配置在之前的文章说过了,这里我就不再重复了。):
①购物车servlet类:
package com.shop.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.shop.bean.OrderListEntity;
public class CarServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String caozuo=request.getParameter("caozuo");
if(caozuo.equals("buy")){
this.buy(request, response);
}
if(caozuo.equals("updsize")){
this.updSize(request, response);
}
}
private void buy(HttpServletRequest request, HttpServletResponse response) throws IOException{
String cid=request.getParameter("cid");
HttpSession session=request.getSession(true);
List<OrderListEntity> carList=(List<OrderListEntity>)session.getAttribute("car");
if(carList==null){
carList=new ArrayList<OrderListEntity>();
session.setAttribute("car",carList);
}
for(int i=0;i<carList.size();i++){
if(carList.get(i).getCommodity().getCid().equals(cid)){
carList.get(i).setComnum(new BigDecimal(carList.get(i).getComnum().intValue()+1));
response.sendRedirect("/ShoppingCar/ShopCenter/index.jsp");
return;
}
}
OrderListEntity ol=new OrderListEntity(null, cid, null, new BigDecimal(1));
carList.add(ol);
response.sendRedirect("/ShoppingCar/ShopCenter/index.jsp");
}
private void updSize(HttpServletRequest request, HttpServletResponse response) throws IOException{
String cid=request.getParameter("cid");
String size=request.getParameter("size");
HttpSession session=request.getSession(true);
List<OrderListEntity> carList=(List<OrderListEntity>)session.getAttribute("car");
for(int i=0;i<carList.size();i++){
if(carList.get(i).getCommodity().getCid().equals(cid)){
carList.get(i).setComnum(new BigDecimal(size));
if(carList.get(i).getComnum().intValue()<=0){
carList.remove(i);
}
response.sendRedirect("/ShoppingCar/ShopCenter/ShowCar.jsp");
return;
}
}
}
}
②登录servlet类:
package com.shop.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.shop.bean.UserInfoEntity;
import com.shop.boss.BossManager;
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String caozuo=request.getParameter("caozuo");
if(caozuo.equals("login")){
this.login(request, response);
}
if(caozuo.equals("exits")){
this.exits(request, response);
}
}
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException{
String logname=request.getParameter("logname");
String pwd=request.getParameter("pwd");
HttpSession session=request.getSession(true);
UserInfoEntity user=BossManager.checkLogin(new UserInfoEntity(logname, pwd));
if(user==null){
response.sendRedirect("/ShoppingCar/ShopCenter/Login.jsp?log=0");
}else{
session.setAttribute("user", user);
PrintWriter out=response.getWriter();
out.print("<script>");
out.print("window.parent.location.reload();");
out.print("</script>");
out.flush();
out.close();
}
}
private void exits(HttpServletRequest request, HttpServletResponse response) throws IOException{
HttpSession session=request.getSession();
session.removeAttribute("user");
response.sendRedirect("/ShoppingCar/ShopCenter/index.jsp");
}
}
③订单明细servlet类:
package com.shop.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.shop.bean.OrderListEntity;
import com.shop.bean.UserInfoEntity;
import com.shop.boss.BossManager;
public class OrderServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session=request.getSession(true);
UserInfoEntity user=(UserInfoEntity)session.getAttribute("user");
if(user==null){
response.sendRedirect("/ShoppingCar/ShopCenter/Login.jsp");
return;
}
List<OrderListEntity> carList=(List<OrderListEntity>)session.getAttribute("car");
String oid=BossManager.createOrder(user,carList);
session.removeAttribute("car");
response.sendRedirect("/ShoppingCar/ShopCenter/index.jsp?oid="+oid);
}
}
三、界面实现
①商品主页(index.jsp):本界面内罗列出了商品的信息,用户可以根据自己喜好将商品加到购物车上,也可以查看自己的购物车,但是若要结账的话要先登录。为了提高用户体验度,用户点击登录时并不是跳转到另一个界面,而是在当前界面内弹出小窗口进行登录。(主要是用到了div的一个属性position:absolute;z-index:4 z-index后面的值是控制DIV处在当前界面的第几层,我们为了实现窗口登录所以设置时肯定是位于0层以上,然后在里面加一个<iframe></iframe>连接登录界面。在通过另一个DIV控制用户登陆时锁定背景不可以操作。具体大家看代码吧。)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@page import="com.shop.boss.BossManager"%>
<%@page import="com.shop.bean.UserInfoEntity"%>
<%@page import="com.shop.bean.CommodityEntity"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<%String oid=request.getParameter("oid");
if(oid!=null){ %>
<script type="text/javascript">
window.alert("订单提交成功,编号为<%= oid%>,请您注意查询订单状态!")
</script>
<%} %>
<%
UserInfoEntity user=(UserInfoEntity)session.getAttribute("user");
String dl="style='display: block'";
String tc="style='display: none'";
if(user!=null){
dl="style='display: none'";
tc="style='display: block'";
}
int pagesize=1;
int rowcount=5;
int sizemax=BossManager.getCommdityPageSize(rowcount);
if(pagesize<1){
pagesize=1;
}
if(pagesize>sizemax){
pagesize=sizemax;
}
//List<commodityEntity> list=BossManager.getAllCommodityInfoByPagesize(pagesize,rowcount);
List<CommodityEntity> list=BossManager.getAllCommodityInfo();
%>
<body style="text-align: center;">
<div style="font-size: 22px;color: blue">欢迎使用QST购物系统:</div>
<div align="right"><a href="javascript:login()" <%=dl %>>登录</a><a href="/ShoppingCar/loginservlet?caozuo=exits" <%=tc %>>退出</a></div>
<div style="width: 50%;background-color: #eeccee;font-size: 20px;color: #ffffff" align="center">
<div style="float: left;width: 80px;">编号</div>
<div style="float: left;width: 150px;">名称</div>
<div style="float: left;width: 50px;">单位</div>
<div style="float: left;width: 80px;">价格</div>
<div style="float: left;width: 80px;">图片</div>
<div style="float: left;width: 180px;">操作</div></div>
<hr/>
<div style="width: 50%;font-size: 14px;" align="center" >
<%for(int i=0;i<list.size();i++) {
CommodityEntity com=list.get(i);
%>
<br/>
<div style="float: left;width: 80px;"><%=i+1%></div>
<div style="float: left;width: 150px;"><%=com.getCname()%></div>
<div style="float: left;width: 50px;"><%=com.getCutil()%></div>
<div style="float: left;width: 80px;"><%=com.getCprice()%></div>
<div style="float: left;width: 80px;"><input type="image" src="/ShoppingCar/Images/<%=com.getCimg()%>" /></div>
<div style="float: left;width: 180px;"><a href="/ShoppingCar/carservlet?cid=<%=com.getCid()%>&caozuo=buy">放入购物车</a> <a href="/ShoppingCar/ShopCenter/ShowCar.jsp">查看购物车</a></div>
<br/><br/><br/>
<hr/>
<%}%>
</div>
<div style="position: absolute;z-index: 4;left:0px;top:0px; border-style: solid;border-color: #0099ff;display: none" id="lg">
<table style="border: 0px;text-align: center;" cellspacing="0px" cellpadding="0px" width="300px;">
<tr>
<td height="20px" bgcolor="#0099ff" align="right">
<a href="javascript:closelogin()" style="color: #ffffff;text-decoration: none">关闭 </a>
</td>
</tr>
<tr>
<td height="200px">
<iframe src="/ShoppingCar/ShopCenter/Login.jsp" height="100%" width="100%"></iframe>
</td>
</tr>
</table>
</div>
<div style="left:0px;top:0px; width: 120%;height: 120%;position: absolute;z-index: 2;background-color: #ccffcc;filter:alpha(opacity=20); display: none;" id="fg" "></div>
</body>
<script type="text/javascript">
function login(){
var d=document.getElementById("lg");
var f=document.getElementById("fg");
d.style.top=document.body.clientHeight/2-300/2;
d.style.left=document.body.clientWidth/2-150;
d.style.display="";
f.style.display="";
}
function closelogin(){
var d=document.getElementById("lg");
var f=document.getElementById("fg");
d.style.display="none";
f.style.display="none";
}
</script>
</html>
②登录界面(Login.jsp):只是简单的一个登录,验证什么的都没做。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.shop.bean.UserInfoEntity"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Login.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<%
String log=request.getParameter("log");
if(log!=null&&"0".equals(log)){%>
<script type="text/javascript">
window.alert("查无此人");
</script>
<%} %>
<body style="text-align: center;">
<div align="center">
<form action="/ShoppingCar/loginservlet?caozuo=login" method="post">
logname: <input type="text" name="logname">
<br/>
<br/>
password:<input type="text" name="pwd">
<br/>
<br/>
<input type="submit" value="登录" style="width: 100px;height: 30px"/>
</form>
</div>
</body>
</html>
③购物车界面(ShowCar.jsp):用户可以查看自己已选购的商品,可以修改商品的数量,可以将商品移出购物车。可以进行结账。结账后订单将存入到数据库中。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="com.shop.bean.OrderListEntity"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ShowCar.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<%
List<OrderListEntity> list=( List<OrderListEntity>)session.getAttribute("car");
if(list==null||list.size()<1){
response.sendRedirect("/ShoppingCar/ShopCenter/index.jsp");
return;
}
double zj=0;
double dj=0;
%>
<body style="text-align: center;">
<div style="font-size: 22px;color: blue" align="left">您一共购买了<%=list.size() %>件商品,如下:</div>
<div align="right"><a href="/ShoppingCar/ShopCenter/index.jsp">继续购物</a></div>
<div style="width: 55%;background-color: #eeccee;font-size: 20px;color: #ffffff" align="center">
<div style="float: left;width: 80px;">编号</div>
<div style="float: left;width: 150px;">名称</div>
<div style="float: left;width: 50px;">单位</div>
<div style="float: left;width: 50px;">数量</div>
<div style="float: left;width: 80px;">单项总价</div>
<div style="float: left;width: 80px;">图片</div>
<div style="float: left;width: 210px;">操作</div></div>
<hr/>
<div style="width: 55%" align="center">
<%for(int i=0;i<list.size();i++) {
OrderListEntity order=list.get(i);
%>
<div style="float: left;width: 80px;"><%=i+1%></div>
<div style="float: left;width: 150px;"><%=order.getCommodity().getCname()%></div>
<div style="float: left;width: 50px;"><%=order.getCommodity().getCutil()%></div>
<div style="float: left;width: 50px;"><%=order.getComnum()%></div>
<div style="float: left;width: 80px;">
<% dj=order.getCommodity().getCprice().intValue()*order.getComnum().intValue();
zj+=dj;
%><%=dj %></div>
<div style="float: left;width: 80px;"><input type="image" src="/ShoppingCar/Images/<%=order.getCommodity().getCimg()%>" /></div>
<div style="float: left;width: 210px;"><a href="/ShoppingCar/carservlet?cid=<%=order.getCommodity().getCid()%>&caozuo=updsize&size=<%=order.getComnum().intValue()+1 %>">加一个</a> <a href="/ShoppingCar/carservlet?cid=<%=order.getCommodity().getCid()%>&caozuo=updsize&size=<%=order.getComnum().intValue()-1 %>">减一个</a> <a href="/ShoppingCar/carservlet?cid=<%=order.getCommodity().getCid()%>&caozuo=updsize&size=<%=0 %>">移出购物车</a></div>
<br/><br/><br/>
<hr/>
<%}%>
</div>
<div align="right">您的消费总计为:<%=zj %>元
<input type="button" value="结账" οnclick="window.open('/ShoppingCar/orderservlet','_self')">
</div>
</body>
</html>
这个小购物车,肯定有很多不晚上的地方,做这个只是想体验一下servlet作为中间层的请求处理,合理运用学的知识。希望能给大家带来一点帮助。想要项目的可以留下你们的邮箱我会尽快给你们发过去,大家共同进步。