首页 > 代码库 > 易买网项目源码【完整版】

易买网项目源码【完整版】

技术分享
  1 package cn.easybuy.dao;
  2 import java.sql.*;
  3 import java.util.ArrayList;
  4 import java.util.HashMap;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import org.apache.log4j.Logger;
  9 
 10 import cn.easybuy.entity.ProductCategory;
 11 import cn.easybuy.utils.EmptyUtils;
 12 import cn.easybuy.utils.Params;
 13 
 14 /**
 15  * 基础dao的实现类,实现最基本的增删查改的方法
 16  */
 17 public abstract  class BaseDaoImpl implements IBaseDao {
 18 
 19     protected Connection connection;
 20 
 21     protected PreparedStatement pstm;
 22     
 23     static Logger logger=Logger.getLogger(BaseDaoImpl.class);
 24             
 25     public BaseDaoImpl(Connection connection) {
 26         this.connection = connection;
 27     }
 28 
 29     public ResultSet executeQuery(String sql,Object[] params){
 30         ResultSet rs=null;
 31         try {
 32             pstm = connection.prepareStatement(sql);
 33             for(int i = 0; i < params.length; i++){
 34                 pstm.setObject(i+1, params[i]);
 35             }
 36             rs = pstm.executeQuery();
 37         } catch (Exception e) {
 38             e.printStackTrace();
 39         }
 40         
 41         return rs;
 42     }
 43     
 44     //增删改操作 delete from news_detail where id=? and title=?
 45     public int executeUpdate(String sql,Object[] params){
 46         int updateRows = 0;
 47         try {
 48             pstm = connection.prepareStatement(sql);
 49             for(int i = 0; i < params.length; i++){
 50                 pstm.setObject(i+1, params[i]);
 51             }
 52             updateRows = pstm.executeUpdate();
 53         } catch (Exception e) {
 54             e.printStackTrace();
 55             updateRows = -1;
 56         }
 57         
 58         return updateRows;
 59     }
 60     
 61     public int executeInsert(String sql,Object[] params){
 62         Long id = 0L;
 63         try {
 64             pstm = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
 65             for(int i = 0; i < params.length; i++){
 66                 pstm.setObject(i+1, params[i]);
 67             }
 68             pstm.executeUpdate();
 69             ResultSet rs = pstm.getGeneratedKeys(); 
 70             if (rs.next()) { 
 71                 id = rs.getLong(1);
 72                 System.out.println("数据主键:" + id); 
 73             } 
 74             
 75         } catch (Exception e) {
 76             e.printStackTrace();
 77             id =null;
 78         }
 79         
 80         return id.intValue();
 81     }
 82     
 83     
 84     //释放资源
 85     public boolean closeResource(){
 86         if(pstm != null){
 87             try {
 88                 pstm.close();
 89             } catch (SQLException e) {
 90                 e.printStackTrace();
 91                 return false;
 92             }
 93         }
 94         return true;
 95     }
 96     
 97     public boolean closeResource(ResultSet reSet){
 98         if(reSet != null){
 99             try {
100                 reSet.close();
101             } catch (SQLException e) {
102                 // TODO Auto-generated catch block
103                 e.printStackTrace();
104                 return false;
105             }
106         }
107         return true;
108     }
109     /**
110      * 需要重写的方法
111      *
112      * @param rs
113      * @return
114      * @throws Exception
115      */
116     public abstract Object tableToClass(ResultSet rs) throws Exception;
117     
118 }
BaseDaoImpl
技术分享
 1 package cn.easybuy.dao;
 2 import cn.easybuy.utils.Params;
 3 
 4 import java.sql.ResultSet;
 5 import java.util.List;
 6 import java.util.Map;
 7 
 8 /**
 9  * Created by bdqn on 2016/4/22.
10  */
11 public interface IBaseDao {
12 //    /**
13 //     * 查询单表的数目
14 //     * @param  params
15 //     * @return 
16 //     * @throws Exception
17 //     */
18 //    public int getRowCount(Params params) throws Exception;
19 //    /**
20 //     * 查询单表的列表
21 //     * @param params
22 //     * @return
23 //     * @throws Exception
24 //     */
25 //    public List getRowList(Params params)throws Exception;
26 //    /**
27 //     * 每一个dao都需要重写的tableName
28 //     * @return
29 //     */
30 //    public String getTableName();
31 //    /**
32 //     * 根据id获取对象
33 //     * @param id
34 //     * @return
35 //     * @throws Exception
36 //     */
37 //    public Object getById(Integer id) throws Exception;
38 //    /**
39 //     * 根据参数更新对象
40 //     * @param params
41 //     * @throws Exception
42 //     */
43 //    public void updateByQuery(Params params) throws Exception;
44 //    /**
45 //     * 根据参数添加对象
46 //     * @param params
47 //     * @return
48 //     * @throws Exception
49 //     */
50 //    public Integer addObject(Params params)throws Exception;
51 //    /**
52 //     * 根据 id 删除记录
53 //     * @param id
54 //     * @throws Exception
55 //     */
56 //    public void deleteById(Integer id) throws Exception;
57 //    /**
58 //     * 自定义sql的方法
59 //     * @param sql
60 //     * @param params
61 //     */
62 //    public List selectBySql(String sqlStr,Params query)throws Exception;
63 }
IBaseDao

以上是dao层代码


 

技术分享
 1 package cn.easybuy.dao.news;
 2 
 3 import java.util.List;
 4 
 5 import cn.easybuy.dao.IBaseDao;
 6 import cn.easybuy.entity.News;
 7 import cn.easybuy.param.NewsParams;
 8 
 9 /**
10  * 新闻的dao
11  */
12 public interface NewsDao extends IBaseDao {
13     /**
14      * 添加新闻
15      * @param news
16      * @throws Exception
17      */
18     public void add(News news) throws Exception;
19     /**
20      * 修改新闻
21      * @param news
22      * @throws Exception
23      */
24     public void update(News news) throws Exception;
25     /**
26      * 根据id删除新闻
27      * @param id
28      * @throws Exception
29      */
30     public void deleteById(Integer id) throws Exception;
31     /**
32      * 根据id查询新闻
33      * @param id
34      * @return
35      * @throws Exception
36      */
37     public News getNewsById(Integer id)throws Exception; 
38     /**
39      * 查询新闻列表
40      * @param params
41      * @return
42      * @throws Exception
43      */
44     public List<News> queryNewsList(NewsParams params)throws Exception; 
45     /**
46      * 查询新闻的数目
47      * @param params
48      * @return
49      * @throws Exception
50      */
51     public Integer queryNewsCount(NewsParams params)throws Exception;
52 }
NewsDao
技术分享
  1 package cn.easybuy.dao.news;
  2 import java.sql.Connection;
  3 import java.sql.ResultSet;
  4 import java.sql.SQLException;
  5 import java.util.ArrayList;
  6 import java.util.Date;
  7 import java.util.List;
  8 import cn.easybuy.dao.BaseDaoImpl;
  9 import cn.easybuy.entity.News;
 10 import cn.easybuy.param.NewsParams;
 11 import cn.easybuy.utils.EmptyUtils;
 12 import cn.easybuy.utils.Pager;
 13 
 14 public class NewsDaoImpl extends BaseDaoImpl implements NewsDao {
 15 
 16     public NewsDaoImpl(Connection connection) {
 17         super(connection);
 18     }
 19 
 20     @Override
 21     public News tableToClass(ResultSet rs) throws Exception {
 22         News news = new News();
 23         news.setId(rs.getInt("id"));
 24         news.setTitle(rs.getString("title"));
 25         news.setContent(rs.getString("content"));
 26         news.setCreateTime(rs.getDate("createTime"));
 27         return news;
 28     }
 29 
 30     public void add(News news) throws Exception {// 保存新闻
 31         String sql = " INSERT into easybuy_news(title,content,createTime) values( ?, ?, ?) ";
 32         Object[] params = new Object[] { news.getTitle(), news.getContent(),
 33                 new Date() };
 34         this.executeUpdate(sql, params);
 35     }
 36 
 37     public void update(News news) throws Exception {// 更新新闻
 38         String sql = " update easybuy_news set title=?,content=? where id=? ";
 39         Object[] params = new Object[] {news.getTitle(), news.getContent(),news.getId() };
 40         this.executeUpdate(sql, params);
 41     }
 42 
 43     public void deleteById(Integer id) throws Exception {
 44         String sql = " delete from easybuy_news where id = ? ";
 45         Object params[] = new Object[] { id };
 46         this.executeUpdate(sql.toString(), params);
 47     }
 48 
 49     public News getNewsById(Integer id) {
 50         String sql = " select * from easybuy_news where id = ? ";
 51         ResultSet resultSet = null;
 52         News news = null;
 53         try {
 54             Object params[] = new Object[] { id };
 55             resultSet = this.executeQuery(sql, params);
 56             while (resultSet.next()) {
 57                 news = tableToClass(resultSet);
 58             }
 59         } catch (Exception e) {
 60             e.printStackTrace();
 61         } finally {
 62             this.closeResource(resultSet);
 63             this.closeResource();
 64             return news;
 65         }
 66     }
 67 
 68     @Override
 69     public List<News> queryNewsList(NewsParams params) {
 70         List<Object> paramsList=new ArrayList<Object>();   
 71         List<News> newsList=new ArrayList<News>();
 72         StringBuffer sql=new StringBuffer(" select id,title,content,createTime FROM easybuy_news where 1=1 ");
 73         if(EmptyUtils.isNotEmpty(params.getTitle())){
 74             sql.append(" and title like ? ");
 75             paramsList.add(params.getTitle());
 76         }
 77         if(EmptyUtils.isNotEmpty(params.getSort())){
 78             sql.append(" order by " + params.getSort()+" ");
 79         }
 80         if(params.isPage()){
 81             sql.append(" limit  " + params.getStartIndex() + "," + params.getPageSize());
 82         }
 83         
 84         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
 85         try {
 86             while (resultSet.next()) {
 87                 News news = this.tableToClass(resultSet);
 88                 newsList.add(news);
 89             }
 90         } catch (SQLException e) {
 91             e.printStackTrace();
 92         } catch (Exception e) {
 93             e.printStackTrace();
 94         }finally{
 95             this.closeResource(resultSet);
 96             this.closeResource();
 97         }
 98                 
 99         return newsList;
100     }
101     
102     @Override
103     public Integer queryNewsCount(NewsParams params) {
104         List<Object> paramsList=new ArrayList<Object>();   
105         Integer count = 0;
106         StringBuffer sql=new StringBuffer(" select count(*) as count FROM easybuy_news where 1=1 ");
107         if(EmptyUtils.isNotEmpty(params.getTitle())){
108             sql.append(" and title like ? ");
109             paramsList.add(params.getTitle());
110         }
111         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
112         try {
113             while (resultSet.next()) {
114                 count = resultSet.getInt("count");
115             }
116         } catch (SQLException e) {
117             e.printStackTrace();
118         } catch (Exception e) {
119             e.printStackTrace();
120         }finally{
121             this.closeResource(resultSet);
122             this.closeResource();
123         }
124         return count;
125     }
126 
127     
128 }
NewsDaoImpl

以上是dao.news层代码


 

技术分享
 1 package cn.easybuy.dao.order;
 2 import java.sql.SQLException;
 3 import java.util.List;
 4 import cn.easybuy.dao.IBaseDao;
 5 import cn.easybuy.entity.News;
 6 import cn.easybuy.entity.Order;
 7 import cn.easybuy.param.NewsParams;
 8 import cn.easybuy.param.OrderParams;
 9 
10 /***
11  * 订单处理的dao层
12  * getRowCount
13  * getRowList(Params params)
14  * getById(Integer id)
15  * addObject(Params params)
16  */
17 public interface OrderDao extends IBaseDao {
18 
19     public void add(Order order) ;
20 
21     public void deleteById(Integer id);
22     
23     public Order getOrderById(Integer id) ;
24     
25     public List<Order> getOrderList(Integer userId,Integer currentPageNo,Integer pageSize) ;
26     
27     public Integer count(Integer userId);
28 }
OrderDao
技术分享
  1 package cn.easybuy.dao.order;
  2 import java.sql.*;
  3 import java.util.ArrayList;
  4 import java.util.Date;
  5 import java.util.List;
  6 
  7 import cn.easybuy.dao.BaseDaoImpl;
  8 import cn.easybuy.dao.order.OrderDao;
  9 import cn.easybuy.entity.News;
 10 import cn.easybuy.entity.Order;
 11 import cn.easybuy.param.OrderParams;
 12 import cn.easybuy.utils.EmptyUtils;
 13 import cn.easybuy.utils.Pager;
 14 import cn.easybuy.utils.Params;
 15 /**
 16  * 订单dao的实现类
 17  */
 18 public class OrderDaoImpl extends BaseDaoImpl implements OrderDao {
 19 
 20     public OrderDaoImpl(Connection connection) {
 21         super(connection);
 22     }
 23 
 24     @Override
 25     public Order tableToClass(ResultSet rs) throws Exception {
 26         Order order = new Order();
 27         order.setId(rs.getInt("id"));
 28         order.setUserId(rs.getInt("userId"));
 29         order.setCreateTime(rs.getDate("createTime"));
 30         order.setCost(rs.getFloat("cost"));
 31         order.setUserAddress(rs.getString("userAddress"));
 32         order.setSerialNumber(rs.getString("serialNumber"));
 33         order.setLoginName(rs.getString("loginName"));
 34         return order;
 35     }
 36     /**
 37      * 保存订单
 38      * @param order
 39      * @throws java.sql.SQLException
 40      */
 41     public void add(Order order) {//保存订单
 42         Integer id=0;
 43         String sql="insert into easybuy_order(userId,loginName,userAddress,createTime,cost,serialNumber) values(?,?,?,?,?,?) ";
 44         Object[] param=new Object[]{order.getUserId(),order.getLoginName(),order.getUserAddress(),new Date(),order.getCost(),order.getSerialNumber()};
 45         try {
 46             id=this.executeInsert(sql, param);
 47             order.setId(new Integer(id).intValue());
 48         }catch (Exception e) {
 49             e.printStackTrace();
 50         }finally{
 51             this.closeResource();
 52         }
 53     }
 54 
 55     @Override
 56     public void deleteById(Integer id) {
 57         String sql = " delete from easybuy_order where id = ? ";
 58         Object params[] = new Object[] { id };
 59         try {
 60             this.executeUpdate(sql.toString(), params);
 61         }catch (Exception e) {
 62             e.printStackTrace();
 63         }finally{
 64             this.closeResource();
 65         }
 66     }
 67 
 68     @Override
 69     public Order getOrderById(Integer id) {
 70         String sql = " select * from easybuy_order where id = ? ";
 71         ResultSet resultSet = null;
 72         Order order = null;
 73         try {
 74             Object params[] = new Object[] { id };
 75             resultSet = this.executeQuery(sql, params);
 76             while (resultSet.next()) {
 77                 order = tableToClass(resultSet);
 78             }
 79         } catch (Exception e) {
 80             e.printStackTrace();
 81         } finally {
 82             this.closeResource(resultSet);
 83             this.closeResource();
 84             return order;
 85         }
 86     }
 87 
 88     @Override
 89     public List<Order> getOrderList(Integer userId,Integer currentPageNo,Integer pageSize) {
 90         List<Object> paramsList=new ArrayList<Object>();   
 91         List<Order> orderList=new ArrayList<Order>();
 92         StringBuffer sql=new StringBuffer(" select id,userId,loginName,userAddress,createTime,cost,serialNumber from easybuy_order  where 1=1 ");
 93         if(EmptyUtils.isNotEmpty(userId)){
 94             sql.append(" and userId = ? ");
 95             paramsList.add(userId);
 96         }
 97         int total = count(userId);
 98         Pager pager = new Pager(total, pageSize, currentPageNo);
 99         sql.append(" limit  " + (pager.getCurrentPage() - 1) * pager.getRowPerPage() + "," + pager.getRowPerPage());
100         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
101         try {
102             while (resultSet.next()) {
103                 Order order = this.tableToClass(resultSet);
104                 orderList.add(order);
105             }
106         } catch (SQLException e) {
107             e.printStackTrace();
108         } catch (Exception e) {
109             e.printStackTrace();
110         }finally{
111             this.closeResource();
112             this.closeResource(resultSet);
113         }
114                 
115         return orderList;
116     }
117 
118     @Override
119     public Integer count(Integer userId)  {
120         List<Object> paramsList=new ArrayList<Object>();   
121         Integer count=0;
122         StringBuffer sql=new StringBuffer(" select count(id) count from easybuy_order  where 1=1 ");
123         if(EmptyUtils.isNotEmpty(userId)){
124             sql.append(" and userId = ? ");
125             paramsList.add(userId);
126         }
127         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
128         try {
129             while (resultSet.next()) {
130                 count = resultSet.getInt("count");
131             }
132         } catch (SQLException e) {
133             e.printStackTrace();
134         } catch (Exception e) {
135             e.printStackTrace();
136         }finally{
137             this.closeResource();
138             this.closeResource(resultSet);
139         }
140         return count;
141     }
142 }
OrderDaoImpl
技术分享
 1 package cn.easybuy.dao.order;
 2 import cn.easybuy.dao.IBaseDao;
 3 import cn.easybuy.entity.News;
 4 import cn.easybuy.entity.OrderDetail;
 5 import cn.easybuy.param.NewsParams;
 6 import cn.easybuy.param.OrderDetailParam;
 7 import java.sql.SQLException;
 8 import java.util.List;
 9 
10 /**
11  * 订单详细
12  * Created by bdqn on 2016/5/8.
13  */
14 public interface OrderDetailDao extends IBaseDao {
15 
16     public void add(OrderDetail detail) throws Exception;
17 
18     public void deleteById(OrderDetail detail) throws Exception;
19     
20     public OrderDetail getOrderDetailById(Integer id)throws Exception; 
21     
22     public List<OrderDetail> getOrderDetailList(Integer orderId)throws Exception;
23     
24     public Integer queryOrderDetailCount(OrderDetailParam params)throws Exception; 
25 }
OrderDetailDao
技术分享
  1 package cn.easybuy.dao.order;
  2 import cn.easybuy.dao.BaseDaoImpl;
  3 import cn.easybuy.dao.product.ProductDaoImpl;
  4 import cn.easybuy.dao.product.ProductDao;
  5 import cn.easybuy.entity.News;
  6 import cn.easybuy.entity.Order;
  7 import cn.easybuy.entity.OrderDetail;
  8 import cn.easybuy.entity.Product;
  9 import cn.easybuy.param.OrderDetailParam;
 10 import cn.easybuy.utils.EmptyUtils;
 11 import cn.easybuy.utils.Params;
 12 
 13 import java.sql.Connection;
 14 import java.sql.ResultSet;
 15 import java.sql.SQLException;
 16 import java.util.ArrayList;
 17 import java.util.List;
 18 
 19 /**
 20  * Created by bdqn on 2016/5/8.
 21  */
 22 public class OrderDetailDaoImpl extends BaseDaoImpl implements OrderDetailDao{
 23 
 24     ProductDao productDao;
 25 
 26     public OrderDetailDaoImpl(Connection connection) {
 27         super(connection);
 28         productDao=new ProductDaoImpl(connection);
 29     }
 30     
 31 
 32     @Override
 33     public OrderDetail tableToClass(ResultSet rs) throws Exception {
 34         OrderDetail orderDetail = new OrderDetail();
 35         orderDetail.setId(rs.getInt("id"));
 36         orderDetail.setOrderId(rs.getInt("orderId"));
 37         orderDetail.setProduct((Product) productDao.getProductById(rs.getInt("productId")));
 38         orderDetail.setProductId(rs.getInt("productId"));
 39         orderDetail.setQuantity(rs.getInt("quantity"));
 40         orderDetail.setCost(rs.getFloat("cost"));
 41         return orderDetail;
 42     }
 43 
 44     public void add(OrderDetail detail) throws SQLException {//保存订单详情
 45         Integer id=0;
 46         String sql=" insert into easybuy_order_detail(orderId,productId,quantity,cost) values(?,?,?,?) ";
 47         try {
 48             Object param[]=new Object[]{detail.getOrderId(),detail.getProduct().getId(),detail.getQuantity(),detail.getCost()};
 49             id=this.executeInsert(sql,param);
 50             detail.setId(id);
 51         } catch (Exception e) {
 52             this.closeResource();
 53             e.printStackTrace();
 54         }
 55     }
 56 
 57     @Override
 58     public void deleteById(OrderDetail detail) throws Exception {
 59         String sql = " delete from easybuy_order_detail where id = ? ";
 60         Object params[] = new Object[] { detail.getId() };
 61         try {
 62         this.executeUpdate(sql.toString(), params);
 63         }catch (Exception e) {
 64             e.printStackTrace();
 65         }finally{
 66             this.closeResource();
 67         }
 68     }
 69 
 70     @Override
 71     public OrderDetail getOrderDetailById(Integer id) throws Exception {
 72         String sql = " select orderId,productId,quantity,cost from easybuy_order_detail where id = ? ";
 73         ResultSet resultSet = null;
 74         OrderDetail orderDetail = null;
 75         try {
 76             Object params[] = new Object[] { id };
 77             resultSet = this.executeQuery(sql, params);
 78             while (resultSet.next()) {
 79                 orderDetail = tableToClass(resultSet);
 80             }
 81         } catch (Exception e) {
 82             e.printStackTrace();
 83         } finally {
 84             this.closeResource(resultSet);
 85             this.closeResource();
 86             return orderDetail;
 87         }
 88     }
 89 
 90     @Override
 91     public List<OrderDetail> getOrderDetailList(Integer orderId)
 92             throws Exception {
 93         List<OrderDetail> orderDetailList = null;
 94         List<Object> paramsList=new ArrayList<Object>();
 95         StringBuffer sql = new StringBuffer(" select id,orderId,productId,quantity,cost FROM easybuy_order_detail where 1=1 ");
 96         
 97         if(EmptyUtils.isNotEmpty(orderId)){
 98             sql.append(" and orderId=? ");
 99             paramsList.add(orderId);
100         }
101         ResultSet resultSet = this.executeQuery(sql.toString(), paramsList.toArray());
102         try {
103             orderDetailList=new ArrayList<OrderDetail>();
104             while (resultSet.next()) {
105                 OrderDetail orderDetail = this.tableToClass(resultSet);
106                 orderDetailList.add(orderDetail);
107             }
108         } catch (Exception e) {
109             e.printStackTrace();
110         }finally{
111             this.closeResource(resultSet);
112             this.closeResource();
113             return orderDetailList;
114         }
115     }
116 
117     @Override
118     public Integer queryOrderDetailCount(OrderDetailParam params)throws Exception {
119         Integer count = 0;
120         List<OrderDetail> orderDetailList = null;
121         String sql = " select count(*) FROM easybuy_order_detail ";
122         ResultSet resultSet = this.executeQuery(sql, new Object[] {});
123         try {
124             orderDetailList=new ArrayList<OrderDetail>();
125             while (resultSet.next()) {
126                 count = resultSet.getInt("count");
127             }
128         } catch (Exception e) {
129             e.printStackTrace();
130         }finally{
131             this.closeResource(resultSet);
132             this.closeResource();
133             return count;
134         }
135     }
136 }
OrderDetailDaoImpl
技术分享
 1 package cn.easybuy.dao.order;
 2 
 3 import java.util.List;
 4 
 5 import cn.easybuy.dao.IBaseDao;
 6 import cn.easybuy.entity.UserAddress;
 7 import cn.easybuy.param.UserAddressParam;
 8 
 9 
10 public interface UserAddressDao extends IBaseDao {
11     
12     public List<UserAddress> queryUserAddressList(UserAddressParam param);
13     
14     public Integer add(UserAddress userAddress);
15     
16     public UserAddress getUserAddressById(Integer addressId);
17 
18 }
UserAddressDao
技术分享
  1 package cn.easybuy.dao.order;
  2 import cn.easybuy.dao.BaseDaoImpl;
  3 import cn.easybuy.entity.Product;
  4 import cn.easybuy.entity.UserAddress;
  5 import cn.easybuy.param.UserAddressParam;
  6 import cn.easybuy.utils.EmptyUtils;
  7 
  8 import java.sql.Connection;
  9 import java.sql.ResultSet;
 10 import java.sql.SQLException;
 11 import java.util.ArrayList;
 12 import java.util.Date;
 13 import java.util.List;
 14 
 15 public class UserAddressDaoImpl extends BaseDaoImpl implements UserAddressDao {
 16 
 17     public UserAddressDaoImpl(Connection connection) {
 18         super(connection);
 19     }
 20 
 21     @Override
 22     public UserAddress tableToClass(ResultSet rs) throws Exception {
 23         UserAddress userAddress = new UserAddress();
 24         userAddress.setId(rs.getInt("id"));
 25         userAddress.setAddress(rs.getString("address"));
 26         userAddress.setUserId(rs.getInt("userId"));
 27         userAddress.setCreateTime(rs.getDate("createTime"));
 28         userAddress.setRemark(rs.getString("remark"));
 29         return userAddress;
 30     }
 31 
 32     @Override
 33     public List<UserAddress> queryUserAddressList(UserAddressParam params) {
 34         List<Object> paramsList=new ArrayList<Object>();   
 35         List<UserAddress> userAddresseList=new ArrayList<UserAddress>();
 36         StringBuffer sql=new StringBuffer("  select id,userId,address,createTime,isDefault,remark from easybuy_user_address  where 1=1 ");
 37         if(EmptyUtils.isNotEmpty(params.getUserId())){
 38             sql.append(" and userId = ? ");
 39             paramsList.add(params.getUserId());
 40         }
 41         if(EmptyUtils.isNotEmpty(params.getAddress())){
 42             sql.append(" and address like ? ");
 43             paramsList.add("%"+params.getAddress()+"%");
 44         }
 45         if(EmptyUtils.isNotEmpty(params.getSort())){
 46             sql.append(" order by " + params.getSort()+" ");
 47         }
 48         if(params.isPage()){
 49             sql.append(" limit  " + params.getStartIndex() + "," + params.getPageSize());
 50         }
 51         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
 52         try {
 53             while (resultSet.next()) {
 54                 UserAddress userAddress = this.tableToClass(resultSet);
 55                 userAddresseList.add(userAddress);
 56             }
 57         } catch (SQLException e) {
 58             e.printStackTrace();
 59         } catch (Exception e) {
 60             e.printStackTrace();
 61         }finally{
 62             this.closeResource();
 63             this.closeResource(resultSet);
 64         }
 65         return userAddresseList;
 66     }
 67 
 68     @Override
 69     public Integer add(UserAddress userAddress) {
 70         Integer id=0;
 71         String sql=" INSERT into easybuy_user_address(userId,address,createTime,isDefault,remark) VALUES(?,?,?,?,?) ";
 72         try {
 73             Object param[]=new Object[]{userAddress.getUserId(),userAddress.getAddress(),new Date(),0,userAddress.getRemark()};
 74             id=this.executeInsert(sql,param);
 75             userAddress.setId(id);
 76         } catch (Exception e) {
 77             e.printStackTrace();
 78         }finally{
 79             this.closeResource();
 80         }
 81         return id;
 82     }
 83 
 84     @Override
 85     public UserAddress getUserAddressById(Integer addressId) {
 86         List<Object> paramsList=new ArrayList<Object>();   
 87         StringBuffer sql=new StringBuffer(" select id,userId,address,createTime,isDefault,remark from easybuy_user_address  where id=? ");
 88         UserAddress userAddress =null;
 89         ResultSet resultSet = this.executeQuery(sql.toString(),new Object[]{addressId});
 90         try {
 91             while (resultSet.next()) {
 92                 userAddress= this.tableToClass(resultSet);
 93             }
 94         } catch (SQLException e) {
 95             e.printStackTrace();
 96         } catch (Exception e) {
 97             e.printStackTrace();
 98         }finally{
 99             this.closeResource();
100             this.closeResource(resultSet);
101         }
102         return userAddress;
103     }
104 }
UserAddressDaoImpl

以上是dao.oreder层代码


 

技术分享
 1 package cn.easybuy.dao.product;
 2 
 3 import cn.easybuy.dao.IBaseDao;
 4 import cn.easybuy.entity.OrderDetail;
 5 import cn.easybuy.entity.ProductCategory;
 6 import cn.easybuy.entity.User;
 7 import cn.easybuy.param.OrderDetailParam;
 8 import cn.easybuy.param.ProductCategoryParam;
 9 import cn.easybuy.utils.Params;
10 
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13 import java.util.List;
14 
15 /**
16  * Created by bdqn on 2016/5/12.
17  * addObject(UserAddress userAddress)
18  * getRowList(params)
19  * getRowCount(params)
20  * getById(Integer id)
21  * updateByQuery(params)
22  */
23 public interface ProductCategoryDao extends IBaseDao {
24     /**
25      * 根据id删除商品
26      * @param parseLong
27      */
28     void deleteById(Integer parseLong);//删除商品分类
29     /**
30      * 根据条件查询商品列表
31      * @param param
32      */
33     public List<ProductCategory> queryProductCategorylist(ProductCategoryParam param);
34     /**
35      * 根据id查询商品分类
36      * @param param
37      */
38     public ProductCategory queryProductCategoryById(Integer id);
39     /**
40      * 添加商品分类
41      * @param param
42      */
43     public Integer add(ProductCategory productCategory) ;
44     /**
45      * 根据参数查询商品分类的数目
46      * @param param
47      */
48     public Integer queryProductCategoryCount(ProductCategoryParam param);
49     /**
50      * 修改商品分类
51      * @param param
52      */
53     public void update(ProductCategory productCategory) ;
54 }
ProductCategoryDao
技术分享
  1 package cn.easybuy.dao.product;
  2 
  3 import java.sql.Connection;
  4 import java.sql.ResultSet;
  5 import java.sql.ResultSetMetaData;
  6 import java.sql.SQLException;
  7 import java.util.ArrayList;
  8 import java.util.HashMap;
  9 import java.util.List;
 10 import java.util.Map;
 11 
 12 import cn.easybuy.dao.BaseDaoImpl;
 13 import cn.easybuy.dao.product.ProductCategoryDao;
 14 import cn.easybuy.entity.Product;
 15 import cn.easybuy.entity.ProductCategory;
 16 import cn.easybuy.entity.User;
 17 import cn.easybuy.param.ProductCategoryParam;
 18 import cn.easybuy.utils.EmptyUtils;
 19 import cn.easybuy.utils.Params;
 20 
 21 public class ProductCategoryDaoImpl extends BaseDaoImpl implements ProductCategoryDao {
 22 
 23     public ProductCategoryDaoImpl(Connection connection) {
 24         super(connection);
 25     }
 26 
 27     @Override
 28     public ProductCategory tableToClass(ResultSet rs) throws Exception {
 29         ProductCategory productCategory = new ProductCategory();
 30         productCategory.setId(rs.getInt("id"));
 31         productCategory.setName(rs.getString("name"));
 32         productCategory.setParentId(rs.getInt("parentId"));
 33         productCategory.setType(rs.getInt("type"));
 34         productCategory.setIconClass(rs.getString("iconClass"));
 35         return productCategory;
 36     }
 37     
 38     public ProductCategory mapToClass(Map map) throws Exception {
 39         ProductCategory productCategory = new ProductCategory();
 40         Object idObject=map.get("id");
 41         Object nameObject=map.get("name");
 42         Object parentIdObject=map.get("parentId");
 43         Object typeObject=map.get("type");
 44         Object iconClassObject=map.get("iconClass");
 45         Object parentNameObject=map.get("parentName");
 46         productCategory.setId(EmptyUtils.isEmpty(idObject)?null:(Integer)idObject);
 47         productCategory.setName(EmptyUtils.isEmpty(nameObject)?null:(String)nameObject);
 48         productCategory.setParentId(EmptyUtils.isEmpty(parentIdObject)?null:(Integer)parentIdObject);
 49         productCategory.setType(EmptyUtils.isEmpty(typeObject)?null:(Integer)typeObject);
 50         productCategory.setIconClass(EmptyUtils.isEmpty(iconClassObject)?null:(String)iconClassObject);
 51         productCategory.setParentName(EmptyUtils.isEmpty(parentNameObject)?null:(String)parentNameObject);
 52         return productCategory;
 53     }
 54     
 55     public List<ProductCategory> queryProductCategorylist(ProductCategoryParam params){
 56         List<ProductCategory> list=new ArrayList<ProductCategory>();
 57         List<Object> paramsList=new ArrayList<Object>();
 58         StringBuffer sqlBuffer=new StringBuffer("SELECT epc1.*,epc2.name as parentName FROM easybuy_product_category epc1 LEFT JOIN easybuy_product_category epc2 ON epc1.parentId=epc2.id where 1=1 ");
 59         ResultSet resultSet=null;
 60         try{
 61             if(EmptyUtils.isNotEmpty(params.getName())){
 62                 sqlBuffer.append(" and epc1.name like ? ");
 63                 paramsList.add("%"+params.getName()+"%");
 64             }
 65             if(EmptyUtils.isNotEmpty(params.getParentId())){
 66                 sqlBuffer.append(" and epc1.parentId = ? ");
 67                 paramsList.add(params.getParentId());
 68             }
 69             if(EmptyUtils.isNotEmpty(params.getType())){
 70                 sqlBuffer.append(" and epc1.type = ? ");
 71                 paramsList.add(params.getType());
 72             }
 73             if(params.isPage()){
 74                 sqlBuffer.append(" limit  " + params.getStartIndex() + "," + params.getPageSize());
 75             }
 76             resultSet=this.executeQuery(sqlBuffer.toString(),paramsList.toArray());
 77             while (resultSet.next()) {
 78                 ProductCategory productCategory = this.tableToClass(resultSet);
 79                 productCategory.setParentName(resultSet.getString("parentName"));
 80                 list.add(productCategory);
 81             }
 82         }catch (Exception e) {
 83             e.printStackTrace();
 84         }finally{
 85             this.closeResource();
 86             this.closeResource(resultSet);
 87         }
 88 
 89         
 90         return list;
 91     }
 92 
 93     @Override
 94     public void deleteById(Integer id){
 95         String sql = " delete from easybuy_product_category where id = ? ";
 96         Object params[] = new Object[] { id };
 97         this.executeUpdate(sql.toString(), params);    
 98     }
 99 
100     public Integer queryProductCategoryCount(ProductCategoryParam params){
101         List<Object> paramsList=new ArrayList<Object>();   
102         Integer count=0;
103         StringBuffer sql=new StringBuffer("SELECT count(*) count FROM easybuy_product_category where 1=1 ");
104         if(EmptyUtils.isNotEmpty(params.getName())){
105             sql.append(" and name like ? ");
106             paramsList.add("%"+params.getName()+"%");
107         }
108         if(EmptyUtils.isNotEmpty(params.getParentId())){
109             sql.append(" and parentId = ? ");
110             paramsList.add(params.getParentId());
111         }
112         ResultSet resultSet=this.executeQuery(sql.toString(), paramsList.toArray());
113         try {
114             while (resultSet.next()) {
115                 count=resultSet.getInt("count");
116             }
117         } catch (SQLException e) {
118             e.printStackTrace();
119         } catch (Exception e) {
120             e.printStackTrace();
121         }finally{
122             this.closeResource();
123             this.closeResource(resultSet);
124         }
125         return count;
126     }
127     
128     public ProductCategory queryProductCategoryById(Integer id){
129         List<Object> paramsList=new ArrayList<Object>();   
130         ProductCategory productCategory=null;
131         StringBuffer sql=new StringBuffer("SELECT id,name,parentId,type,iconClass  FROM easybuy_product_category where id = ? ");
132         ResultSet resultSet=this.executeQuery(sql.toString(),new Object[]{id});
133         try {
134             while (resultSet.next()) {
135                 productCategory = this.tableToClass(resultSet);
136             }
137         } catch (SQLException e) {
138             e.printStackTrace();
139         } catch (Exception e) {
140             e.printStackTrace();
141         }finally{
142             this.closeResource();
143             this.closeResource(resultSet);
144         }
145         return productCategory;
146     }
147     
148     public Integer add(ProductCategory productCategory)  {//新增用户信息
149         Integer id=0;
150         try {
151             String sql=" INSERT into easybuy_product_category(name,parentId,type,iconClass) values(?,?,?,?) ";
152             Object param[]=new Object[]{productCategory.getName(),productCategory.getParentId(),productCategory.getType(),productCategory.getIconClass()};
153             id=this.executeInsert(sql,param);
154             productCategory.setId(id);
155         } catch (Exception e) {
156             e.printStackTrace();
157         }finally{
158             this.closeResource();
159         }
160         return id;
161     }
162 
163     @Override
164     public void update(ProductCategory productCategory) {
165         try {
166             Object[] params = new Object[] {productCategory.getName(),productCategory.getParentId(),productCategory.getType(),productCategory.getIconClass(),productCategory.getId()};
167             String sql = " UPDATE easybuy_product_category SET name=?,parentId=?,type=?,iconClass=? WHERE id =?  ";
168             this.executeUpdate(sql, params);
169         } catch (Exception e) {
170             e.printStackTrace();
171         }finally{
172             this.closeResource();
173         }        
174     }
175     
176     
177 }
ProductCategoryDaoImpl
技术分享
 1 package cn.easybuy.dao.product;
 2 
 3 import java.util.List;
 4 
 5 import cn.easybuy.dao.IBaseDao;
 6 import cn.easybuy.entity.News;
 7 import cn.easybuy.entity.Product;
 8 import cn.easybuy.param.NewsParams;
 9 import cn.easybuy.param.ProductParam;
10 
11 /**
12  * 商品查询Dao
13  *
14  * deleteById(Integer id)
15  * getById(Integer id)
16  * getRowCount(params)
17  * getRowList(params)
18  *
19  */
20 public interface ProductDao extends IBaseDao {
21 
22     Integer updateStock(Integer id, Integer quantity) throws Exception;
23     
24     public Integer add(Product product) throws Exception;
25 
26     public Integer update(Product product) throws Exception;
27     
28     public Integer deleteProductById(Integer id) throws Exception;
29     
30     public Product getProductById(Integer id)throws Exception;
31     
32     public List<Product> getProductList(Integer currentPageNo,Integer pageSize,String proName,Integer categoryId,Integer level)throws Exception;
33     
34     public Integer queryProductCount(String proName,Integer categoryId,Integer level)throws Exception;
35 }
ProductDao
技术分享
  1 package cn.easybuy.dao.product;
  2 
  3 import java.sql.Connection;
  4 import java.sql.ResultSet;
  5 import java.sql.SQLException;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 
  9 import cn.easybuy.dao.BaseDaoImpl;
 10 import cn.easybuy.dao.product.ProductDao;
 11 import cn.easybuy.entity.News;
 12 import cn.easybuy.entity.Order;
 13 import cn.easybuy.entity.OrderDetail;
 14 import cn.easybuy.entity.Product;
 15 import cn.easybuy.param.ProductParam;
 16 import cn.easybuy.utils.EmptyUtils;
 17 import cn.easybuy.utils.Pager;
 18 import cn.easybuy.utils.Params;
 19 
 20 public class ProductDaoImpl extends BaseDaoImpl implements ProductDao {
 21 
 22     public ProductDaoImpl(Connection connection) {
 23         super(connection);
 24     }
 25 
 26     /**
 27      * 字段 和 列名 的对应
 28      *
 29      * @param rs
 30      * @return
 31      * @throws Exception
 32      */
 33     @Override
 34     public Product tableToClass(ResultSet rs) throws Exception {
 35         Product product = new Product();
 36         product.setId(rs.getInt("id"));
 37         product.setName(rs.getString("name"));
 38         product.setDescription(rs.getString("description"));
 39         product.setPrice(rs.getFloat("price"));
 40         product.setStock(rs.getInt("stock"));
 41         product.setCategoryLevel1Id(rs.getInt("categoryLevel1Id"));
 42         product.setCategoryLevel2Id(rs.getInt("categoryLevel2Id"));
 43         product.setCategoryLevel3Id(rs.getInt("categoryLevel3Id"));
 44         product.setFileName(rs.getString("fileName"));
 45         return product;
 46     }
 47 
 48     public Integer updateStock(Integer id, Integer quantity) {
 49        Integer count=0;
 50         try {
 51             Object[] params = new Object[] {quantity,id};
 52             String sql = " update easybuy_product set stock=? where id=? ";
 53             count=this.executeUpdate(sql, params);
 54         } catch (Exception e) {
 55             e.printStackTrace();
 56         }finally{
 57             this.closeResource();
 58             return count;
 59         }
 60     }
 61 
 62     @Override
 63     public Integer add(Product product) {
 64         Integer id=0;
 65         String sql=" insert into easybuy_product(name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,fileName,isDelete) values(?,?,?,?,?,?,?,?,?) ";
 66         try {
 67             Object param[]=new Object[]{product.getName(),product.getDescription(),product.getPrice(),product.getStock(),product.getCategoryLevel1Id(),product.getCategoryLevel2Id(),product.getCategoryLevel3Id(),product.getFileName(),0};
 68             id=this.executeInsert(sql,param);
 69             product.setId(id);
 70         } catch (Exception e) {
 71             e.printStackTrace();
 72         }finally{
 73             this.closeResource();
 74             return id;
 75         }
 76     }
 77 
 78     @Override
 79     public Integer update(Product product) {
 80         Integer count=0;
 81         try {
 82             Object[] params = new Object[] {product.getName(),product.getFileName(),product.getCategoryLevel1Id(),product.getCategoryLevel2Id(),product.getCategoryLevel3Id(),product.getId()};
 83             String sql = " update easybuy_product set name=?,fileName=?,categoryLevel1Id=?,categoryLevel3Id=?,categoryLevel3Id=? where id=? ";
 84             count=this.executeUpdate(sql, params);
 85         } catch (Exception e) {
 86             e.printStackTrace();
 87         }finally{
 88             this.closeResource();
 89             return count;
 90         }
 91     }
 92 
 93     @Override
 94     public Integer deleteProductById(Integer id) throws Exception {
 95         String sql = " delete from easybuy_product where id = ? ";
 96         Object params[] = new Object[] { id };
 97         Integer count=0;
 98         try{
 99             count=this.executeUpdate(sql.toString(), params);
100         }catch (Exception e) {
101             e.printStackTrace();
102         }finally{
103             this.closeResource();
104             return count;
105         }
106     }
107 
108     @Override
109     public Product getProductById(Integer id) throws Exception {
110         String sql = " select id,name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,fileName,isDelete from easybuy_product where id = ? ";
111         ResultSet resultSet = null;
112         Product product = null;
113         try {
114             Object params[] = new Object[] { id };
115             resultSet = this.executeQuery(sql, params);
116             while (resultSet.next()) {
117                 product = tableToClass(resultSet);
118             }
119         } catch (Exception e) {
120             e.printStackTrace();
121         } finally {
122             this.closeResource(resultSet);
123             this.closeResource();
124             return product;
125         }
126     }
127 
128     @Override
129     public List<Product> getProductList(Integer currentPageNo,Integer pageSize,String proName,Integer categoryId,Integer level) throws Exception {
130         List<Object> paramsList=new ArrayList<Object>();   
131         List<Product> productList=new ArrayList<Product>();
132         StringBuffer sql=new StringBuffer("  select id,name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,fileName,isDelete from easybuy_product  where 1=1 ");
133         ResultSet resultSet = null;
134         try {
135             if(EmptyUtils.isNotEmpty(proName)){
136                 sql.append(" and name like ? ");
137                 paramsList.add("%"+proName+"%");
138             }
139 
140             if(EmptyUtils.isNotEmpty(categoryId)){
141                 sql.append(" and (categoryLevel1Id = ? or categoryLevel2Id=? or categoryLevel3Id=? ) ");
142                 paramsList.add(categoryId);
143                 paramsList.add(categoryId);
144                 paramsList.add(categoryId);
145             }
146             int total = queryProductCount(proName,categoryId,level);
147             Pager pager = new Pager(total, pageSize, currentPageNo);
148             sql.append(" limit  " + (pager.getCurrentPage() - 1) * pager.getRowPerPage() + "," + pager.getRowPerPage());
149             resultSet=this.executeQuery(sql.toString(),paramsList.toArray());
150             while (resultSet.next()) {
151                 Product product = this.tableToClass(resultSet);
152                 productList.add(product);
153             }
154         } catch (SQLException e) {
155             e.printStackTrace();
156         } catch (Exception e) {
157             e.printStackTrace();
158         }finally{
159             this.closeResource(resultSet);
160             this.closeResource();
161         }
162                 
163         return productList;
164     }
165 
166     
167     @Override
168     public Integer queryProductCount(String proName,Integer categoryId,Integer level) throws Exception {
169         List<Object> paramsList=new ArrayList<Object>();   
170         Integer count=0;
171         StringBuffer sql=new StringBuffer("  select count(*) count from easybuy_product where 1=1 ");
172         if(EmptyUtils.isNotEmpty(proName)){
173             sql.append(" and name like ? ");
174             paramsList.add("%"+proName+"%");
175         }
176 
177         if(EmptyUtils.isNotEmpty(categoryId)){
178             sql.append(" and (categoryLevel1Id = ? or categoryLevel2Id=? or categoryLevel3Id=? ) ");
179             paramsList.add(categoryId);
180             paramsList.add(categoryId);
181             paramsList.add(categoryId);
182         }
183         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
184         try {
185             while (resultSet.next()) {
186                 count=resultSet.getInt("count");
187             }
188         } catch (SQLException e) {
189             e.printStackTrace();
190         } catch (Exception e) {
191             e.printStackTrace();
192         }finally{
193             this.closeResource(resultSet);
194             this.closeResource();
195         }
196         return count;
197     }
198     
199     
200 }
ProductDaoImpl

以上是dao.product层代码


 

技术分享
 1 package cn.easybuy.dao.user;
 2 
 3 import java.sql.SQLException;
 4 import java.util.List;
 5 
 6 import cn.easybuy.dao.IBaseDao;
 7 import cn.easybuy.entity.User;
 8 import cn.easybuy.param.UserParam;
 9 
10 /***
11  * UserDao 用户业务的dao层
12  * 从父类继承下的被使用的方法
13  * User getById(userId);
14  * Integer userDao.getRowCount(params);
15  * List<User> userDao.getRowList(params);
16  */
17 public interface UserDao extends IBaseDao {
18 
19     int add(User user) throws Exception;//新增用户信息
20 
21     int update(User user) throws Exception;//更新用户信息
22 
23     public int deleteUserById(String id) throws Exception;
24     
25     public List<User> getUserList(Integer currentPageNo,Integer pageSize)throws Exception;
26     
27     public Integer count() throws Exception;
28     
29     public User getUser(Integer id,String loginName) throws Exception;
30 }
UserDao
技术分享
  1 package cn.easybuy.dao.user;
  2 
  3 import java.sql.Connection;
  4 import java.sql.ResultSet;
  5 import java.sql.SQLException;
  6 import java.util.ArrayList;
  7 import java.util.List;
  8 
  9 import cn.easybuy.dao.BaseDaoImpl;
 10 import cn.easybuy.entity.Product;
 11 import cn.easybuy.entity.User;
 12 import cn.easybuy.param.UserParam;
 13 import cn.easybuy.utils.EmptyUtils;
 14 import cn.easybuy.utils.Pager;
 15 import cn.easybuy.utils.Params;
 16 
 17 /**
 18  * 用户dao
 19  */
 20 public class UserDaoImpl extends BaseDaoImpl implements UserDao {
 21 
 22     public UserDaoImpl(Connection connection) {
 23         super(connection);
 24     }
 25 
 26     @Override
 27     public User tableToClass(ResultSet rs) throws Exception {
 28         User user = new User();
 29         user.setLoginName(rs.getString("loginName"));
 30         user.setUserName(rs.getString("userName"));
 31         user.setPassword(rs.getString("password"));
 32         user.setSex(rs.getInt("sex"));
 33         user.setIdentityCode(rs.getString("identityCode"));
 34         user.setEmail(rs.getString("email"));
 35         user.setMobile(rs.getString("mobile"));
 36         user.setType(rs.getInt("type"));
 37         user.setId(rs.getInt("id"));
 38         return user;
 39     }
 40     /**
 41      * 保存用户
 42      *
 43      * @param user
 44      * @throws java.sql.SQLException
 45      */
 46     public int add(User user){//新增用户信息
 47         Integer id=0;
 48         try {
 49             String sql=" INSERT into easybuy_user(loginName,userName,password,sex,identityCode,email,mobile) values(?,?,?,?,?,?,?) ";
 50             try {
 51                 Object param[]=new Object[]{user.getLoginName(),user.getUserName(),user.getPassword(),user.getSex(),user.getIdentityCode(),user.getEmail(),user.getMobile()};
 52                 id=this.executeInsert(sql,param);
 53                 user.setId(id);
 54             } catch (Exception e) {
 55                 e.printStackTrace();
 56             }
 57         } catch (Exception e) {
 58             e.printStackTrace();
 59         }finally{
 60             this.closeResource();
 61         }
 62         return id;
 63     }
 64 
 65     //更新用户信息
 66     public int update(User user) {
 67         Integer count=0;
 68         try {
 69             Object[] params = new Object[] {user.getLoginName(),user.getUserName(),user.getType(),user.getSex(),user.getIdentityCode(),user.getEmail(),user.getMobile(),user.getId()};
 70             String sql = " UPDATE easybuy_user SET loginName=?,userName =?,type=?,sex =?, identityCode =?, email =?, mobile =? WHERE id =?  ";
 71             count=this.executeUpdate(sql, params);
 72         } catch (Exception e) {
 73             e.printStackTrace();
 74         }finally{
 75             this.closeResource();
 76             return count;
 77         }
 78     }
 79 
 80     @Override
 81     public int deleteUserById(String id) {
 82         Integer count=0;
 83         String sql = " delete from easybuy_user where id = ? ";
 84         Object params[] = new Object[] { id };
 85         try{
 86             this.executeUpdate(sql.toString(), params);
 87         }catch (Exception e) {
 88             e.printStackTrace();
 89         }finally{
 90             this.closeResource();
 91             return count;
 92         }
 93     }
 94 
 95     @Override
 96     public List<User> getUserList(Integer currentPageNo,Integer pageSize) throws Exception {
 97         List<Object> paramsList=new ArrayList<Object>();   
 98         List<User> userList=new ArrayList<User>();
 99         StringBuffer sql=new StringBuffer("  select id,loginName,password,userName,sex,identityCode,email,mobile,type from easybuy_user where 1=1 ");
100         ResultSet resultSet = null;
101         try {
102             int total = count();
103             Pager pager = new Pager(total, pageSize, currentPageNo);
104             sql.append(" limit  " + (pager.getCurrentPage() - 1) * pager.getRowPerPage() + "," + pager.getRowPerPage());
105             resultSet=this.executeQuery(sql.toString(),paramsList.toArray());
106             while (resultSet.next()) {
107                 User user = this.tableToClass(resultSet);
108                 userList.add(user);
109             }
110         }  catch (Exception e) {
111             e.printStackTrace();
112         }finally{
113             this.closeResource();
114             this.closeResource(resultSet);
115         }
116         return userList;
117     }
118     
119     public Integer count() throws Exception {
120         List<Object> paramsList=new ArrayList<Object>();   
121         StringBuffer sql=new StringBuffer(" select count(*) count from easybuy_user where 1=1 ");
122         Integer count=0;
123         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
124         try {
125             while (resultSet.next()) {
126                 count=resultSet.getInt("count");
127             }
128         } catch (SQLException e) {
129             e.printStackTrace();
130         } catch (Exception e) {
131             e.printStackTrace();
132         }finally{
133             this.closeResource();
134             this.closeResource(resultSet);
135         }
136         return count;
137     }
138     
139     
140     @Override
141     public User getUser(Integer id,String loginName) throws Exception {
142         List<Object> paramsList=new ArrayList<Object>();   
143         List<User> userList=new ArrayList<User>();
144         StringBuffer sql=new StringBuffer("  select id,loginName,userName,password,sex,identityCode,email,mobile,type from easybuy_user where 1=1  ");
145 
146         if(EmptyUtils.isNotEmpty(id)){
147             sql.append(" and id=? ");
148             paramsList.add(id);
149         }
150 
151         if(EmptyUtils.isNotEmpty(loginName)){
152             sql.append(" and loginName=? ");
153             paramsList.add(loginName);
154         }
155 
156         ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
157         User user=null;
158         try {
159             while (resultSet.next()) {
160                 user = this.tableToClass(resultSet);
161             }
162         } catch (SQLException e) {
163             e.printStackTrace();
164         } catch (Exception e) {
165             e.printStackTrace();
166         }finally{
167             this.closeResource();
168             this.closeResource(resultSet);
169         }
170         return user;
171     }
172 
173 }
UserDaoImpl

以上是dao.user层代码


 

技术分享
 1 package cn.easybuy.entity;
 2 
 3 import java.io.Serializable;
 4 import java.util.Date;
 5 
 6 public class News implements Serializable{
 7     private Integer id;//ID
 8     private String title;//标题
 9     private String content;//内容
10     private Date createTime;//创建时间
11 
12     
13 
14     public Integer getId() {
15         return id;
16     }
17 
18     public void setId(Integer id) {
19         this.id = id;
20     }
21 
22     public String getTitle() {
23         return title;
24     }
25 
26     public void setTitle(String title) {
27         this.title = title;
28     }
29 
30     public String getContent() {
31         return content;
32     }
33 
34     public void setContent(String content) {
35         this.content = content;
36     }
37 
38     public Date getCreateTime() {
39         return createTime;
40     }
41 
42     public void setCreateTime(Date createTime) {
43         this.createTime = createTime;
44     }
45 }
News
技术分享
  1 package cn.easybuy.entity;
  2 
  3 import java.io.Serializable;
  4 import java.util.Date;
  5 import java.util.List;
  6 
  7 public class Order implements Serializable {
  8 
  9     private Integer id;//ID
 10     private String serialNumber;//订单号
 11     private Integer userId;//用户id
 12     private String userAddress;//收货地址
 13     private Date createTime;//创建时间
 14     private Float cost;//订单总计价格
 15     
 16     private String loginName;//登录名称
 17     private List<OrderDetail> orderDetailList;//订单明细列表
 18 
 19     public List<OrderDetail> getOrderDetailList() {
 20         return orderDetailList;
 21     }
 22 
 23     public void setOrderDetailList(List<OrderDetail> orderDetailList) {
 24         this.orderDetailList = orderDetailList;
 25     }
 26 
 27     public int getId() {
 28         return id;
 29     }
 30 
 31     public void setId(int id) {
 32         this.id = id;
 33     }
 34     
 35 
 36     public String getLoginName() {
 37         return loginName;
 38     }
 39 
 40     public void setLoginName(String loginName) {
 41         this.loginName = loginName;
 42     }
 43 
 44     public Date getCreateTime() {
 45         return createTime;
 46     }
 47 
 48     public void setCreateTime(Date createTime) {
 49         this.createTime = createTime;
 50     }
 51 
 52     public Float getCost() {
 53         return cost;
 54     }
 55 
 56     public void setCost(Float cost) {
 57         this.cost = cost;
 58     }
 59 
 60     public Integer getUserId() {
 61         return userId;
 62     }
 63 
 64     public void setUserId(Integer userId) {
 65         this.userId = userId;
 66     }
 67 
 68     public void setId(Integer id) {
 69         this.id = id;
 70     }
 71 
 72     public String getUserAddress() {
 73         return userAddress;
 74     }
 75 
 76     public void setUserAddress(String userAddress) {
 77         this.userAddress = userAddress;
 78     }
 79 
 80     @Override
 81     public int hashCode() {        
 82         return id;
 83     }
 84 
 85     @Override
 86     public boolean equals(Object obj) {
 87         if(obj instanceof Order){
 88             if(((Order)obj).id==id){
 89                 return true;
 90             }            
 91         }    
 92         return false;
 93     }
 94 
 95     public String getSerialNumber() {
 96         return serialNumber;
 97     }
 98 
 99     public void setSerialNumber(String serialNumber) {
100         this.serialNumber = serialNumber;
101     }
102 }
Order
技术分享
 1 package cn.easybuy.entity;
 2 
 3 import java.io.Serializable;
 4 
 5 public class OrderDetail implements Serializable{
 6     private Integer id;//ID
 7     private Integer orderId;//订单ID
 8     private Integer quantity;//数量 
 9     private Float cost;//单价
10     private Integer productId;//商品id
11 
12     private Product product;//商品
13 
14     public Integer getProductId() {
15         return productId;
16     }
17 
18     public void setProductId(Integer productId) {
19         this.productId = productId;
20     }
21 
22     public Integer getId() {
23         return id;
24     }
25 
26     public void setId(Integer id) {
27         this.id = id;
28     }
29 
30 
31     public Integer getOrderId() {
32         return orderId;
33     }
34 
35     public void setOrderId(Integer orderId) {
36         this.orderId = orderId;
37     }
38 
39     public Product getProduct() {
40         return product;
41     }
42 
43     public void setProduct(Product product) {
44         this.product = product;
45     }
46 
47 
48     public Integer getQuantity() {
49         return quantity;
50     }
51 
52     public void setQuantity(Integer quantity) {
53         this.quantity = quantity;
54     }
55 
56     public Float getCost() {
57         return cost;
58     }
59 
60     public void setCost(Float cost) {
61         this.cost = cost;
62     }
63 }
OrderDetail
技术分享Product
技术分享ProductCategory
技术分享User
技术分享UserAddress

 以上是entity类代码


 

技术分享
 1 package cn.easybuy.filter;
 2 import java.io.IOException;
 3 import javax.servlet.Filter;
 4 import javax.servlet.FilterChain;
 5 import javax.servlet.FilterConfig;
 6 import javax.servlet.ServletException;
 7 import javax.servlet.ServletRequest;
 8 import javax.servlet.ServletResponse;
 9 import javax.servlet.annotation.WebFilter;
10 import javax.servlet.http.HttpServletRequest;
11 import javax.servlet.http.HttpServletResponse;
12 import javax.servlet.http.HttpSession;
13 
14 import cn.easybuy.entity.User;
15 import cn.easybuy.utils.EmptyUtils;
16 
17 @WebFilter(urlPatterns = {"/admin/productCategory","/admin/product","/admin/user","/admin/order"})
18 public class AdminUserPowerFilter implements Filter {
19     
20     String extUrl="queryUserList";
21     
22     public void destroy() {        
23         
24     }
25     
26     public void doFilter(ServletRequest request, ServletResponse response,
27             FilterChain chain) throws IOException, ServletException {
28         HttpServletRequest req=(HttpServletRequest)request;
29         HttpServletResponse resp=(HttpServletResponse)response;
30         HttpSession session = req.getSession();
31         User user=(User) session.getAttribute("loginUser");
32         if(null==user){
33             resp.sendRedirect(req.getContextPath()+"/Login?action=toLogin");
34             return;            
35         }
36         String action=req.getParameter("action");
37         if(EmptyUtils.isEmpty(action)){
38             resp.sendRedirect(req.getContextPath()+"/Login?action=toLogin");
39             return;        
40         }else{
41             if(extUrl.contains(action) && user.getType()!=1){
42                 resp.sendRedirect(req.getContextPath()+"/Login?action=toLogin");
43                 return;        
44             }
45         }
46         chain.doFilter(request, response);
47     }
48     public void init(FilterConfig filterConfig) throws ServletException {        
49     }    
50 }
AdminUserPowerFilter
技术分享
 1 package cn.easybuy.filter;
 2 
 3 import java.io.IOException;
 4 
 5 import javax.servlet.Filter;
 6 import javax.servlet.FilterChain;
 7 import javax.servlet.FilterConfig;
 8 import javax.servlet.ServletException;
 9 import javax.servlet.ServletRequest;
10 import javax.servlet.ServletResponse;
11 import javax.servlet.annotation.WebFilter;
12 import javax.servlet.annotation.WebInitParam;
13 
14 @WebFilter(urlPatterns = {"/*"},filterName="EncodeFilter" ,initParams = {@WebInitParam(name = "encode", value = "http://www.mamicode.com/utf-8")}) 
15 public class EncodeFilter implements Filter {
16     private String encode=null;
17     public void destroy() {
18         encode=null;
19     }
20 
21     public void doFilter(ServletRequest request, ServletResponse response,
22             FilterChain chain) throws IOException, ServletException {
23         if(null==request.getCharacterEncoding()){
24             request.setCharacterEncoding(encode);
25         }
26         chain.doFilter(request, response);
27     }
28 
29     public void init(FilterConfig filterConfig) throws ServletException {
30         String encode=filterConfig.getInitParameter("encode");        
31         if(this.encode==null){
32             this.encode=encode;
33         }
34     }
35     
36 }
EncodeFilter

 

以上是filter类代码


技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.News;
 4 
 5 public class NewsParams extends News{
 6     
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10 
11     private String sort;
12     
13     private boolean isPage=false;
14     
15     public Integer getStartIndex() {
16         return startIndex;
17     }
18 
19     public void setStartIndex(Integer startIndex) {
20         this.startIndex = startIndex;
21     }
22 
23     public Integer getPageSize() {
24         return pageSize;
25     }
26 
27     public void setPageSize(Integer pageSize) {
28         this.pageSize = pageSize;
29     }
30     
31     public String getSort() {
32         return sort;
33     }
34 
35     public void setSort(String sort) {
36         this.sort = sort;
37     }
38 
39     public boolean isPage() {
40         return isPage;
41     }
42 
43     public void setPage(boolean isPage) {
44         this.isPage = isPage;
45     }
46 
47     public void openPage(Integer startIndex, Integer pageSize) {
48         this.isPage = true;
49         this.startIndex = startIndex;
50         this.pageSize = pageSize;
51     }
52 }
NewsParams

 

技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.OrderDetail;
 4 
 5 public class OrderDetailParam extends OrderDetail{
 6 
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10     
11     private boolean isPage=false;
12     
13     private String sort;
14     
15     public void openPage(Integer startIndex, Integer pageSize) {
16         this.isPage = true;
17         this.startIndex = startIndex;
18         this.pageSize = pageSize;
19     }
20 
21     public Integer getStartIndex() {
22         return startIndex;
23     }
24 
25     public void setStartIndex(Integer startIndex) {
26         this.startIndex = startIndex;
27     }
28 
29     public Integer getPageSize() {
30         return pageSize;
31     }
32 
33     public void setPageSize(Integer pageSize) {
34         this.pageSize = pageSize;
35     }
36 
37     public boolean isPage() {
38         return isPage;
39     }
40 
41     public void setPage(boolean isPage) {
42         this.isPage = isPage;
43     }
44 
45     public String getSort() {
46         return sort;
47     }
48 
49     public void setSort(String sort) {
50         this.sort = sort;
51     }
52     
53     
54     
55     
56 }
OrderDetailParam

 

技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.Order;
 4 
 5 public class OrderParams extends Order{
 6     
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10     
11     private boolean isPage=false;
12     
13     private String sort;
14 
15     public Integer getStartIndex() {
16         return startIndex;
17     }
18 
19     public void setStartIndex(Integer startIndex) {
20         this.startIndex = startIndex;
21     }
22 
23     public Integer getPageSize() {
24         return pageSize;
25     }
26 
27     public void setPageSize(Integer pageSize) {
28         this.pageSize = pageSize;
29     }
30 
31     public boolean isPage() {
32         return isPage;
33     }
34 
35     public void setPage(boolean isPage) {
36         this.isPage = isPage;
37     }
38 
39     public void openPage(Integer startIndex, Integer pageSize) {
40         this.isPage = true;
41         this.startIndex = startIndex;
42         this.pageSize = pageSize;
43     }
44 
45     public String getSort() {
46         return sort;
47     }
48 
49     public void setSort(String sort) {
50         this.sort = sort;
51     }
52     
53     
54 }
OrderParams
技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.ProductCategory;
 4 
 5 public class ProductCategoryParam extends ProductCategory{
 6     
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10     
11     private boolean isPage=false;
12     
13     private String sort;
14 
15     public Integer getStartIndex() {
16         return startIndex;
17     }
18 
19     public void setStartIndex(Integer startIndex) {
20         this.startIndex = startIndex;
21     }
22 
23     public Integer getPageSize() {
24         return pageSize;
25     }
26 
27     public void setPageSize(Integer pageSize) {
28         this.pageSize = pageSize;
29     }
30 
31     public boolean isPage() {
32         return isPage;
33     }
34 
35     public void setPage(boolean isPage) {
36         this.isPage = isPage;
37     }
38     
39     public void openPage(Integer startIndex, Integer pageSize) {
40         this.isPage = true;
41         this.startIndex = startIndex;
42         this.pageSize = pageSize;
43     }
44 
45     public String getSort() {
46         return sort;
47     }
48 
49     public void setSort(String sort) {
50         this.sort = sort;
51     }
52     
53     
54     
55     
56 
57 }
ProductCategoryParam

 

技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.Product;
 4 
 5 public class ProductParam extends Product{
 6     
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10     
11     private boolean isPage=false;
12     
13     private String sort;
14     
15     private String keyword;
16     
17     private Integer categoryId;
18 
19     public Integer getCategoryId() {
20         return categoryId;
21     }
22 
23     public void setCategoryId(Integer categoryId) {
24         this.categoryId = categoryId;
25     }
26 
27     public String getKeyword() {
28         return keyword;
29     }
30 
31     public void setKeyword(String keyword) {
32         this.keyword = keyword;
33     }
34 
35     public Integer getStartIndex() {
36         return startIndex;
37     }
38 
39     public void setStartIndex(Integer startIndex) {
40         this.startIndex = startIndex;
41     }
42 
43     public Integer getPageSize() {
44         return pageSize;
45     }
46 
47     public void setPageSize(Integer pageSize) {
48         this.pageSize = pageSize;
49     }
50 
51     public boolean isPage() {
52         return isPage;
53     }
54 
55     public void setPage(boolean isPage) {
56         this.isPage = isPage;
57     }
58     
59     public void openPage(Integer startIndex, Integer pageSize) {
60         this.isPage = true;
61         this.startIndex = startIndex;
62         this.pageSize = pageSize;
63     }
64 
65     public String getSort() {
66         return sort;
67     }
68 
69     public void setSort(String sort) {
70         this.sort = sort;
71     }
72     
73     
74     
75     
76 }
ProductParam
技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.UserAddress;
 4 
 5 public class UserAddressParam extends UserAddress{
 6     
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10     
11     private boolean isPage=false;
12     
13     private String sort;
14 
15     public Integer getStartIndex() {
16         return startIndex;
17     }
18 
19     public void setStartIndex(Integer startIndex) {
20         this.startIndex = startIndex;
21     }
22 
23     public Integer getPageSize() {
24         return pageSize;
25     }
26 
27     public void setPageSize(Integer pageSize) {
28         this.pageSize = pageSize;
29     }
30     
31     
32     
33     public boolean isPage() {
34         return isPage;
35     }
36 
37     public void setPage(boolean isPage) {
38         this.isPage = isPage;
39     }
40 
41     public void openPage(Integer startIndex, Integer pageSize) {
42         this.isPage = true;
43         this.startIndex = startIndex;
44         this.pageSize = pageSize;
45     }
46 
47     public String getSort() {
48         return sort;
49     }
50 
51     public void setSort(String sort) {
52         this.sort = sort;
53     }
54     
55     
56 }
UserAddressParam
技术分享
 1 package cn.easybuy.param;
 2 
 3 import cn.easybuy.entity.User;
 4 
 5 public class UserParam extends User{
 6     
 7     private Integer startIndex;
 8     
 9     private Integer pageSize;
10     
11     private boolean isPage=false;
12     
13     private String sort;
14 
15     public Integer getStartIndex() {
16         return startIndex;
17     }
18 
19     public void setStartIndex(Integer startIndex) {
20         this.startIndex = startIndex;
21     }
22 
23     public Integer getPageSize() {
24         return pageSize;
25     }
26 
27     public void setPageSize(Integer pageSize) {
28         this.pageSize = pageSize;
29     }
30 
31     public boolean isPage() {
32         return isPage;
33     }
34 
35     public void setPage(boolean isPage) {
36         this.isPage = isPage;
37     }
38 
39     public void openPage(Integer startIndex, Integer pageSize) {
40         this.isPage = true;
41         this.startIndex = startIndex;
42         this.pageSize = pageSize;
43     }
44 
45     public String getSort() {
46         return sort;
47     }
48 
49     public void setSort(String sort) {
50         this.sort = sort;
51     }
52     
53     
54     
55 }
UserParam

 

以上是param类代码


 

技术分享
 1 package cn.easybuy.service.news;
 2 
 3 import java.util.List;
 4 
 5 import cn.easybuy.entity.News;
 6 import cn.easybuy.param.NewsParams;
 7 import cn.easybuy.utils.Pager;
 8 
 9 public interface NewsService{
10     /**
11      * 保存新闻
12      * @param news
13      */
14     void addNews(News news);//保存新闻
15     /**
16      * 根据id查询新闻
17      * @param parameter
18      * @return
19      */
20     News findNewsById(String parameter);
21     /***
22      * 删除新闻
23      * @param parameter
24      */
25     void deleteNews(String parameter);
26     /***
27      * 查询新闻列表
28      * @param param
29      * @return
30      */
31     List<News> queryNewsList(NewsParams param);
32     /***
33      * 查询数目
34      * @param param
35      * @return
36      */
37     Integer queryNewsCount(NewsParams param);
38 
39 }
NewsService
技术分享
  1 package cn.easybuy.service.news;
  2 
  3 import java.sql.Connection;
  4 import java.sql.SQLException;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import cn.easybuy.dao.news.NewsDao;
  9 import cn.easybuy.dao.news.NewsDaoImpl;
 10 import cn.easybuy.entity.News;
 11 import cn.easybuy.param.NewsParams;
 12 import cn.easybuy.utils.DataSourceUtil;
 13 import cn.easybuy.utils.Pager;
 14 import cn.easybuy.utils.Params;
 15 
 16 /**
 17  *
 18  */
 19 public class NewsServiceImpl implements NewsService {
 20 
 21     public void deleteNews(String id) {// 删除新闻
 22         Connection connection=null;
 23         try {
 24             connection=DataSourceUtil.openConnection();
 25             NewsDao newsDao = new NewsDaoImpl(connection);
 26             newsDao.deleteById(Integer.parseInt(id));
 27         } catch (Exception e) {
 28             e.printStackTrace();
 29         }finally{
 30             DataSourceUtil.closeConnection(connection);
 31         }
 32     }
 33 
 34     public News findNewsById(String id) {// 根据ID获取新闻
 35         News news = null;
 36         Connection connection=null;
 37         try {
 38             connection=DataSourceUtil.openConnection();
 39             NewsDao newsDao = new NewsDaoImpl(connection);
 40             news = newsDao.getNewsById(Integer.parseInt(id));
 41         } catch (Exception e) {
 42             e.printStackTrace();
 43         } finally {
 44             DataSourceUtil.closeConnection(connection);
 45         }
 46         return news;
 47     }
 48 
 49     public void addNews(News news) {// 保存新闻
 50         Connection connection = null;
 51         try {
 52             connection = DataSourceUtil.openConnection();
 53             NewsDao newsDao = new NewsDaoImpl(connection);
 54             newsDao.add(news);
 55         } catch (Exception e) {
 56             e.printStackTrace();
 57         } finally {
 58             DataSourceUtil.closeConnection(connection);
 59         }
 60     }
 61 
 62     public void updateNews(News news) {// 更新留言
 63         Connection connection = null;
 64         try {
 65             connection = DataSourceUtil.openConnection();
 66             NewsDao newsDao = new NewsDaoImpl(connection);
 67             newsDao.update(news);
 68         } catch (Exception e) {
 69             e.printStackTrace();
 70         } finally {
 71             DataSourceUtil.closeConnection(connection);
 72         }
 73     }
 74 
 75     
 76     public List<News> queryNewsPageList(NewsParams param) throws SQLException {
 77         List<News> newsList=new ArrayList<News>();
 78         Connection connection = null;
 79         NewsDao newsDao =null;
 80         try {
 81             connection = DataSourceUtil.openConnection();
 82             newsDao= new NewsDaoImpl(connection);
 83             newsList=newsDao.queryNewsList(param);
 84         } catch (Exception e) {
 85             e.printStackTrace();
 86         } finally {
 87             System.out.println(connection.isClosed());
 88             DataSourceUtil.closeConnection(connection);
 89         }
 90         return newsList;
 91     }
 92     
 93     @Override
 94     public List<News> queryNewsList(NewsParams param) {
 95         List<News> newsList=new ArrayList<News>();
 96         Connection connection = null;
 97         try {
 98             connection = DataSourceUtil.openConnection();
 99             NewsDao newsDao = new NewsDaoImpl(connection);
100             newsList=newsDao.queryNewsList(param);
101         } catch (Exception e) {
102             e.printStackTrace();
103         } finally {
104             DataSourceUtil.closeConnection(connection);
105         }
106         return newsList;
107     }
108 
109     @Override
110     public Integer queryNewsCount(NewsParams param) {
111         Connection connection = null;
112         Integer count=0;
113         try {
114             connection = DataSourceUtil.openConnection();
115             NewsDao newsDao = new NewsDaoImpl(connection);
116             count=newsDao.queryNewsCount(param);
117         } catch (Exception e) {
118             e.printStackTrace();
119         } finally {
120             DataSourceUtil.closeConnection(connection);
121             return count;
122         }
123     }
124 
125 }
NewsServiceImpl

 

以上是service.news类代码


 

技术分享
 1 package cn.easybuy.service.order;
 2 
 3 import cn.easybuy.utils.ShoppingCart;
 4 
 5 public interface CartService {
 6 
 7     public ShoppingCart modifyShoppingCart(String productId,String quantityStr,ShoppingCart cart) throws Exception;
 8 
 9     public ShoppingCart calculate(ShoppingCart cart)throws Exception;
10 }
CartService

 

技术分享
 1 package cn.easybuy.service.order;
 2 
 3 import java.sql.Connection;
 4 import cn.easybuy.service.order.CartService;
 5 import cn.easybuy.utils.EmptyUtils;
 6 import cn.easybuy.utils.ShoppingCart;
 7 import cn.easybuy.utils.ShoppingCartItem;
 8 
 9 
10 public class CartServiceImpl implements CartService {
11     
12     @Override
13     public ShoppingCart modifyShoppingCart(String productId, String quantityStr, ShoppingCart cart) throws Exception {
14         Integer quantity = 0;
15         Connection connection = null;
16         if (!EmptyUtils.isEmpty(quantityStr))
17             quantity = Integer.parseInt(quantityStr);
18         //便利购物车寻找该商品 修改其数量
19         for (ShoppingCartItem item : cart.getItems()) {
20             if (item.getProduct().getId().toString().equals(productId)) {
21                 if (quantity == 0 || quantity < 0) {
22                     cart.getItems().remove(item);
23                     break;
24                 } else {
25                     item.setQuantity(quantity);
26                 }
27             }
28         }
29         //重新计算金额
30         calculate(cart);
31         return cart;
32     }
33 
34     /**
35      * 核算购物车的金额
36      *
37      * @param cart
38      * @return
39      * @throws Exception
40      */
41     @Override
42     public ShoppingCart calculate(ShoppingCart cart) throws Exception {
43         double sum = 0.0;
44         for (ShoppingCartItem item : cart.getItems()) {
45             sum = sum + item.getQuantity() * item.getProduct().getPrice();
46             item.setCost(item.getQuantity() * item.getProduct().getPrice());
47         }
48         cart.setSum(sum);
49         return cart;
50     }
51 }
CartServiceImpl
技术分享
 1 package cn.easybuy.service.order;
 2 import java.util.List;
 3 import cn.easybuy.entity.Order;
 4 import cn.easybuy.entity.OrderDetail;
 5 import cn.easybuy.entity.User;
 6 import cn.easybuy.utils.ShoppingCart;
 7 
 8 /**
 9  * OrderService接口方法:
10  * (1)结算订单(返回类型:Order对象,参数:ShoppingCart对象、User对象、收货地址)。
11  * (2)根据查询条件,分页显示订单信息列表(返回类型:List<Order>,参数:当前页码、页码容量,用户id)。
12  * (3)根据条件查询订单表总记录数(返回类型:int,参数:用户id)。
13  * (4)根据订单id查询订单明细列表(返回类型:List<OrderDetail>,参数:订单id)。
14  *
15  */
16 public interface OrderService {
17     
18     public Order payShoppingCart(ShoppingCart cart, User user,String address);
19     
20     public List<Order> getOrderList(Integer userId,
21                                     Integer currentPageNo,
22                                     Integer pageSize);
23 
24     public int count(Integer userId);
25     
26     public List<OrderDetail> getOrderDetailList(Integer orderId);
27 
28 }
OrderService
技术分享
  1 package cn.easybuy.service.order;
  2 
  3 import java.sql.Connection;
  4 import java.sql.SQLException;
  5 import java.util.*;
  6 
  7 import cn.easybuy.dao.order.*;
  8 import cn.easybuy.dao.product.ProductDao;
  9 import cn.easybuy.dao.product.ProductDaoImpl;
 10 import cn.easybuy.utils.*;
 11 import cn.easybuy.entity.Order;
 12 import cn.easybuy.entity.OrderDetail;
 13 import cn.easybuy.entity.User;
 14 
 15 public class OrderServiceImpl implements OrderService {
 16 
 17     /**
 18      * 结算购物车物品包含以下步骤:
 19      * 1.生成订单
 20      * 2.生成订单明细
 21      * 3.更新商品表,减库存
 22      * 注意加入事物的控制
 23      */
 24 
 25     @Override
 26     public Order payShoppingCart(ShoppingCart cart, User user, String address) {
 27         // TODO Auto-generated method stub
 28         Connection connection = null;
 29         Order order = new Order();
 30         try {
 31             connection = DataSourceUtil.openConnection();
 32             connection.setAutoCommit(false);
 33             ProductDao productDao = new ProductDaoImpl(connection);
 34             OrderDao orderDao = new OrderDaoImpl(connection);
 35             OrderDetailDao orderDetailDao = new OrderDetailDaoImpl(connection);
 36             //增加订单
 37             order.setUserId(user.getId());
 38             order.setLoginName(user.getLoginName());
 39             order.setUserAddress(address);
 40             order.setCreateTime(new Date());
 41             order.setCost(cart.getTotalCost());
 42             order.setSerialNumber(StringUtils.randomUUID());
 43             orderDao.add(order);
 44             //增加订单对应的明细信息
 45             for (ShoppingCartItem item : cart.getItems()) {
 46                 OrderDetail orderDetail = new OrderDetail();
 47                 orderDetail.setOrderId(order.getId());
 48                 orderDetail.setCost(item.getCost());
 49                 orderDetail.setProduct(item.getProduct());
 50                 orderDetail.setQuantity(item.getQuantity());
 51                 orderDetailDao.add(orderDetail);
 52                 //更新商品表的库存
 53                 productDao.updateStock(item.getProduct().getId(), item.getQuantity());
 54                 connection.commit();
 55             }
 56         } catch (Exception e) {
 57             // TODO: handle exception
 58             e.printStackTrace();
 59             try {
 60                 connection.rollback();
 61             } catch (SQLException e1) {
 62                 e1.printStackTrace();
 63             }
 64             order = null;
 65         } finally {
 66             try {
 67                 connection.setAutoCommit(true);
 68                 DataSourceUtil.closeConnection(connection);
 69             } catch (SQLException e) {
 70                 e.printStackTrace();
 71             }
 72         }
 73         return order;
 74     }
 75 
 76     @Override
 77     public List<Order> getOrderList(Integer userId, Integer currentPageNo, Integer pageSize) {
 78         Connection connection = null;
 79         List<Order> orderList = new ArrayList<Order>();
 80         try {
 81             connection = DataSourceUtil.openConnection();
 82             OrderDao orderDao = new OrderDaoImpl(connection);
 83             OrderDetailDao orderDetailDao=new OrderDetailDaoImpl(connection);
 84             orderList = orderDao.getOrderList(userId, currentPageNo, pageSize);
 85             for(Order order:orderList){
 86                 order.setOrderDetailList(orderDetailDao.getOrderDetailList(order.getId()));
 87             }
 88         } catch (Exception e) {
 89             e.printStackTrace();
 90         } finally {
 91             DataSourceUtil.closeConnection(connection);
 92             return orderList;
 93         }
 94     }
 95 
 96     @Override
 97     public int count(Integer userId) {
 98         Connection connection = null;
 99         Integer count=0;
100         try {
101             connection = DataSourceUtil.openConnection();
102             OrderDao orderDao = new OrderDaoImpl(connection);
103             count=orderDao.count(userId);
104         } catch (Exception e) {
105             e.printStackTrace();
106         } finally {
107             DataSourceUtil.closeConnection(connection);
108             return count;
109         }
110     }
111 
112     /**
113      * 调用dao接口:OrderDetailMapper的方法实现
114      */
115     @Override
116     public List<OrderDetail> getOrderDetailList(Integer orderId) {
117         Connection connection = null;
118         List<OrderDetail> orderDetailList = new ArrayList<OrderDetail>();
119         try {
120             connection = DataSourceUtil.openConnection();
121             OrderDetailDao orderDetailDao = new OrderDetailDaoImpl(connection);
122             orderDetailList = orderDetailDao.getOrderDetailList(orderId);
123         } catch (Exception e) {
124             e.printStackTrace();
125         } finally {
126             DataSourceUtil.closeConnection(connection);
127             return orderDetailList;
128         }
129     }
130 }
OrderServiceImpl

 

以上是service.order类代码


技术分享
 1 package cn.easybuy.service.product;
 2 
 3 import cn.easybuy.entity.ProductCategory;
 4 import cn.easybuy.param.ProductCategoryParam;
 5 import cn.easybuy.utils.Params;
 6 import cn.easybuy.utils.ProductCategoryVo;
 7 
 8 import java.util.List;
 9 
10 public interface ProductCategoryService {
11     /**
12      * 根据id查询商品分类
13      * @param id
14      * @return
15      */
16     public ProductCategory getById(Integer id);
17     /**
18      * 查询商品分类列表
19      * @param params
20      * @return
21      */
22     public List<ProductCategory> queryProductCategoryList(ProductCategoryParam params);
23     /**
24      * 查询数目
25      * @param params
26      * @return
27      */
28     public int queryProductCategoryCount(ProductCategoryParam params);
29     /**
30      * 修改商品分类
31      * @param params
32      */
33     public void modifyProductCategory(ProductCategory productCategory);
34     /**
35      * 添加商品分类
36      * @param params
37      */
38     public void addProductCategory(ProductCategory productCategory);
39     /**
40      * 根据id删除
41      * @param id
42      */
43     public void deleteById(Integer id);
44     /**
45      * 查询全部的商品分类
46      * @return
47      */
48     public List<ProductCategoryVo> queryAllProductCategoryList();
49 }
ProductCategoryService
技术分享
  1 package cn.easybuy.service.product;
  2 
  3 import cn.easybuy.dao.product.ProductCategoryDao;
  4 import cn.easybuy.dao.product.ProductCategoryDaoImpl;
  5 import cn.easybuy.entity.ProductCategory;
  6 import cn.easybuy.param.ProductCategoryParam;
  7 import cn.easybuy.utils.DataSourceUtil;
  8 import cn.easybuy.utils.EmptyUtils;
  9 import cn.easybuy.utils.Params;
 10 import cn.easybuy.utils.ProductCategoryVo;
 11 
 12 import java.sql.Connection;
 13 import java.util.ArrayList;
 14 import java.util.List;
 15 
 16 public class ProductCategoryServiceImpl implements ProductCategoryService {
 17     /**
 18      *
 19      * @param id
 20      * @return
 21      */
 22     @Override
 23     public ProductCategory getById(Integer id) {
 24         Connection connection = null;
 25         ProductCategory productCategory = null;
 26         try {
 27             connection = DataSourceUtil.openConnection();
 28             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
 29             productCategory =productCategoryDao.queryProductCategoryById(id);
 30         } catch (Exception e) {
 31             e.printStackTrace();
 32         } finally {
 33             DataSourceUtil.closeConnection(connection);
 34         }
 35         return productCategory;
 36     }
 37 
 38     @Override
 39     public List<ProductCategory> queryProductCategoryList(ProductCategoryParam params) {
 40         Connection connection = null;
 41         List<ProductCategory> rtn = null;
 42         try {
 43             connection = DataSourceUtil.openConnection();
 44             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
 45             rtn = productCategoryDao.queryProductCategorylist(params);
 46         } catch (Exception e) {
 47             e.printStackTrace();
 48         } finally {
 49             DataSourceUtil.closeConnection(connection);
 50         }
 51         return rtn;
 52     }
 53 
 54     @Override
 55     public int queryProductCategoryCount(ProductCategoryParam params) {
 56         Connection connection = null;
 57         int rtn = 0;
 58         try {
 59             connection = DataSourceUtil.openConnection();
 60             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
 61             rtn = productCategoryDao.queryProductCategoryCount(params);
 62         } catch (Exception e) {
 63             e.printStackTrace();
 64         } finally {
 65             DataSourceUtil.closeConnection(connection);
 66         }
 67         return rtn;
 68     }
 69 
 70     @Override
 71     public void modifyProductCategory(ProductCategory productCategory) {
 72         Connection connection = null;
 73         try {
 74             connection = DataSourceUtil.openConnection();
 75             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
 76             productCategoryDao.update(productCategory);
 77         } catch (Exception e) {
 78             e.printStackTrace();
 79         } finally {
 80             DataSourceUtil.closeConnection(connection);
 81         }
 82     }
 83     /**
 84      * 新增商品分类
 85      */
 86     @Override
 87     public void addProductCategory(ProductCategory productCategory) {
 88         Connection connection = null;
 89         try {
 90             connection = DataSourceUtil.openConnection();
 91             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
 92             productCategoryDao.add(productCategory);
 93         } catch (Exception e) {
 94             e.printStackTrace();
 95         } finally {
 96             DataSourceUtil.closeConnection(connection);
 97         }
 98     }
 99     /**
100      * 根据Id删除商品
101      * @param id
102      */
103     @Override
104     public void deleteById(Integer id) {
105         Connection connection = null;
106         try {
107             connection = DataSourceUtil.openConnection();
108             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
109             productCategoryDao.deleteById(id);
110         } catch (Exception e) {
111             e.printStackTrace();
112         } finally {
113             DataSourceUtil.closeConnection(connection);
114         }
115     }
116     /**
117      * 查询全部的商品分类
118      * @return
119      */
120     @Override
121     public List<ProductCategoryVo> queryAllProductCategoryList() {
122         //查询一级分类的列表
123         List<ProductCategoryVo> productCategory1VoList = new ArrayList<ProductCategoryVo>();
124         //查询一级分类
125         List<ProductCategory> productCategory1List = getProductCategories(null);
126         //查询二级分类
127         for (ProductCategory product1Category : productCategory1List) {
128             //封装一级分类
129             ProductCategoryVo productCategoryVo = new ProductCategoryVo();
130             productCategoryVo.setProductCategory(product1Category);
131             List<ProductCategoryVo> productCategoryVo1ChildList = new ArrayList<ProductCategoryVo>();
132             //根据一级分类查询二级分类
133             List<ProductCategory> productCategory2List = getProductCategories(product1Category.getId());
134             for (ProductCategory productCategory2 : productCategory2List) {
135                 ProductCategoryVo productCategoryVo2 = new ProductCategoryVo();
136                 productCategoryVo1ChildList.add(productCategoryVo2);
137                 productCategoryVo2.setProductCategory(productCategory2);
138                 List<ProductCategoryVo> productCategoryVo2ChildList = new ArrayList<ProductCategoryVo>();
139                 productCategoryVo2.setProductCategoryVoList(productCategoryVo2ChildList);
140                 //根据二级分类查询三级分类的列表
141                 List<ProductCategory> productCategory3List = getProductCategories(productCategory2.getId());
142                 for (ProductCategory productCategory3 : productCategory3List) {
143                     ProductCategoryVo productCategoryVo3 = new ProductCategoryVo();
144                     productCategoryVo3.setProductCategory(productCategory3);
145                     productCategoryVo2ChildList.add(productCategoryVo3);
146                 }
147             }
148             productCategoryVo.setProductCategoryVoList(productCategoryVo1ChildList);
149             productCategory1VoList.add(productCategoryVo);
150         }
151         return productCategory1VoList;
152     }
153     /**
154      * 查询子分类
155      * @param parentId
156      * @return
157      */
158     private List<ProductCategory> getProductCategories(Integer parentId) {//根据父ID查询所有子商品分类
159         Connection connection = null;
160         List<ProductCategory> productCategoryList = null;
161         try {
162             connection = DataSourceUtil.openConnection();
163             ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
164             ProductCategoryParam params = new ProductCategoryParam();
165             if (EmptyUtils.isNotEmpty(parentId)) {
166                 params.setParentId(parentId);
167             } else {
168                 params.setParentId(0);
169             }
170             productCategoryList = productCategoryDao.queryProductCategorylist(params);
171         } catch (Exception e) {
172             e.printStackTrace();
173         } finally {
174             DataSourceUtil.closeConnection(connection);
175             return productCategoryList;
176         }
177     }
178 }
ProductCategoryServiceImpl

 

技术分享
 1 package cn.easybuy.service.product;
 2 
 3 import java.util.List;
 4 import cn.easybuy.entity.Product;
 5 
 6 public interface ProductService {
 7     
 8     public boolean add(Product product);
 9     
10     public boolean update(Product product);
11     
12     public boolean deleteProductById(Integer productId);
13     
14     public Product getProductById(Integer productId);
15     
16     public List<Product> getProductList(Integer currentPageNo,Integer pageSize,
17                                         String proName,Integer categoryId,Integer level);
18     
19     public int count(String proName,Integer categoryId,Integer level);
20     
21     public boolean updateStock(Integer productId,Integer stock);
22     
23 }
ProductService
技术分享
  1 package cn.easybuy.service.product;
  2 import java.sql.Connection;
  3 import java.util.List;
  4 import cn.easybuy.dao.product.ProductDao;
  5 import cn.easybuy.dao.product.ProductDaoImpl;
  6 import cn.easybuy.utils.DataSourceUtil;
  7 import org.apache.log4j.Logger;
  8 import cn.easybuy.entity.Product;
  9 /**
 10  * 商品的业务类
 11  */
 12 public class ProductServiceImpl implements ProductService {
 13     
 14     private Logger logger = Logger.getLogger(ProductServiceImpl.class);
 15     
 16     @Override
 17     public boolean add(Product product) {
 18         Connection connection = null;
 19         Integer count=0;
 20         try {
 21             connection = DataSourceUtil.openConnection();
 22             ProductDao productDao = new ProductDaoImpl(connection);
 23             count=productDao.add(product);
 24         } catch (Exception e) {
 25             e.printStackTrace();
 26         } finally {
 27             DataSourceUtil.closeConnection(connection);
 28             return count>0;
 29         }
 30     }
 31 
 32     @Override
 33     public boolean update(Product product) {
 34         Connection connection = null;
 35         Integer count=0;
 36         try {
 37             connection = DataSourceUtil.openConnection();
 38             ProductDao productDao = new ProductDaoImpl(connection);
 39             count=productDao.update(product);
 40         } catch (Exception e) {
 41             e.printStackTrace();
 42         } finally {
 43             DataSourceUtil.closeConnection(connection);
 44             return count>0;
 45         }
 46     }
 47 
 48     @Override
 49     public boolean deleteProductById(Integer productId) {
 50         Connection connection = null;
 51         Integer count=0;
 52         try {
 53             connection = DataSourceUtil.openConnection();
 54             ProductDao productDao = new ProductDaoImpl(connection);
 55             count=productDao.deleteProductById(productId);
 56         } catch (Exception e) {
 57             e.printStackTrace();
 58         } finally {
 59             DataSourceUtil.closeConnection(connection);
 60             return count>0;
 61         }
 62     }
 63 
 64     @Override
 65     public Product getProductById(Integer productId) {
 66         Connection connection = null;
 67         Product product=null;
 68         try {
 69             connection = DataSourceUtil.openConnection();
 70             ProductDao productDao = new ProductDaoImpl(connection);
 71             product=productDao.getProductById(productId);
 72         } catch (Exception e) {
 73             e.printStackTrace();
 74         } finally {
 75             DataSourceUtil.closeConnection(connection);
 76             return product;
 77         }
 78     }
 79 
 80     @Override
 81     public List<Product> getProductList(Integer currentPageNo,Integer pageSize,String proName, Integer categoryId, Integer level) {
 82         Connection connection = null;
 83         List<Product> productList=null;
 84         try {
 85             connection = DataSourceUtil.openConnection();
 86             ProductDao productDao = new ProductDaoImpl(connection);
 87             productList=productDao.getProductList(currentPageNo,pageSize,proName,categoryId,level);
 88         } catch (Exception e) {
 89             e.printStackTrace();
 90         } finally {
 91             DataSourceUtil.closeConnection(connection);
 92             return productList;
 93         }
 94     }
 95 
 96     @Override
 97     public int count(String proName,Integer categoryId, Integer level) {
 98         Connection connection = null;
 99         Integer count=0;
100         try {
101             connection = DataSourceUtil.openConnection();
102             ProductDao productDao = new ProductDaoImpl(connection);
103             count=productDao.queryProductCount(proName,categoryId,level);
104         } catch (Exception e) {
105             e.printStackTrace();
106         } finally {
107             DataSourceUtil.closeConnection(connection);
108             return count;
109         }
110     }
111 
112     @Override
113     public boolean updateStock(Integer productId, Integer stock) {
114         Connection connection = null;
115         Integer count=0;
116         try {
117             connection = DataSourceUtil.openConnection();
118             ProductDao productDao = new ProductDaoImpl(connection);
119             count=productDao.updateStock(productId,stock);
120         } catch (Exception e) {
121             e.printStackTrace();
122         } finally {
123             DataSourceUtil.closeConnection(connection);
124             return count>0;
125         }
126     }
127    
128 }
ProductServiceImpl

 

以上是service.product类代码


 

技术分享
 1 package cn.easybuy.service.user;
 2 import cn.easybuy.entity.UserAddress;
 3 
 4 import java.util.List;
 5 
 6 public interface UserAddressService {
 7     /**
 8      * 根据loginName 查询用户地址
 9      * @param id
10      * @return
11      * @throws Exception
12      */
13     public List<UserAddress> queryUserAdressList(Integer id) throws Exception;
14     /**
15      * 给用户添加地址
16      * @param id
17      * @param address
18      * @return
19      */
20     public Integer addUserAddress(Integer id, String address, String remark) throws Exception;
21     /**
22      * 根据id查询地址
23      * @param id
24      * @return
25      */
26     public UserAddress getUserAddressById(Integer id);
27 
28 }
UserAddressService
技术分享
 1 package cn.easybuy.service.user;
 2 
 3 import cn.easybuy.dao.order.UserAddressDao;
 4 import cn.easybuy.dao.order.UserAddressDaoImpl;
 5 import cn.easybuy.entity.UserAddress;
 6 import cn.easybuy.param.UserAddressParam;
 7 import cn.easybuy.utils.DataSourceUtil;
 8 import cn.easybuy.utils.Params;
 9 
10 import java.sql.Connection;
11 import java.sql.SQLException;
12 import java.util.List;
13 
14 public class UserAddressServiceImpl implements UserAddressService {
15     /**
16      * 查询用户地址列表
17      *
18      * @param id
19      * @return
20      * @throws Exception
21      */
22     public List<UserAddress> queryUserAdressList(Integer id) throws Exception{
23         Connection connection = null;
24         List<UserAddress> userAddressList = null;
25         try {
26             connection = DataSourceUtil.openConnection();
27             UserAddressDao userAddressDao = new UserAddressDaoImpl(connection);
28             UserAddressParam params = new UserAddressParam();
29             params.setUserId(id);
30             userAddressList = userAddressDao.queryUserAddressList(params);
31         } catch (SQLException e) {
32             e.printStackTrace();
33         } catch (Exception e) {
34             e.printStackTrace();
35         }finally{
36             DataSourceUtil.closeConnection(connection);
37         }
38         return userAddressList;
39     }
40     /**
41      * 添加用户地址
42      *
43      * @param id
44      * @param address
45      * @return
46      */
47     @Override
48     public Integer addUserAddress(Integer id, String address,String remark) {
49         Connection connection = null;
50         Integer userAddressId = null;
51         try {
52             connection = DataSourceUtil.openConnection();
53             UserAddressDao userAddressDao = new UserAddressDaoImpl(connection);
54             UserAddress userAddress=new UserAddress();
55             userAddress.setUserId(id);
56             userAddress.setAddress(address);
57             userAddress.setRemark(remark);
58             userAddressId = userAddressDao.add(userAddress);
59         } catch (SQLException e) {
60             e.printStackTrace();
61         } catch (Exception e) {
62             e.printStackTrace();
63         }finally{
64             DataSourceUtil.closeConnection(connection);
65         }
66         return userAddressId;
67     }
68 
69     @Override
70     public UserAddress getUserAddressById(Integer id) {
71         Connection connection = null;
72         UserAddress userAddress= null;
73         try {
74             connection = DataSourceUtil.openConnection();
75             UserAddressDao userAddressDao = new UserAddressDaoImpl(connection);
76             userAddress = (UserAddress) userAddressDao.getUserAddressById(id);
77         } catch (SQLException e) {
78             e.printStackTrace();
79         } catch (Exception e) {
80             e.printStackTrace();
81         }finally {
82             DataSourceUtil.closeConnection(connection);
83             return  userAddress;
84         }
85     }
86 }
UserAddressServiceImpl

 

技术分享
 1 package cn.easybuy.service.user;
 2 import cn.easybuy.entity.User;
 3 import java.util.List;
 4 
 5 public interface UserService {
 6 
 7     public boolean add(User user);
 8     
 9     public boolean update(User user);
10     
11     public boolean deleteUserById(Integer userId);
12     
13     public User getUser(Integer userId,String loginName);
14     
15     public List<User> getUserList(Integer currentPageNo,Integer pageSize);
16     
17     public int count();
18 }
UserService
技术分享
  1 package cn.easybuy.service.user;
  2 import java.sql.Connection;
  3 import java.sql.SQLException;
  4 import java.util.ArrayList;
  5 import java.util.List;
  6 import cn.easybuy.dao.order.UserAddressDao;
  7 import cn.easybuy.dao.order.UserAddressDaoImpl;
  8 import cn.easybuy.dao.user.UserDao;
  9 import cn.easybuy.dao.user.UserDaoImpl;
 10 import cn.easybuy.entity.UserAddress;
 11 import cn.easybuy.utils.DataSourceUtil;
 12 import org.apache.log4j.Logger;
 13 import cn.easybuy.entity.User;
 14 
 15 public class UserServiceImpl implements UserService {
 16     
 17     private Logger logger = Logger.getLogger(UserServiceImpl.class);
 18     
 19     @Override
 20     public boolean add(User user){
 21         Connection connection = null;
 22         Integer count=0;
 23         try {
 24             connection = DataSourceUtil.openConnection();
 25             UserDao userDao = new UserDaoImpl(connection);
 26             count=userDao.add(user);
 27         } catch (SQLException e) {
 28             e.printStackTrace();
 29         } catch (Exception e) {
 30             e.printStackTrace();
 31         }finally {
 32             DataSourceUtil.closeConnection(connection);
 33             return  count>0;
 34         }
 35     }
 36 
 37     @Override
 38     public boolean update(User user) {
 39         Connection connection = null;
 40         Integer count=0;
 41         try {
 42             connection = DataSourceUtil.openConnection();
 43             UserDao userDao = new UserDaoImpl(connection);
 44             count=userDao.update(user);
 45         } catch (SQLException e) {
 46             e.printStackTrace();
 47         } catch (Exception e) {
 48             e.printStackTrace();
 49         }finally {
 50             DataSourceUtil.closeConnection(connection);
 51             return  count>0;
 52         }
 53     }
 54 
 55     @Override
 56     public boolean deleteUserById(Integer userId) {
 57         Connection connection = null;
 58         Integer count=0;
 59         try {
 60             connection = DataSourceUtil.openConnection();
 61             UserDao userDao = new UserDaoImpl(connection);
 62             count=userDao.deleteUserById(userId+"");
 63         } catch (SQLException e) {
 64             e.printStackTrace();
 65         } catch (Exception e) {
 66             e.printStackTrace();
 67         }finally {
 68             DataSourceUtil.closeConnection(connection);
 69             return  count>0;
 70         }
 71     }
 72 
 73     @Override
 74     public User getUser(Integer userId, String loginName) {
 75         Connection connection = null;
 76         User user=null;
 77         try {
 78             connection = DataSourceUtil.openConnection();
 79             UserDao userDao = new UserDaoImpl(connection);
 80             user=userDao.getUser(userId,loginName);
 81         } catch (SQLException e) {
 82             e.printStackTrace();
 83         } catch (Exception e) {
 84             e.printStackTrace();
 85         }finally {
 86             DataSourceUtil.closeConnection(connection);
 87             return user;
 88         }
 89     }
 90 
 91     @Override
 92     public List<User> getUserList(Integer currentPageNo, Integer pageSize) {
 93         Connection connection = null;
 94         List<User> userList=null;
 95         try {
 96             connection = DataSourceUtil.openConnection();
 97             UserDao userDao = new UserDaoImpl(connection);
 98             userList=userDao.getUserList(currentPageNo,pageSize);
 99         } catch (SQLException e) {
100             e.printStackTrace();
101         } catch (Exception e) {
102             e.printStackTrace();
103         }finally {
104             DataSourceUtil.closeConnection(connection);
105             return userList;
106         }
107     }
108 
109     @Override
110     public int count() {
111         Connection connection = null;
112         Integer count=null;
113         try {
114             connection = DataSourceUtil.openConnection();
115             UserDao userDao = new UserDaoImpl(connection);
116             count=userDao.count();
117         } catch (SQLException e) {
118             e.printStackTrace();
119         } catch (Exception e) {
120             e.printStackTrace();
121         }finally {
122             DataSourceUtil.closeConnection(connection);
123             return count;
124         }
125     }
126 }
UserServiceImpl

 

以上是service.user类代码


技术分享
 1 package cn.easybuy.utils;
 2 
 3 public class Constants {
 4     /**
 5      * json 格式返回数据的 status 标示说明
 6      */
 7     public static interface ReturnResult{
 8         public static int SUCCESS=1;
 9         public static int FAIL=-1;
10     }
11     /**
12      * 前后台用户
13      */
14     public static interface  UserType{
15         public static int PRE=0;
16         public static int BACKEND=1;
17     }
18 }
Constants
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.sql.Connection;
 6 import java.sql.DriverManager;
 7 import java.sql.SQLException;
 8 
 9 import javax.naming.Context;
10 import javax.naming.InitialContext;
11 import javax.naming.NamingException;
12 import javax.sql.DataSource;
13 import java.util.Properties;
14 
15 public class DataSourceUtil {
16     private static DataSource dataSource;
17     
18     private static String driver;
19     private static String url;
20     private static String user;
21     private static String password;
22     
23     static {
24         init();
25     }
26     
27     public static void init(){
28         Properties params=new Properties();
29         String configFile = "database.properties";
30         InputStream is=DataSourceUtil.class.getClassLoader().getResourceAsStream(configFile);
31         try {
32             params.load(is);
33         } catch (IOException e) {
34             e.printStackTrace();
35         }
36         driver=params.getProperty("driver");
37         url=params.getProperty("url");
38         user=params.getProperty("username");
39         password=params.getProperty("password");
40     }   
41 
42     //获取连接
43     public static Connection openConnection() throws SQLException {
44         Connection connection = null;
45         try {
46             Class.forName(driver);
47             connection = DriverManager.getConnection(url, user, password);
48         } catch (Exception e) {
49             // TODO Auto-generated catch block
50             e.printStackTrace();
51         }
52         
53         return connection;
54     }
55     //关闭连接
56     public static void closeConnection(Connection connection) {
57         try {
58             if (connection != null)
59                 connection.close();
60         } catch (SQLException e) {
61             e.printStackTrace();
62         }
63     }
64 }
DataSourceUtil
技术分享
 1 package cn.easybuy.utils;
 2 import java.util.Collection;
 3 import java.util.Map;
 4 
 5 /**
 6  * <p>判断是否是空的 工具类</p>
 7  * @author zzshang
 8  * @version v1.0
 9  * @since 
10  */
11 public class EmptyUtils {
12     //判空
13     public static boolean isEmpty(Object obj){
14         if (obj == null)
15             return true;
16         if (obj instanceof CharSequence)
17             return ((CharSequence) obj).length() == 0;
18         if (obj instanceof Collection)
19             return ((Collection) obj).isEmpty();
20         if (obj instanceof Map)
21             return ((Map) obj).isEmpty();
22         if (obj instanceof Object[]) {
23             Object[] object = (Object[]) obj;
24             if (object.length == 0) {
25                 return true;
26             }
27             boolean empty = true;
28             for (int i = 0; i < object.length; i++) {
29                 if (!isEmpty(object[i])) {
30                     empty = false;
31                     break;
32                 }
33             }
34             return empty;
35         }
36         return false;
37     }
38     public static boolean isNotEmpty(Object obj){
39         return !isEmpty(obj);
40     }
41 
42 
43 
44     private boolean validPropertyEmpty(Object ...args) {
45         for (int i = 0; i < args.length; i++) {
46             if(EmptyUtils.isEmpty(args[i])){
47                 return true;
48             }
49         }
50         return false;
51     }
52 }
EmptyUtils
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import com.danga.MemCached.MemCachedClient;
 4 import com.danga.MemCached.SockIOPool;
 5 
 6 import java.util.ArrayList;
 7 import java.util.List;
 8 
 9 
10 public class MemcachedUtils {
11 
12     static MemCachedClient client = null;
13 
14     static String[] connectUrls = new String[]{"127.0.0.1:11211"};
15 
16     static {
17         String[] attr = connectUrls;
18         client = new MemCachedClient();
19         SockIOPool pool = SockIOPool.getInstance();
20         pool.setServers(attr);
21         pool.setWeights(new Integer[]{3});
22         pool.setInitConn(5);
23         pool.setMinConn(5);
24         pool.setMaxConn(200);
25         pool.setMaxIdle(1000 * 30 * 30);
26         pool.setMaintSleep(30);
27         pool.setNagle(false);
28         pool.setSocketConnectTO(30);
29         pool.initialize();
30     }
31 
32     public static void add(String key, Object object) {
33         client.set(key, object);
34     }
35 
36     public static void del(String key) {
37         client.delete(key);
38     }
39 
40     public static Object get(String key) {
41         return client.get(key);
42     }
43 
44     public static void main(String args[]) {
45         List<String> name = new ArrayList<String>();
46         name.add("1111");
47         name.add("2222");
48         name.add("3333");
49         name.add("4444");
50         name.add("5555");
51         name.add("6666");
52         add("name", name);
53         List<String> test = (List<String>) get("name");
54         System.out.print(test);
55     }
56 }
MemcachedUtils

 

技术分享
 1 package cn.easybuy.utils;
 2 
 3 import cn.easybuy.entity.Order;
 4 import cn.easybuy.entity.OrderDetail;
 5 
 6 import java.io.Serializable;
 7 import java.util.List;
 8 
 9 
10 public class OrderVo implements Serializable {
11     private Order order;
12     private List<OrderDetail> orderDetailList;
13 
14     public Order getOrder() {
15         return order;
16     }
17 
18     public void setOrder(Order order) {
19         this.order = order;
20     }
21 
22     public List<OrderDetail> getOrderDetailList() {
23         return orderDetailList;
24     }
25 
26     public void setOrderDetailList(List<OrderDetail> orderDetailList) {
27         this.orderDetailList = orderDetailList;
28     }
29 }
OrderVo
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import java.io.Serializable;
 4 import java.util.ArrayList;
 5 import java.util.List;
 6 
 7 public class Pager implements Serializable{
 8     private int currentPage;//当前页
 9     private int rowCount;//总条数
10     private int rowPerPage;//每页显示条数
11     private int pageCount;//总页数
12     private String url;
13 
14     public String getUrl() {
15         return url;
16     }
17 
18     public void setUrl(String url) {
19         this.url = url;
20     }
21 
22 
23     public void setRowCount(int rowCount) {
24         this.rowCount = rowCount;
25     }
26 
27     public void setRowPerPage(int rowPerPage) {
28         this.rowPerPage = rowPerPage;
29     }
30 
31     public void setCurrentPage(int currentPage) {
32         this.currentPage = currentPage;
33     }
34 
35     public void setPageCount(int pageCount) {
36         this.pageCount = pageCount;
37     }
38 
39 
40     public Pager(int rowCount, int rowPerPage, int currentPage) {
41 
42         this.rowCount = rowCount;
43         this.rowPerPage = rowPerPage;
44         this.currentPage = currentPage;
45         if(this.rowCount % this.rowPerPage == 0){
46             this.pageCount = this.rowCount / this.rowPerPage;
47         }else if(this.rowCount % this.rowPerPage > 0){
48             this.pageCount = this.rowCount / this.rowPerPage + 1;
49         }else{
50             this.pageCount = 0;
51         }
52     }
53 
54     public int getRowCount() {
55         return rowCount;
56     }
57 
58     public int getRowPerPage() {
59         return rowPerPage;
60     }
61 
62     public int getCurrentPage() {
63         return currentPage;
64     }
65 
66     public int getPageCount() {
67         return pageCount;
68     }
69 }
Pager
技术分享
  1 package cn.easybuy.utils;
  2 
  3 import java.io.Serializable;
  4 import java.util.HashMap;
  5 import java.util.Map;
  6 
  7 /**
  8  * 自己定义的查询工具类
  9  */
 10 public class Params implements Serializable{
 11 
 12     private String tableName;
 13 
 14     //选择参数
 15     private Map<String,Object> selectParams;
 16     //模糊查询参数
 17     private Map<String,Object> likeParams;
 18     //更新参数
 19     private Map<String,Object> updateParams;
 20     //排序参数
 21     private Map<String,Object> sortParams;
 22     //新增参数
 23     private Map<String,Object> addParams;
 24 
 25     //查询起始位置
 26     private int startIndex;
 27 
 28     //查询数目
 29     private int pageSize;
 30 
 31     private boolean isOpenPager=false;
 32 
 33     public Params() {
 34         selectParams=new HashMap<String, Object>();
 35         sortParams=new HashMap<String, Object>();
 36         updateParams=new HashMap<String, Object>();
 37         addParams=new HashMap<String, Object>();
 38         likeParams=new HashMap<String, Object>();
 39     }
 40     public Params(String tableName) {
 41         this.tableName=tableName;
 42         selectParams=new HashMap<String, Object>();
 43         sortParams=new HashMap<String, Object>();
 44         updateParams=new HashMap<String, Object>();
 45         addParams=new HashMap<String, Object>();
 46         likeParams=new HashMap<String, Object>();
 47     }
 48 
 49     //增加查询参数
 50     public Params addEqual(String column, Object value){
 51         selectParams.put(column,value);
 52         return this;
 53     }
 54     public Params addLike(String column, Object value){
 55         likeParams.put(column,value);
 56         return this;
 57     }
 58     //增加设置参数
 59     public Params addSet(String column,Object value){
 60         updateParams.put(column,value);
 61         return this;
 62     }
 63     //设置排序
 64     public Params orderDesc(String cloumn){
 65         sortParams.put(cloumn,"desc");
 66         return this;
 67     }
 68     public Params orderAsc(String cloumn){
 69         sortParams.put(cloumn,"asc");
 70         return this;
 71     }
 72     //设置分页
 73     public Params openPager(int startIndex,int pageSize){
 74         this.isOpenPager=true;
 75         this.startIndex=startIndex;
 76         this.pageSize=pageSize;
 77         return this;
 78     }
 79     public Params addSaveParam(String column,Object value){
 80         addParams.put(column,value);
 81         return this;
 82     }
 83 
 84     public Map<String, Object> getLikeParams() {
 85         return likeParams;
 86     }
 87 
 88     public void setLikeParams(Map<String, Object> likeParams) {
 89         this.likeParams = likeParams;
 90     }
 91 
 92     public boolean isOpenPager() {
 93         return isOpenPager;
 94     }
 95 
 96     public void setOpenPager(boolean isOpenPager) {
 97         this.isOpenPager = isOpenPager;
 98     }
 99 
100     public String getTableName() {
101         return tableName;
102     }
103 
104     public void setTableName(String tableName) {
105         this.tableName = tableName;
106     }
107 
108     public Map<String, Object> getSelectParams() {
109         return selectParams;
110     }
111 
112     public void setSelectParams(Map<String, Object> selectParams) {
113         this.selectParams = selectParams;
114     }
115 
116     public Map<String, Object> getUpdateParams() {
117         return updateParams;
118     }
119 
120     public void setUpdateParams(Map<String, Object> updateParams) {
121         this.updateParams = updateParams;
122     }
123 
124     public Map<String, Object> getSortParams() {
125         return sortParams;
126     }
127 
128     public void setSortParams(Map<String, Object> sortParams) {
129         this.sortParams = sortParams;
130     }
131 
132     public Map<String, Object> getAddParams() {
133         return addParams;
134     }
135 
136     public void setAddParams(Map<String, Object> addParams) {
137         this.addParams = addParams;
138     }
139 
140     public int getStartIndex() {
141         return startIndex;
142     }
143 
144     public void setStartIndex(int startIndex) {
145         this.startIndex = startIndex;
146     }
147 
148     public int getPageSize() {
149         return pageSize;
150     }
151 
152     public void setPageSize(int pageSize) {
153         this.pageSize = pageSize;
154     }
155 }
Params
技术分享
 1 package cn.easybuy.utils;
 2 import com.alibaba.fastjson.JSONObject;
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 public class PrintUtil {
 8 
 9     private static void print(String msg,HttpServletResponse response){
10         PrintWriter writer=null;
11         try {
12             if(null != response){
13                 writer=response.getWriter();
14                 writer.print(msg);
15                 writer.flush();
16             }
17         } catch (IOException e) {
18             e.printStackTrace();
19         }finally {
20             writer.close();
21         }
22     }
23     public static void write(Object obj,HttpServletResponse response){
24         response.setContentType("text/html; charset=utf-8");
25         String json = JSONObject.toJSONString(obj);
26         print(json,response);
27     }
28 }
PrintUtil
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import cn.easybuy.entity.Product;
 4 import cn.easybuy.entity.ProductCategory;
 5 
 6 import java.io.Serializable;
 7 import java.util.List;
 8 
 9 
10 public class ProductCategoryVo implements Serializable {
11 
12     private ProductCategory productCategory;
13     private List<ProductCategoryVo> productCategoryVoList;
14     private List<Product> productList;
15 
16     public ProductCategory getProductCategory() {
17         return productCategory;
18     }
19 
20     public void setProductCategory(ProductCategory productCategory) {
21         this.productCategory = productCategory;
22     }
23 
24     public List<ProductCategoryVo> getProductCategoryVoList() {
25         return productCategoryVoList;
26     }
27 
28     public void setProductCategoryVoList(List<ProductCategoryVo> productCategoryVoList) {
29         this.productCategoryVoList = productCategoryVoList;
30     }
31 
32     public List<Product> getProductList() {
33         return productList;
34     }
35 
36     public void setProductList(List<Product> productList) {
37         this.productList = productList;
38     }
39 }
ProductCategoryVo
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import java.util.regex.Matcher;
 4 import java.util.regex.Pattern;
 5 
 6 /**
 7  * 正则表达式验证 工具类
 8  * @author bdqn
 9  *
10  */
11 public class RegUtils {
12 
13     static String emailReg="^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$";
14     static String mobileReg="^\\d{5,11}$";
15     static String identityCodeReg="^\\w{18}$";
16     
17     public static boolean checkEmail(String email){
18         Pattern pattern=Pattern.compile(emailReg);
19         Matcher matcher=pattern.matcher(email);
20         System.out.println(matcher.matches());
21         return matcher.matches();
22     }
23     
24     public static boolean checkMobile(String mobile){
25         Pattern pattern=Pattern.compile(mobileReg);
26         Matcher matcher=pattern.matcher(mobile);
27         System.out.println(matcher.matches());
28         return matcher.matches();
29     }
30     
31     public static boolean checkIdentityCodeReg(String identityCode){
32         Pattern pattern=Pattern.compile(identityCodeReg);
33         Matcher matcher=pattern.matcher(identityCode);
34         System.out.println(matcher.matches());
35         return matcher.matches();
36     }
37     
38 }
RegUtils
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import java.io.Serializable;
 4 
 5 
 6 public class ReturnResult implements Serializable{
 7 
 8     private int status;
 9     private Object data;
10     private String message="操作成功";
11 
12     public int getStatus() {
13         return status;
14     }
15 
16     public void setStatus(int status) {
17         this.status = status;
18     }
19 
20     public Object getData() {
21         return data;
22     }
23 
24     public void setData(Object data) {
25         this.data =http://www.mamicode.com/ data;
26     }
27 
28     public String getMessage() {
29         return message;
30     }
31 
32     public void setMessage(String message) {
33         this.message = message;
34     }
35     /**
36      * 返回成功状态
37      * @param obj
38      */
39     public ReturnResult returnSuccess(Object obj){
40         this.status=Constants.ReturnResult.SUCCESS;
41         this.data=http://www.mamicode.com/obj;
42         return this;
43     }
44     /**
45      * 返回默认成功状态
46      */
47     public ReturnResult returnSuccess(){
48         this.status=Constants.ReturnResult.SUCCESS;
49         return this;
50     }
51     /**
52      * 返回失败状态
53      * @param message
54      */
55     public ReturnResult returnFail(String message){
56         this.status=Constants.ReturnResult.FAIL;
57         this.message=message;
58         return this;
59     }
60 
61     public ReturnResult(String message, int status, Object data) {
62         this.message = message;
63         this.status = status;
64         this.data =http://www.mamicode.com/ data;
65     }
66 
67     public ReturnResult(Object data) {
68         this.status=Constants.ReturnResult.SUCCESS;
69         this.data =http://www.mamicode.com/ data;
70     }
71 
72     public ReturnResult(){
73 
74     }
75 }
ReturnResult
技术分享
 1 package cn.easybuy.utils;
 2 
 3 
 4 import org.apache.commons.codec.digest.DigestUtils;
 5 
 6 public class SecurityUtils {
 7 
 8     /**
 9      * md5加密
10      *
11      * @param value 要加密的值
12      * @return md5加密后的值
13      */
14     public static String md5Hex(String value) {
15         return DigestUtils.md5Hex(value);
16     }
17 
18     /**
19      * 3次md5操作
20      * @param value
21      * @return
22      */
23     public static String md5Hex3(String value) {
24         for (int i = 0; i < 3; i++) {
25             value =http://www.mamicode.com/ DigestUtils.md5Hex(value);
26         }
27         return value;
28     }
29     
30     
31     /**
32      * sha256加密
33      *
34      * @param value 要加密的值
35      * @return sha256加密后的值
36      */
37     public static String sha256Hex(String value) {
38         return DigestUtils.sha256Hex(value);
39     }
40 
41     public static String sha512Hex(String value) {
42         return DigestUtils.sha512Hex(value);
43     }
44     
45     public static void main(String[] args) {
46         System.out.println(SecurityUtils.md5Hex("123456"));
47     }
48 }
SecurityUtils
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import cn.easybuy.entity.Order;
 4 import cn.easybuy.entity.Product;
 5 
 6 import java.io.Serializable;
 7 import java.util.ArrayList;
 8 import java.util.List;
 9 
10 public class ShoppingCart implements Serializable{
11     public List<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>();
12     private Double sum;
13 
14     //获取购物车中所有商品
15     public List<ShoppingCartItem> getItems() {
16         return items;
17     }    
18     //添加一项
19     public ReturnResult addItem(Product product, Integer quantity) {
20         ReturnResult result=new ReturnResult();
21         int flag=0;
22         for(int i=0;i<items.size();i++){
23             //判断购物车中是否已有此商品,如果有则累计数量
24             if((items.get(i).getProduct().getId()).equals(product.getId())){
25                 if(items.get(i).getQuantity()+quantity>product.getStock()){
26                     return result.returnFail("商品数量不足");
27                 }else{
28                     items.get(i).setQuantity(items.get(i).getQuantity()+quantity);
29                     flag=1;
30                 }
31             }
32         }
33         if(quantity>product.getStock()){
34             return result.returnFail("商品数量不足");
35         }
36         if(flag==0){
37             items.add(new ShoppingCartItem(product, quantity));
38         }
39         return result.returnSuccess();
40     }
41 
42     //移除一项
43     public void removeItem(int index) {
44         items.remove(index);
45     }
46 
47     //修改数量
48     public void modifyQuantity(int index, Integer quantity) {
49         items.get(index).setQuantity(quantity);
50     }
51 
52     //计算总价格
53     public float getTotalCost() {
54         float sum = 0;
55         for (ShoppingCartItem item : items) {
56             sum = sum + item.getCost();
57         }
58         return sum;
59     }
60 
61     public void setItems(List<ShoppingCartItem> items) {
62         this.items = items;
63     }
64 
65     public Double getSum() {
66         return sum;
67     }
68 
69     public void setSum(Double sum) {
70         this.sum = sum;
71     }
72 }
ShoppingCart
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import cn.easybuy.entity.Product;
 4 
 5 import java.io.Serializable;
 6 
 7 public class ShoppingCartItem implements Serializable{
 8     private Product product;//商品
 9     private Integer quantity;//数量
10     private float cost;//价格
11 
12     public ShoppingCartItem(Product product, Integer quantity) {
13         this.product = product;
14         this.quantity = quantity;
15         this.cost = product.getPrice() * quantity;
16     }
17 
18     public Integer getQuantity() {
19         return quantity;
20     }
21 
22     public void setQuantity(Integer quantity) {
23         this.quantity = quantity;
24         this.cost = product.getPrice() * quantity;
25     }
26 
27     public Product getProduct() {
28         return product;
29     }
30 
31     public float getCost() {
32         return cost;
33     }
34 
35     public void setProduct(Product product) {
36         this.product = product;
37     }
38 
39     public void setCost(float cost) {
40         this.cost = cost;
41     }
42 }
ShoppingCartItem
技术分享
  1 package cn.easybuy.utils;
  2 
  3 import java.security.InvalidKeyException;
  4 import java.security.NoSuchAlgorithmException;
  5 import java.text.SimpleDateFormat;
  6 import java.util.Calendar;
  7 import java.util.Date;
  8 import java.util.Map;
  9 import java.util.Random;
 10 import java.util.UUID;
 11 
 12 import javax.crypto.BadPaddingException;
 13 import javax.crypto.Cipher;
 14 import javax.crypto.IllegalBlockSizeException;
 15 import javax.crypto.NoSuchPaddingException;
 16 import javax.crypto.SecretKey;
 17 import javax.crypto.spec.SecretKeySpec;
 18 
 19 
 20 
 21 public class StringUtils {
 22     private static String[] binaryArray =   
 23         {"0000","0001","0010","0011",  
 24         "0100","0101","0110","0111",  
 25         "1000","1001","1010","1011",  
 26         "1100","1101","1110","1111"};  
 27 //    private static String[] chineseDigits = new String[] { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
 28     public static String[] chineseDigits = new String[] { "零", "一", "二", "三", "四", "五", "六", "七", "八", "九"};
 29     
 30     private static final char[] charBytes = { ‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘,‘a‘, ‘b‘, ‘c‘, ‘d‘, ‘e‘, ‘f‘, ‘g‘, ‘h‘,
 31         ‘i‘,‘j‘,‘k‘,‘l‘,‘m‘,‘n‘,‘o‘,‘p‘,‘q‘,‘r‘,‘s‘,‘t‘,‘u‘,‘v‘,‘w‘,‘x‘,‘y‘,‘z‘};
 32     
 33     private static final char[] numberBytes = {‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘};
 34     
 35     /**
 36      * 生成指定位数的随机数子.
 37      * @param number
 38      * @return
 39      */
 40     public static String randomNumbers(int number) {
 41         int count = 0; //生成的密码的长度
 42         int i; //生成的随机数
 43         final int maxNum = numberBytes.length;
 44         StringBuffer randomStr = new StringBuffer("");
 45         Random r = new Random();
 46         while(count < number){
 47              //生成随机数,取绝对值,防止生成负数,
 48              i = Math.abs(r.nextInt(maxNum)); //生成的数最大为36-1
 49              if (i >= 0 && i < numberBytes.length) {
 50                  randomStr.append(numberBytes[i]);
 51               count ++;
 52              }
 53         }
 54         return randomStr.toString();
 55     }
 56     
 57     
 58     
 59     public static String randomStrByNumber(int number) {
 60         int count = 0; //生成的密码的长度
 61         int i; //生成的随机数
 62         final int maxNum = charBytes.length;
 63         StringBuffer randomStr = new StringBuffer("");
 64         Random r = new Random();
 65         while(count < number){
 66              //生成随机数,取绝对值,防止生成负数,
 67              i = Math.abs(r.nextInt(maxNum)); //生成的数最大为36-1
 68              if (i >= 0 && i < charBytes.length) {
 69                  randomStr.append(charBytes[i]);
 70               count ++;
 71              }
 72         }
 73         return randomStr.toString();
 74     }
 75     
 76     
 77     public static String randomUUID() {
 78         UUID uuid = UUID.randomUUID();
 79         return uuid.toString().replace("-", "").toUpperCase();
 80     }
 81     public static String digitsTochinese(int i){
 82         //大于10的需要重写
 83         return chineseDigits[i];
 84     }
 85     public static String toAllUpperCase(String uuid) {
 86         StringBuffer buffer = new StringBuffer();
 87 
 88         for (int i = 0; i < uuid.length(); i++) {
 89             char c = uuid.charAt(i);
 90             if (Character.isLowerCase(c)) {
 91                 buffer.append(Character.toUpperCase(c));
 92             } else {
 93                 buffer.append(c);
 94             }
 95         }
 96         return buffer.toString();
 97     }
 98     
 99 
100     
101     // 十六进制字符串转byte数组
102         public static byte[] hexStringToBytes(String hexString) {
103             if (hexString == null || hexString.equals("")) {
104                 return null;
105             }
106             hexString = hexString.toUpperCase();
107             int length = hexString.length() / 2;
108             char[] hexChars = hexString.toCharArray();
109             byte[] d = new byte[length];
110             for (int i = 0; i < length; i++) {
111                 int pos = i * 2;
112                 d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
113             }
114             return d;
115         }
116 
117         private static byte charToByte(char c) {
118             return (byte) "0123456789ABCDEF".indexOf(c);
119         }
120 
121         // 数组转字符串、以空格间隔
122         public static String bytesToHexString(byte[] src) {
123             StringBuilder stringBuilder = new StringBuilder("");
124             if (src =http://www.mamicode.com/= null || src.length <= 0) {
125                 return null;
126             }
127             for (int i = 0; i < src.length; i++) {
128                 int v = src[i] & 0xFF;
129                 String hv = Integer.toHexString(v);
130                 if (hv.length() < 2) {
131                     stringBuilder.append(0);
132                 }
133                 if (i == src.length - 1) {
134                     stringBuilder.append(hv);
135                 } else {
136                     stringBuilder.append(hv);
137                 }
138             }
139             return stringBuilder.toString();
140         }
141         
142         
143         public static String bytesToHexStringNoAppendBit(byte[] src) {
144             StringBuilder stringBuilder = new StringBuilder("");
145             if (src =http://www.mamicode.com/= null || src.length <= 0) {
146                 return null;
147             }
148             for (int i = 0; i < src.length; i++) {
149                 int v = src[i] & 0xFF;
150                 String hv = Integer.toHexString(v);
151                 /*if (hv.length() < 2) {
152                     stringBuilder.append(0);
153                 }*/
154                 if (i == src.length - 1) {
155                     stringBuilder.append(hv);
156                 } else {
157                     stringBuilder.append(hv);
158                 }
159             }
160             return stringBuilder.toString();
161         }
162         
163         
164         public static String bytesToString(byte[] src, String split) {
165             StringBuilder stringBuilder = new StringBuilder("");
166             if (src =http://www.mamicode.com/= null || src.length <= 0) {
167                 return null;
168             }
169             for (int i = 0; i < src.length; i++) {
170                 int v = src[i] & 0xFF;
171                 String hv = String.valueOf(v);
172                 if (i == src.length - 1) {
173                     stringBuilder.append(hv);
174                 } else {
175                     stringBuilder.append(hv + split);
176                 }
177             }
178             return stringBuilder.toString();
179         }
180         
181 
182         public static String generateHexString(int paramInt) {
183             StringBuffer localStringBuffer = new StringBuffer();
184             Random localRandom = new Random();
185             int i = 16;
186             for (int j = 0; j < paramInt; j++) {
187                 if (j % 2 == 0) {
188                     localStringBuffer.append("0123456789ABCDEF".charAt(localRandom
189                             .nextInt(i)));
190                 } else {
191                     localStringBuffer.append("0123456789ABCDEF".charAt(localRandom
192                             .nextInt(i)) + " ");
193                 }
194             }
195             return localStringBuffer.toString();
196         }
197 
198         public static byte[] decodeTripleDES(byte[] data, byte[] key)
199                 throws NoSuchAlgorithmException, NoSuchPaddingException,
200                 InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
201             byte[] keys;
202             if (key.length == 16) {
203                 keys = new byte[24];
204                 System.arraycopy(key, 0, keys, 0, 16);
205                 System.arraycopy(key, 0, keys, 16, 8);
206             } else {
207                 keys = key;
208             }
209 
210             Cipher cipher = Cipher.getInstance("DESede/ECB/NoPadding");
211             SecretKey secretKey = new SecretKeySpec(keys, "DESede");
212             cipher.init(Cipher.DECRYPT_MODE, secretKey);
213             return cipher.doFinal(data);
214         }
215 
216         public static boolean equals(byte[] b1, byte[] b2) {
217             if (b1.length != b2.length) {
218                 return false;
219             }
220             for (int i = 0; i < b1.length; i++) {
221                 if (b1[i] != b2[i]) {
222                     return false;
223                 }
224             }
225             return true;
226         }
227     /** 
228      *  
229      * @return 转换为二进制字符串
230      */  
231     public static String bytes2BinaryStr(byte[] bArray){  
232         String outStr = "";  
233         int pos = 0;  
234         for(byte b:bArray){  
235             //高四位  
236             pos = (b&0xF0)>>4;  
237             outStr+=binaryArray[pos];  
238             //低四位  
239             pos=b&0x0F;  
240             outStr+=binaryArray[pos];  
241         }  
242         return outStr;  
243     }
244     /**将二进制转换成16进制
245     * @param buf
246     * @return
247     */
248     public static String binaryToHexString(byte[] bytes) {
249            StringBuffer sb = new StringBuffer();
250            for (int i = 0; i < bytes.length; i++) {
251                String hex = Integer.toHexString(bytes[i] & 0xFF);
252              if (hex.length() == 1) {
253                  hex = ‘0‘ + hex;
254              }
255              sb.append(hex.toUpperCase());
256            }
257            return sb.toString();
258     }
259     /**将16进制转换为二进制
260     * @param hexStr
261     * @return
262     */
263     public static byte[] hexStringToBinary(String hexStr) {
264         if (hexStr.length() < 1)
265             return null;
266         byte[] result = new byte[hexStr.length()/2];
267         for (int i = 0;i< hexStr.length()/2; i++) {
268             int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
269             int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
270             result[i] = (byte) (high * 16 + low);
271         }
272         return result;
273     }
274     
275     //十六进制转为字符
276     public static String hexStringToString(String s) {
277         byte[] baKeyword = new byte[s.length() / 2];
278         for (int i = 0; i < baKeyword.length; i++) {
279             try {
280                 baKeyword[i] = (byte) (0xff & Integer.parseInt(
281                         s.substring(i * 2, i * 2 + 2), 16));
282             } catch (Exception e) {
283                 e.printStackTrace();
284             }
285         }
286         try {
287             s = new String(baKeyword, "utf-8");// UTF-16le:Not
288         } catch (Exception e1) {
289             e1.printStackTrace();
290         }
291         return s;
292     }
293 
294     /**
295      * 给某个日期加几天后的日期 eg:2013-06-28号+1天是 2013-06-29 ,+3天是2013-07-01
296      * @param date 日期
297      * @param dump 数字
298      * @return
299      */
300     public static String getDateByAddSomeDay(Date date,int dump){
301         Calendar ca=Calendar.getInstance();
302         SimpleDateFormat sm = new SimpleDateFormat("yyyy-MM-dd");  //构造任意格式
303         String today = sm.format(date);
304         String[] timeArray= today.split("-");
305         ca.set(Calendar.YEAR,Integer.parseInt(timeArray[0]));
306         ca.set(Calendar.MONTH, Integer.parseInt(timeArray[1])-1);
307         ca.set(Calendar.DAY_OF_MONTH,Integer.parseInt(timeArray[2]));
308         ca.add(Calendar.DAY_OF_MONTH, dump);
309         String someDay = sm.format(ca.getTime());
310         return someDay;
311     }
312     
313     /**
314      * 生成公钥
315      * @param pubkey
316      * @return
317      * add by yaoyuan
318      */
319     public static String generatePublicKey(String pubkey) {
320 //        BASE64Encoder base64en = new BASE64Encoder();
321 //        String encode = base64en.encode(hexStringToBinary(pubkey));
322 //        encode = "-----BEGIN RSA PUBLIC KEY-----" + encode + "-----END RSA PUBLIC KEY-----";
323 //        if (encode.getBytes().length < 256) {
324 //            encode = org.apache.commons.lang.StringUtils.rightPad(encode, 256, "0");
325 //        }
326 //        return encode;
327         return null;
328     }
329     
330     /**
331      * 获取当前时间 精确到毫秒
332      */
333     public static String getCurrentTime(){
334          SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
335          String currentTime = sdf.format(new Date());
336          return currentTime;
337     }
338     /** 
339      * @功能: BCD码转为10进制串(阿拉伯数据) 
340      * @参数: BCD码 
341      * @结果: 10进制串 
342      */  
343     public static String bcd2Str(byte[] bytes) {  
344         StringBuffer temp = new StringBuffer(bytes.length * 2);  
345         for (int i = 0; i < bytes.length; i++) {  
346             temp.append((byte) ((bytes[i] & 0xf0) >>> 4));  
347             temp.append((byte) (bytes[i] & 0x0f));  
348         }  
349         return temp.toString().substring(0, 1).equalsIgnoreCase("0") ? temp  
350                 .toString().substring(1) : temp.toString();  
351     }  
352   
353     /** 
354      * @功能: 10进制串转为BCD码 
355      * @参数: 10进制串 
356      * @结果: BCD码 
357      */  
358     public static byte[] str2Bcd(String asc) {  
359         int len = asc.length();  
360         int mod = len % 2;  
361         if (mod != 0) {  
362             asc = "0" + asc;  
363             len = asc.length();  
364         }  
365         byte abt[] = new byte[len];  
366         if (len >= 2) {  
367             len = len / 2;  
368         }  
369         byte bbt[] = new byte[len];  
370         abt = asc.getBytes();  
371         int j, k;  
372         for (int p = 0; p < asc.length() / 2; p++) {  
373             if ((abt[2 * p] >= ‘0‘) && (abt[2 * p] <= ‘9‘)) {  
374                 j = abt[2 * p] - ‘0‘;  
375             } else if ((abt[2 * p] >= ‘a‘) && (abt[2 * p] <= ‘z‘)) {  
376                 j = abt[2 * p] - ‘a‘ + 0x0a;  
377             } else {  
378                 j = abt[2 * p] - ‘A‘ + 0x0a;  
379             }  
380             if ((abt[2 * p + 1] >= ‘0‘) && (abt[2 * p + 1] <= ‘9‘)) {  
381                 k = abt[2 * p + 1] - ‘0‘;  
382             } else if ((abt[2 * p + 1] >= ‘a‘) && (abt[2 * p + 1] <= ‘z‘)) {  
383                 k = abt[2 * p + 1] - ‘a‘ + 0x0a;  
384             } else {  
385                 k = abt[2 * p + 1] - ‘A‘ + 0x0a;  
386             }  
387             int a = (j << 4) + k;  
388             byte b = (byte) a;  
389             bbt[p] = b;  
390         }  
391         return bbt;  
392     }
393     /**
394      * 去除字符串中的符合${}形式的子串.
395      * @param
396      * @return 去除${}的字符串
397      */
398     public static String escape$String(String input) {
399         return input.replaceAll("\\$\\{[^}]*\\}", "");
400     }
401 
402     public static String replace$String(String input, String newStr) {
403         return input.replaceAll("\\$\\{[^}]*\\}", newStr);
404     }
405 
406     public static String replace$SpecifyString(String input, String str,
407             String newStr) {
408         if(input != null){
409             input = input.replaceAll("\\$\\{" + str + "\\}", newStr);
410         }
411         return input;
412     }
413     
414     public static String replace$String(Map<String, Object> map, String src) {
415         if (src != null && map != null) {
416             for (String key : map.keySet()) {
417                 String value =http://www.mamicode.com/ String.valueOf(map.get(key));
418                 src =http://www.mamicode.com/ replace$SpecifyString(src, key, value);
419             }
420         }
421         return src;
422         
423     }
424     /**
425      * 生成验证码
426      * @return
427      */
428     public static String createValidateCode(){
429         String str = "0,1,2,3,4,5,6,7,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D";
430         String str2[] = str.split(",");//将字符串以,分割
431         String code="";
432         for(int i=0;i<4;i++){
433             int a=(int)(Math.random()*36);
434             code=code+str2[a];
435         }
436         return code;
437     }
438     /**
439      * 根据身份证计算年龄
440      * @param idNumber
441      * @return
442      */
443     public static int calculateAgeByIdNumber(String idNumber){
444         int leh = idNumber.length();
445         int years =0;
446         if (leh == 18) {
447             years=Integer.parseInt(idNumber.substring(6, 10));
448         }else {
449             years = Integer.parseInt("19" + idNumber.substring(6, 8));
450         }
451         Calendar a=Calendar.getInstance();
452         return a.get(Calendar.YEAR)-years;
453     }
454     /**
455      * 根据身份证计算性别
456      * @param idNumber
457      * @return
458      */
459     public static int calculateSexByIdNumber(String idNumber){
460         int leh = idNumber.length();
461         int se =0;
462         if (leh == 18) {
463             se=Integer.valueOf(idNumber.substring(16,17)) % 2;
464         }
465         return (se==1?1:2);
466     }
467     
468     /**
469      * 查找数字在数组中得区间.
470      * @param sortedData 排序数组
471      * @param findValue
472      * @return
473      */
474     public static int searchValueSectionInArr(Integer[] sortedData,int findValue) {
475         int start = 0;
476         int end = 0;
477         for (int i = 0; i < sortedData.length; i++) {
478             if (findValue >= sortedData[i]) {
479                 start = i;
480             } else {
481                 end = i;
482                 break;
483             }
484         }
485         return start;
486     }
487     
488     /** 
489      * 循环二分查找数组区间,返回第一次出现该值的位置 
490      * @param sortedData    已排序的数组 
491      * @param findValue     需要找的值 
492      * @return 值在数组中的位置,从0开始。找不到返回-1 
493      */  
494     public static int binarySearch(Integer[] sortedData,int findValue)  {  
495         int start=0;  
496         int end=sortedData.length-1;  
497           
498         while(start<=end)  {  
499             //中间位置  
500             int middle=(start+end)>>1;    //相当于(start+end)/2
501      //   System.out.println("middle==>>" + middle);
502             //中值  
503             int middleValue=http://www.mamicode.com/sortedData[middle];  
504 
505              if(findValue < middleValue)  {
506                 //小于中值时在中值前面找  
507                 end = middle-1;
508                 //如果小于前边的值 和前 前边的值  则继续下一次查找
509                 if (end >= 0) {
510                     int end_v =sortedData[end];
511                     if (findValue >= end_v) {
512                         return end;
513                     }
514                 } else {
515                     return middle;
516                 }
517             }  
518             else   {  
519                 //大于中值在中值后面找  
520                 start=middle+1;
521                 if (start <= sortedData.length -1) {
522                     int end_v = sortedData[start];
523                     if (findValue < end_v) {
524                         return middle;
525                     }
526                 } else {
527                     return middle;
528                 }
529             }  
530         }  
531         //找不到  
532         return -1;  
533     }  
534     
535     
536 
537     public static void main(String[] args) {
538         Integer age=calculateAgeByIdNumber("133022198201242396");
539         Integer sex=calculateSexByIdNumber("133022198201242396");
540         System.out.println("age"+age+">>>>>>sex>>>>>>>>>"+sex);
541     }
542 }
StringUtils
技术分享
 1 package cn.easybuy.utils;
 2 
 3 import java.io.Serializable;
 4 import java.sql.SQLException;
 5 
 6 public class UniqueConstraintException extends RuntimeException implements Serializable {
 7 
 8     //包装类异常
 9     public UniqueConstraintException(SQLException e) {
10         super(e);
11     }
12 
13 }
UniqueConstraintException

 

以上是utils类代码


 

技术分享
 1 package cn.easybuy.web;
 2 
 3 import cn.easybuy.utils.EmptyUtils;
 4 import cn.easybuy.utils.PrintUtil;
 5 import cn.easybuy.utils.ReturnResult;
 6 
 7 import javax.servlet.ServletException;
 8 import javax.servlet.http.HttpServlet;
 9 import javax.servlet.http.HttpServletRequest;
10 import javax.servlet.http.HttpServletResponse;
11 import java.io.IOException;
12 import java.lang.reflect.InvocationTargetException;
13 import java.lang.reflect.Method;
14 
15 /**
16  * 公共的Servlet抽象类
17  * 
18  */
19 public abstract class AbstractServlet extends HttpServlet {
20 
21 
22     public abstract Class getServletClass();
23 
24     protected void doGet(HttpServletRequest req, HttpServletResponse resp)
25             throws ServletException, IOException {
26         doPost(req, resp);
27     }
28 
29     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
30         String actionIndicator = req.getParameter("action");
31         Method method = null;
32         Object result = null;
33         try {
34             if (EmptyUtils.isEmpty(actionIndicator)) {
35                 result = execute(req, resp);
36             } else {
37                 method = getServletClass().getDeclaredMethod(actionIndicator, HttpServletRequest.class, HttpServletResponse.class);
38                 result = method.invoke(this, req, resp);
39             }
40             toView(req, resp, result);
41         } catch (NoSuchMethodException e) {
42             String viewName = "404.jsp";
43             req.getRequestDispatcher(viewName).forward(req, resp);
44         } catch (Exception e) {
45             e.printStackTrace();
46             if (!EmptyUtils.isEmpty(result)) {
47                 if (result instanceof String) {
48                     String viewName = "500.jsp";
49                     req.getRequestDispatcher(viewName).forward(req, resp);
50                 } else {
51                     ReturnResult returnResult = new ReturnResult();
52                     returnResult.returnFail("系统错误");
53                     PrintUtil.write(returnResult, resp);
54                 }
55             } else {
56                 String viewName = "500.jsp";
57                 req.getRequestDispatcher(viewName).forward(req, resp);
58             }
59 
60         }
61     }
62 
63     protected void toView(HttpServletRequest req, HttpServletResponse resp, Object result) throws IOException, ServletException {
64         if (!EmptyUtils.isEmpty(result)) {
65             if (result instanceof String) {
66                 String viewName = result.toString() + ".jsp";
67                 req.getRequestDispatcher(viewName).forward(req, resp);
68             } else {
69                 PrintUtil.write(result, resp);
70             }
71         }
72     }
73 
74     public Object execute(HttpServletRequest req, HttpServletResponse resp) {
75         return "pre/index";
76     }
77 }
AbstractServlet

 

以上是web类代码


技术分享
 1 package cn.easybuy.web.backend;
 2 import javax.servlet.ServletException;
 3 import javax.servlet.annotation.WebServlet;
 4 import javax.servlet.http.HttpServletRequest;
 5 import javax.servlet.http.HttpServletResponse;
 6 
 7 import com.sun.faces.renderkit.html_basic.HtmlBasicRenderer.Param;
 8 
 9 import cn.easybuy.entity.News;
10 import cn.easybuy.param.NewsParams;
11 import cn.easybuy.service.news.NewsService;
12 import cn.easybuy.service.product.ProductService;
13 import cn.easybuy.service.news.NewsServiceImpl;
14 import cn.easybuy.service.product.ProductServiceImpl;
15 import cn.easybuy.utils.EmptyUtils;
16 import cn.easybuy.utils.Pager;
17 import cn.easybuy.web.AbstractServlet;
18 
19 import java.util.List;
20 
21 @WebServlet(urlPatterns = {"/admin/news"},name = "adminNews")
22 public class AdminNewsServlet extends AbstractServlet {
23 
24     private NewsService newsService;
25     private ProductService productService;
26 
27     public void init() throws ServletException {
28         this.newsService = new NewsServiceImpl();
29         this.productService = new ProductServiceImpl();
30     }
31 
32     @Override
33     public Class getServletClass() {
34         return AdminNewsServlet.class;
35     }
36 
37     /**
38      * 查询新闻列表
39      * @param request
40      * @param response
41      * @return
42      */
43     public String queryNewsList(HttpServletRequest request, HttpServletResponse response)throws Exception{
44         //获取当前页数
45         String currentPageStr = request.getParameter("currentPage");
46         //获取页大小
47         String pageSize = request.getParameter("pageSize");
48         int rowPerPage = EmptyUtils.isEmpty(pageSize)?10:Integer.parseInt(pageSize);
49         int currentPage = EmptyUtils.isEmpty(currentPageStr)?1:Integer.parseInt(currentPageStr);
50         int total=newsService.queryNewsCount(new NewsParams());
51         Pager pager=new Pager(total,rowPerPage,currentPage);
52         pager.setUrl("/admin/news?action=queryNewsList");
53         NewsParams params = new NewsParams();
54         params.openPage((pager.getCurrentPage() - 1) * pager.getRowPerPage(),pager.getRowPerPage());
55         List<News> newsList = newsService.queryNewsList(params);
56         request.setAttribute("newsList", newsList);
57         request.setAttribute("pager", pager);
58         request.setAttribute("menu", 7);
59         return "/backend/news/newsList";
60     }
61     /**
62      * 查询新闻详情
63      * @param request
64      * @param response
65      * @return
66      */
67     public String newsDeatil(HttpServletRequest request,HttpServletResponse response)throws Exception{
68         String id = request.getParameter("id");
69         News news=newsService.findNewsById(id);
70         request.setAttribute("news",news);
71         request.setAttribute("menu", 7);
72         return "/backend/news/newsDetail";
73     }
74 
75 }
AdminNewsServlet
技术分享
 1 package cn.easybuy.web.backend;
 2 import cn.easybuy.entity.*;
 3 import cn.easybuy.service.order.OrderService;
 4 import cn.easybuy.service.order.OrderServiceImpl;
 5 import cn.easybuy.utils.EmptyUtils;
 6 import cn.easybuy.utils.Pager;
 7 import cn.easybuy.utils.Params;
 8 import cn.easybuy.web.AbstractServlet;
 9 
10 import javax.servlet.ServletException;
11 import javax.servlet.annotation.WebServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 import java.util.List;
15 
16 /**
17  * 
18  */
19 @WebServlet(urlPatterns = {"/admin/order"},name = "order")
20 public class AdminOrderServlet extends AbstractServlet{
21 
22     private OrderService orderService;
23 
24     public void init() throws ServletException {
25         orderService = new OrderServiceImpl();
26     }
27     /**
28      * 订单的主页面
29      * @param request
30      * @param response
31      * @return
32      */
33     public String index(HttpServletRequest request,HttpServletResponse response)throws Exception{
34         //获取用户id
35         String userId=request.getParameter("userId");
36         //获取当前页数
37         String currentPageStr = request.getParameter("currentPage");
38         //获取页大小
39         String pageSize = request.getParameter("pageSize");
40         int rowPerPage  = EmptyUtils.isEmpty(pageSize)?5:Integer.parseInt(pageSize);
41         int currentPage = EmptyUtils.isEmpty(currentPageStr)?1:Integer.parseInt(currentPageStr);
42         int total=orderService.count(Integer.valueOf(userId));
43         Pager pager=new Pager(total,rowPerPage,currentPage);
44         pager.setUrl("/admin/order?action=index&userId="+userId);
45         List<Order> orderList=orderService.getOrderList(Integer.valueOf(userId), currentPage, rowPerPage);
46         request.setAttribute("orderList", orderList);
47         request.setAttribute("pager", pager);
48         request.setAttribute("menu", 1);
49         return "/backend/order/orderList";
50     }
51     /**
52      * 查询订单明细
53      * @param request
54      * @param response
55      * @return
56      */
57     public String queryOrderDeatil(HttpServletRequest request,HttpServletResponse response)throws Exception{
58         String orderId=request.getParameter("orderId");
59         List<OrderDetail> orderDetailList=orderService.getOrderDetailList(Integer.valueOf(orderId));
60         request.setAttribute("orderDetailList", orderDetailList);
61         request.setAttribute("menu", 1);
62         return "/backend/order/orderDetailList";
63     }
64     
65     public String queryAllOrder(HttpServletRequest request,HttpServletResponse response)throws Exception{
66         //获取当前页数
67         String currentPageStr = request.getParameter("currentPage");
68         //获取页大小
69         String pageSize = request.getParameter("pageSize");
70         int rowPerPage  = EmptyUtils.isEmpty(pageSize)?5:Integer.parseInt(pageSize);
71         int currentPage = EmptyUtils.isEmpty(currentPageStr)?1:Integer.parseInt(currentPageStr);
72         int total=orderService.count(null);
73         Pager pager=new Pager(total,rowPerPage,currentPage);
74         pager.setUrl("/admin/order?action=queryAllOrder");
75         List<Order> orderList=orderService.getOrderList(null, currentPage, rowPerPage);
76         request.setAttribute("orderList", orderList);
77         request.setAttribute("pager", pager);
78         request.setAttribute("menu", 9);
79         return "/backend/order/orderList";
80     }
81 
82     @Override
83     public Class getServletClass() {
84         return AdminOrderServlet.class;
85     }
86 }
AdminOrderServlet
技术分享
  1 package cn.easybuy.web.backend;
  2 import cn.easybuy.entity.ProductCategory;
  3 import cn.easybuy.param.ProductCategoryParam;
  4 import cn.easybuy.service.product.ProductCategoryService;
  5 import cn.easybuy.service.product.ProductCategoryServiceImpl;
  6 import cn.easybuy.service.product.ProductService;
  7 import cn.easybuy.service.product.ProductServiceImpl;
  8 import cn.easybuy.utils.Constants;
  9 import cn.easybuy.utils.EmptyUtils;
 10 import cn.easybuy.utils.Pager;
 11 import cn.easybuy.utils.Params;
 12 import cn.easybuy.utils.ReturnResult;
 13 import cn.easybuy.web.AbstractServlet;
 14 
 15 import javax.servlet.ServletException;
 16 import javax.servlet.annotation.WebServlet;
 17 import javax.servlet.http.HttpServletRequest;
 18 import javax.servlet.http.HttpServletResponse;
 19 import java.util.List;
 20 
 21 @WebServlet(urlPatterns = { "/admin/productCategory" }, name = "adminProductCategory")
 22 public class AdminProductCategoryServlet extends AbstractServlet{
 23 
 24     private ProductCategoryService productCategoryService;
 25     
 26     private ProductService productService;
 27 
 28     public void init() throws ServletException {
 29         this.productCategoryService = new ProductCategoryServiceImpl();
 30         this.productService=new ProductServiceImpl();
 31     }
 32     /**
 33      * 订单的主页面
 34      * @param request
 35      * @param response
 36      * @return
 37      */
 38     public String index(HttpServletRequest request,HttpServletResponse response)throws Exception{
 39         //获取当前页数
 40         String currentPageStr = request.getParameter("currentPage");
 41         //获取页大小
 42         String pageSize = request.getParameter("pageSize");
 43         int rowPerPage  = EmptyUtils.isEmpty(pageSize)?8:Integer.parseInt(pageSize);
 44         int currentPage = EmptyUtils.isEmpty(currentPageStr)?1:Integer.parseInt(currentPageStr);
 45         ProductCategoryParam params =new ProductCategoryParam();
 46         int total=productCategoryService.queryProductCategoryCount(params);
 47         Pager pager=new Pager(total,rowPerPage,currentPage);
 48         params.openPage((pager.getCurrentPage()-1)*pager.getRowPerPage(),pager.getRowPerPage());
 49         pager.setUrl("/admin/productCategory?action=index");
 50         List<ProductCategory> productCategoryList=productCategoryService.queryProductCategoryList(params);
 51         request.setAttribute("productCategoryList", productCategoryList);
 52         request.setAttribute("pager", pager);
 53         request.setAttribute("menu", 4);
 54         return "/backend/productCategory/productCategoryList";
 55     }
 56     /**
 57      * 添加商品分类
 58      * @param request
 59      * @param response
 60      * @return
 61      */
 62     public String toAddProductCategory(HttpServletRequest request,HttpServletResponse response)throws Exception{
 63         //查询一级分类 全部
 64         List<ProductCategory> productCategoryList=null;
 65         ProductCategoryParam params =new ProductCategoryParam();
 66         params.setType(1);
 67         productCategoryList=productCategoryService.queryProductCategoryList(params);
 68         request.setAttribute("productCategoryList1",productCategoryList);
 69         request.setAttribute("productCategory",new ProductCategory());
 70         return "/backend/productCategory/toAddProductCategory";
 71     }
 72     /**
 73      * 修改商品分类
 74      * @param request
 75      * @param response
 76      * @return
 77      */
 78     public String toUpdateProductCategory(HttpServletRequest request,HttpServletResponse response)throws Exception{
 79         String id=request.getParameter("id");
 80         ProductCategory productCategory=productCategoryService.getById(Integer.parseInt(id));
 81         List<ProductCategory> productCategoryList1=null;
 82         List<ProductCategory> productCategoryList2=null;
 83         List<ProductCategory> productCategoryList3=null;
 84         request.setAttribute("productCategory",productCategory);
 85         //判断分类级别
 86         if(productCategory.getType()>=1){
 87             ProductCategoryParam params =new ProductCategoryParam();
 88             params.setType(1);
 89             productCategoryList1=productCategoryService.queryProductCategoryList(params);
 90         }
 91         if(productCategory.getType()>=2){
 92             ProductCategoryParam params =new ProductCategoryParam();
 93             params.setType(2);
 94             productCategoryList2=productCategoryService.queryProductCategoryList(params);
 95             request.setAttribute("parentProductCategory",productCategoryService.getById(productCategory.getParentId()));
 96         }
 97         if(productCategory.getType()>=3){
 98             List<ProductCategory> productCategoryList=null;
 99             ProductCategoryParam params =new ProductCategoryParam();
100             params.setType(3);
101             productCategoryList3=productCategoryService.queryProductCategoryList(params);
102         }
103         request.setAttribute("productCategoryList1",productCategoryList1);
104         request.setAttribute("productCategoryList2",productCategoryList2);
105         request.setAttribute("productCategoryList3",productCategoryList3);
106         return "/backend/productCategory/toAddProductCategory";
107     }
108 
109     /**
110      * 查询子分类
111      * @param request
112      * @param response
113      * @return
114      * @throws Exception
115      */
116     public ReturnResult queryProductCategoryList(HttpServletRequest request,HttpServletResponse response)throws Exception{
117         ReturnResult result=new ReturnResult();
118         String parentId=request.getParameter("parentId");
119         List<ProductCategory> productCategoryList=null;
120         ProductCategoryParam params =new ProductCategoryParam();
121         params.setParentId(EmptyUtils.isEmpty(parentId)?0:Integer.parseInt(parentId));
122         productCategoryList=productCategoryService.queryProductCategoryList(params);
123         result.setStatus(Constants.ReturnResult.SUCCESS);
124         result.setData(productCategoryList);
125         return result;
126     }
127     /**
128      * 修改商品分类
129      * @param request
130      * @param response
131      * @return
132      * @throws Exception
133      */
134     public ReturnResult modifyProductCategory(HttpServletRequest request,HttpServletResponse response)throws Exception{
135         ReturnResult result=new ReturnResult();
136         Integer parentId=0;
137         String id=request.getParameter("id");
138         String productCategoryLevel1=request.getParameter("productCategoryLevel1");
139         String productCategoryLevel2=request.getParameter("productCategoryLevel2");
140         String name=request.getParameter("name");
141         String type=request.getParameter("type");
142         if(type.equals("1")){
143             parentId =0;
144         }else if(type.equals("2")){
145             parentId =Integer.parseInt(productCategoryLevel1);
146         }else{
147             parentId =Integer.parseInt(productCategoryLevel2);
148         }
149         ProductCategory productCategory  =new ProductCategory();
150         productCategory.setId(Integer.parseInt(id));
151         productCategory.setParentId(parentId);
152         productCategory.setName(name);
153         productCategory.setType(Integer.parseInt(type));
154         productCategoryService.modifyProductCategory(productCategory);
155         result.returnSuccess();
156         return result;
157     }
158     /**
159      * 添加商品分类
160      * @param request
161      * @param response
162      * @return
163      * @throws Exception
164      */
165     public ReturnResult addProductCategory(HttpServletRequest request,HttpServletResponse response)throws Exception{
166         ReturnResult result=new ReturnResult();
167         Integer parentId=0;
168         //获取分类级别
169         String type=request.getParameter("type");
170         String productCategoryLevel1=request.getParameter("productCategoryLevel1");
171         String productCategoryLevel2=request.getParameter("productCategoryLevel2");
172         String name=request.getParameter("name");
173         if(type.equals("1")){
174             parentId =0;
175         }else if(type.equals("2")){
176             parentId =Integer.parseInt(productCategoryLevel1);
177         }else{
178             parentId =Integer.parseInt(productCategoryLevel2);
179         }
180         ProductCategory productCategory =new ProductCategory();
181         productCategory.setName(name);
182         productCategory.setParentId(parentId);
183         productCategory.setType(Integer.parseInt(type));
184         productCategory.setIconClass("");
185         productCategoryService.addProductCategory(productCategory);
186         result.returnSuccess();
187         return result;
188     }
189     /**
190      * 删除商品分类
191      * @param request
192      * @param response
193      * @return
194      * @throws Exception
195      */
196     public ReturnResult deleteProductCategory(HttpServletRequest request,HttpServletResponse response)throws Exception{
197         ReturnResult result=new ReturnResult();
198         //获取分类id
199         String id=request.getParameter("id");
200         String type=request.getParameter("type");
201         //查询是否有子类
202         ProductCategoryParam productCategoryParam=new ProductCategoryParam();
203         productCategoryParam.setParentId(Integer.parseInt(id));
204         int count=productCategoryService.queryProductCategoryCount(productCategoryParam);
205         if(count>0){
206             return result.returnFail("已经存在子分类,不能删除");
207         }
208         //查询是否有商品
209         count=productService.count(null,Integer.parseInt(id),Integer.parseInt(type));
210         if(count>0){
211             return result.returnFail("已经存在商品,不能删除");
212         }
213         productCategoryService.deleteById(Integer.parseInt(id));
214         result.returnSuccess();
215         return result;
216     }
217 
218     @Override
219     public Class getServletClass() {
220         return AdminProductCategoryServlet.class;
221     }
222 }
AdminProductCategoryServlet
技术分享
  1 package cn.easybuy.web.backend;
  2 import javax.servlet.ServletConfig;
  3 import javax.servlet.ServletException;
  4 import javax.servlet.annotation.WebServlet;
  5 import javax.servlet.http.HttpServletRequest;
  6 import javax.servlet.http.HttpServletResponse;
  7 
  8 import cn.easybuy.entity.Product;
  9 import cn.easybuy.entity.ProductCategory;
 10 import cn.easybuy.param.ProductCategoryParam;
 11 import cn.easybuy.service.product.ProductCategoryService;
 12 import cn.easybuy.service.product.ProductService;
 13 import cn.easybuy.service.product.ProductCategoryServiceImpl;
 14 import cn.easybuy.service.product.ProductServiceImpl;
 15 import cn.easybuy.utils.EmptyUtils;
 16 import cn.easybuy.utils.Pager;
 17 import cn.easybuy.utils.Params;
 18 import cn.easybuy.utils.ReturnResult;
 19 import cn.easybuy.utils.StringUtils;
 20 import cn.easybuy.web.AbstractServlet;
 21 
 22 import org.apache.commons.fileupload.FileItem;
 23 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
 24 import org.apache.commons.fileupload.servlet.ServletFileUpload;
 25 import java.io.File;
 26 import java.util.HashMap;
 27 import java.util.Iterator;
 28 import java.util.List;
 29 import java.util.Map;
 30 
 31 @WebServlet(urlPatterns = {"/admin/product"},name = "adminProduct")
 32 public class AdminProductServlet extends AbstractServlet {
 33 
 34     private ProductCategoryService productCategoryService;
 35     private static final String TMP_DIR_PATH = "c:\\tmp";
 36     private File tmpDir;
 37     private static final String DESTINATION_DIR_PATH = "/files";
 38     private File destinationDir;
 39     private ProductService productService;
 40 
 41     public void init(ServletConfig config) throws ServletException {
 42         super.init(config);
 43         tmpDir = new File(TMP_DIR_PATH);
 44         if (!tmpDir.exists()) {//如果目录不存在,则新建目录
 45             tmpDir.mkdirs();
 46         }
 47         String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
 48         destinationDir = new File(realPath);
 49         destinationDir.mkdirs();
 50         if (!destinationDir.isDirectory()) {
 51             throw new ServletException(DESTINATION_DIR_PATH
 52                     + " is not a directory");
 53         }
 54         productService = new ProductServiceImpl();
 55         productCategoryService=new ProductCategoryServiceImpl();
 56     }
 57     /**
 58      * 商品的主页面
 59      * @param request
 60      * @param response
 61      * @return
 62      */
 63     public String index(HttpServletRequest request,HttpServletResponse response)throws Exception{
 64         //获取当前页数
 65         String currentPageStr = request.getParameter("currentPage");
 66         //获取页大小
 67         String pageSize = request.getParameter("pageSize");
 68         int rowPerPage  = EmptyUtils.isEmpty(pageSize)?5:Integer.parseInt(pageSize);
 69         int currentPage = EmptyUtils.isEmpty(currentPageStr)?1:Integer.parseInt(currentPageStr);
 70         int total=productService.count(null, null, null);
 71         Pager pager=new Pager(total,rowPerPage,currentPage);
 72         pager.setUrl("/admin/product?action=index");
 73         List<Product> productList=productService.getProductList(currentPage,rowPerPage, null, null, null);
 74         request.setAttribute("productList", productList);
 75         request.setAttribute("pager", pager);
 76         request.setAttribute("menu",5);
 77         return "/backend/product/productList";
 78     }
 79     /**
 80      * 添加商品
 81      * @return
 82      */
 83     public String toAddProduct(HttpServletRequest request,HttpServletResponse response)throws Exception{
 84         request.setAttribute("menu",6);
 85         request.setAttribute("product",new Product());
 86         //查询一级分类
 87         ProductCategoryParam params =new ProductCategoryParam();
 88         params.setType(1);
 89         List<ProductCategory> productCategoryList=productCategoryService.queryProductCategoryList(params);
 90         //一级分类列表
 91         request.setAttribute("productCategoryList1", productCategoryList);
 92         return "/backend/product/toAddProduct";
 93     }
 94     /**
 95      * 添加商品
 96      * @param request
 97      * @param response
 98      * @throws Exception
 99      */
100     public void addProduct(HttpServletRequest request,HttpServletResponse response)throws Exception {
101         Map<String, String> params = new HashMap<String, String>();
102         Product product=null;
103         DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
104         fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
105         fileItemFactory.setRepository(tmpDir);
106         String fileName = null;
107         ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
108         uploadHandler.setHeaderEncoding("utf-8");
109         try {
110             List items = uploadHandler.parseRequest(request);
111             Iterator itr = items.iterator();
112             while (itr.hasNext()) {
113                 FileItem item = (FileItem) itr.next();
114                 if (item.isFormField()) {
115                     params.put(item.getFieldName(), item.getString("utf-8"));
116                 } else {
117                     if (item.getSize() > 0) {//修改图片
118                         fileName = item.getName().substring(
119                                 item.getName().lastIndexOf("."));
120                         File file = new File(destinationDir, fileName);
121                         fileName = StringUtils.randomUUID()
122                                 + item.getName().substring(
123                                 item.getName().lastIndexOf("."));
124                         file = new File(destinationDir, fileName);//图片名与商品ID一致
125                         item.write(file);//保存商品图片
126                     }
127                 }
128             }
129             //获取商品参数
130             product=copyToProduct(params);
131             product.setFileName(fileName);
132             Integer id = product.getId();
133             if (EmptyUtils.isEmpty(id) || id.equals("0")) {
134                productService.add(product);
135             } else {
136                 if(EmptyUtils.isEmpty(product.getFileName())|| product.getFileName().length()<5){
137                     Product productDemo=productService.getProductById(id);
138                     product.setFileName(productDemo.getFileName());
139                 }
140                 productService.update(product);
141             }
142             
143         }catch (Exception e){
144             e.printStackTrace();
145         }
146         response.sendRedirect(request.getContextPath()+"/admin/product?action=index");
147     }
148     /**
149      * 添加商品
150      * @return
151      */
152     public String toUpdateProduct(HttpServletRequest request,HttpServletResponse response)throws Exception{
153         String id=request.getParameter("id");
154         Product product=productService.getProductById(Integer.valueOf(id));
155         request.setAttribute("menu",6);
156         //查询一级分类
157         ProductCategoryParam params =new ProductCategoryParam();
158         params.setType(1);
159         List<ProductCategory> productCategoryList1=productCategoryService.queryProductCategoryList(params);
160         params.setType(2);
161         List<ProductCategory> productCategoryList2=productCategoryService.queryProductCategoryList(params);
162         params.setType(3);
163         List<ProductCategory> productCategoryList3=productCategoryService.queryProductCategoryList(params);
164         //一级分类列表
165         request.setAttribute("productCategoryList1", productCategoryList1);
166         request.setAttribute("productCategoryList2", productCategoryList2);
167         request.setAttribute("productCategoryList3", productCategoryList3);
168         request.setAttribute("product", product);
169         return "/backend/product/toAddProduct";
170     }
171     /**
172      * 根据id删除商品
173      * @param request
174      * @param response
175      * @return
176      * @throws Exception
177      */
178     public ReturnResult deleteById(HttpServletRequest request,HttpServletResponse response)throws Exception{
179         ReturnResult result=new ReturnResult();
180         String id=request.getParameter("id");
181         productService.deleteProductById(Integer.parseInt(id));
182         result.returnSuccess();
183         return result;
184     }
185 
186     private Product copyToProduct(Map<String,String> params)throws Exception{
187         Product product=new Product();
188         String id=params.get("id");
189         String name=params.get("name");
190         String description=params.get("description");
191         String price=params.get("price");
192         String stock=params.get("stock");
193         String categoryLevel1Id=params.get("categoryLevel1Id");
194         String categoryLevel2Id=params.get("categoryLevel2Id");
195         String categoryLevel3Id=params.get("categoryLevel3Id");
196         product.setName(name);
197         product.setDescription(description);
198         product.setPrice(Float.valueOf(price));
199         product.setStock(Integer.parseInt(stock));
200         product.setCategoryLevel1Id(EmptyUtils.isNotEmpty(categoryLevel1Id)?Integer.parseInt(categoryLevel1Id):0);
201         product.setCategoryLevel2Id(EmptyUtils.isNotEmpty(categoryLevel2Id)?Integer.parseInt(categoryLevel2Id):0);
202         product.setCategoryLevel3Id(EmptyUtils.isNotEmpty(categoryLevel3Id)?Integer.parseInt(categoryLevel3Id):0);
203         product.setId(EmptyUtils.isNotEmpty(id)?Integer.parseInt(id):null);
204         return product;
205     }
206 
207     @Override
208     public Class getServletClass() {
209         return AdminProductServlet.class;
210     }
211 }
AdminProductServlet
技术分享
  1 package cn.easybuy.web.backend;
  2 
  3 import cn.easybuy.entity.User;
  4 import cn.easybuy.service.user.UserService;
  5 import cn.easybuy.service.user.UserServiceImpl;
  6 import cn.easybuy.utils.Constants;
  7 import cn.easybuy.utils.EmptyUtils;
  8 import cn.easybuy.utils.Pager;
  9 import cn.easybuy.utils.Params;
 10 import cn.easybuy.utils.RegUtils;
 11 import cn.easybuy.utils.ReturnResult;
 12 import cn.easybuy.utils.SecurityUtils;
 13 import cn.easybuy.web.AbstractServlet;
 14 
 15 import javax.servlet.ServletException;
 16 import javax.servlet.annotation.WebServlet;
 17 import javax.servlet.http.HttpServletRequest;
 18 import javax.servlet.http.HttpServletResponse;
 19 import java.util.List;
 20 
 21 @WebServlet(urlPatterns = {"/admin/user"}, name = "adminUser")
 22 public class AdminUserServlet extends AbstractServlet {
 23 
 24     private UserService userService;
 25 
 26     public void init() throws ServletException {
 27         userService = new UserServiceImpl();
 28     }
 29 
 30     @Override
 31     public Class getServletClass() {
 32         return AdminUserServlet.class;
 33     }
 34 
 35     /**
 36      * 跳到用户主页
 37      *
 38      * @param request
 39      * @param response
 40      * @return
 41      */
 42     public String index(HttpServletRequest request, HttpServletResponse response) throws Exception {
 43         //获取登陆用户
 44         User user = (User) request.getSession().getAttribute("loginUser");
 45         request.setAttribute("user", user);
 46         request.setAttribute("menu", 2);
 47         return "/backend/user/userInfo";
 48     }
 49 
 50     /**
 51      * 订单的主页面
 52      *
 53      * @param request
 54      * @param response
 55      * @return
 56      */
 57     public String queryUserList(HttpServletRequest request, HttpServletResponse response) throws Exception {
 58         //获取当前页数
 59         String currentPageStr = request.getParameter("currentPage");
 60         //获取页大小
 61         String pageSize = request.getParameter("pageSize");
 62         int rowPerPage = EmptyUtils.isEmpty(pageSize) ? 10 : Integer.parseInt(pageSize);
 63         int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
 64         int total = userService.count();
 65         Pager pager = new Pager(total, rowPerPage, currentPage);
 66         List<User> userList = userService.getUserList(currentPage, rowPerPage);
 67         pager.setUrl("/admin/user?action=queryUserList");
 68         request.setAttribute("userList", userList);
 69         request.setAttribute("pager", pager);
 70         request.setAttribute("menu", 8);
 71         return "/backend/user/userList";
 72     }
 73 
 74     /**
 75      * 修改用户信息
 76      *
 77      * @param request
 78      * @param response
 79      * @return
 80      * @throws Exception
 81      */
 82     public String toUpdateUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
 83         String id = request.getParameter("id");
 84         User user = userService.getUser(Integer.parseInt(id), null);
 85         request.setAttribute("user", user);
 86         return "/backend/user/toUpdateUser";
 87     }
 88 
 89     /**
 90      * 去添加用户
 91      *
 92      * @param request
 93      * @param response
 94      * @return
 95      * @throws Exception
 96      */
 97     public String toAddUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
 98         User user = new User();
 99         request.setAttribute("user", user);
100         return "/backend/user/toUpdateUser";
101     }
102     /**
103      * 更新用户
104      * @param request
105      * @param response
106      * @return
107      * @throws Exception
108      */
109     public ReturnResult updateUser(HttpServletRequest request, HttpServletResponse response) throws Exception {
110         ReturnResult result = new ReturnResult();
111         String id = request.getParameter("id");
112         User user = new User();
113         String loginName = request.getParameter("loginName");
114         String sex = request.getParameter("sex");
115         User oldUser = userService.getUser(null, loginName);
116         
117         //判断用户
118         if (EmptyUtils.isNotEmpty(oldUser) && (EmptyUtils.isEmpty(id) || oldUser.getId() != Integer.parseInt(id))) {
119             result.returnFail("用户已经存在");
120             return result;
121         }
122         user.setLoginName(loginName);
123         user.setUserName(request.getParameter("userName"));
124         user.setSex(EmptyUtils.isEmpty(sex) ? 1 : 0);
125         if (EmptyUtils.isEmpty(id) || id.equals("0")) {
126             user.setPassword(SecurityUtils.md5Hex(request.getParameter("password")));
127         }
128         user.setIdentityCode(request.getParameter("identityCode"));
129         user.setEmail(request.getParameter("email"));
130         user.setMobile(request.getParameter("mobile"));
131         user.setType(Integer.parseInt(request.getParameter("type")));
132         
133         result=checkUser(user);
134         //是否验证通过
135         if(result.getStatus()==Constants.ReturnResult.SUCCESS){
136              if (EmptyUtils.isEmpty(id) || id.equals("0")) {
137                  if(!userService.add(user)){
138                      return result.returnFail("增加失败!");
139                  }
140              } else {
141                  user.setId(Integer.parseInt(id));
142                   if(!userService.update(user)){
143                      return result.returnFail("修改失败!");
144                  }
145              }
146         }
147         result.returnSuccess();
148         return result;
149         
150         
151     }
152     
153     public ReturnResult deleteUserById(HttpServletRequest request, HttpServletResponse response) throws Exception {
154           ReturnResult result = new ReturnResult();
155           String id = request.getParameter("id");
156           userService.deleteUserById(Integer.parseInt(id));
157           result.returnSuccess();
158           return result;
159     }
160     private ReturnResult checkUser(User user){
161         ReturnResult result = new ReturnResult();
162         boolean flag=true;
163         if(EmptyUtils.isNotEmpty(user.getMobile())){
164             if(!RegUtils.checkMobile(user.getMobile())){
165                 return result.returnFail("手机格式不正确");
166             }
167         }
168         
169         if(EmptyUtils.isNotEmpty(user.getIdentityCode())){
170             if(!RegUtils.checkIdentityCodeReg(user.getIdentityCode())){
171                 return result.returnFail("身份证号码不正确");
172             }
173         }
174         
175         if(EmptyUtils.isNotEmpty(user.getEmail())){
176             if(!RegUtils.checkEmail(user.getEmail())){
177                 return result.returnFail("邮箱格式不正确");
178             }
179         }
180         return result.returnSuccess();
181     }
182     
183 }
AdminUserServlet

 

以上是web.backend类代码


技术分享
  1 package cn.easybuy.web.pre;
  2 
  3 import cn.easybuy.entity.*;
  4 import cn.easybuy.service.order.CartService;
  5 import cn.easybuy.service.order.CartServiceImpl;
  6 import cn.easybuy.service.order.OrderService;
  7 import cn.easybuy.service.order.OrderServiceImpl;
  8 import cn.easybuy.service.product.ProductCategoryService;
  9 import cn.easybuy.service.product.ProductCategoryServiceImpl;
 10 import cn.easybuy.service.product.ProductService;
 11 import cn.easybuy.service.product.ProductServiceImpl;
 12 import cn.easybuy.service.user.UserAddressService;
 13 import cn.easybuy.service.user.UserAddressServiceImpl;
 14 import cn.easybuy.service.user.UserService;
 15 import cn.easybuy.service.user.UserServiceImpl;
 16 import cn.easybuy.utils.Constants;
 17 import cn.easybuy.utils.DataSourceUtil;
 18 import cn.easybuy.utils.EmptyUtils;
 19 import cn.easybuy.utils.ProductCategoryVo;
 20 import cn.easybuy.utils.ReturnResult;
 21 import cn.easybuy.utils.ShoppingCart;
 22 import cn.easybuy.utils.ShoppingCartItem;
 23 import cn.easybuy.web.AbstractServlet;
 24 
 25 import javax.servlet.ServletException;
 26 import javax.servlet.annotation.WebServlet;
 27 import javax.servlet.http.HttpServletRequest;
 28 import javax.servlet.http.HttpServletResponse;
 29 import javax.servlet.http.HttpSession;
 30 import java.util.List;
 31 
 32 
 33 @WebServlet(urlPatterns = {"/Cart"}, name = "Cart")
 34 public class CartServlet extends AbstractServlet {
 35 
 36     private ProductService productService;
 37 
 38     private OrderService orderService;
 39 
 40     private UserService userService;
 41 
 42     private ProductCategoryService productCategoryService;
 43 
 44     private CartService cartService;
 45 
 46     private UserAddressService userAddressService;
 47 
 48     public void init() throws ServletException {
 49         productService = new ProductServiceImpl();
 50         orderService = new OrderServiceImpl();
 51         userService = new UserServiceImpl();
 52         productCategoryService = new ProductCategoryServiceImpl();
 53         cartService = new CartServiceImpl();
 54         userAddressService = new UserAddressServiceImpl();
 55     }
 56 
 57     @Override
 58     public Class getServletClass() {
 59         return CartServlet.class;
 60     }
 61 
 62     /**
 63      * 添加到购物车
 64      *
 65      * @return
 66      */
 67     public ReturnResult add(HttpServletRequest request, HttpServletResponse response) throws Exception {
 68         HttpSession session = request.getSession();
 69         ReturnResult result = new ReturnResult();
 70         String id = request.getParameter("entityId");
 71         String quantityStr = request.getParameter("quantity");
 72         Integer quantity = 1;
 73         if (!EmptyUtils.isEmpty(quantityStr))
 74             quantity = Integer.parseInt(quantityStr);
 75         //查询出商品
 76         Product product = productService.getProductById(Integer.valueOf(id));
 77         if(product.getStock()<quantity){
 78             return result.returnFail("商品数量不足");
 79         }
 80         //获取购物车
 81         ShoppingCart cart = getCartFromSession(request);
 82         //往购物车放置商品
 83         result=cart.addItem(product, quantity);
 84         if(result.getStatus()==Constants.ReturnResult.SUCCESS){
 85             cart.setSum((EmptyUtils.isEmpty(cart.getSum()) ? 0.0 : cart.getSum()) + (product.getPrice() * quantity * 1.0));
 86         }
 87         return result;
 88     }
 89     
 90     
 91 
 92     /**
 93      * 刷新购物车
 94      *
 95      * @param request
 96      * @param response
 97      * @return
 98      */
 99     public String refreshCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
100         HttpSession session = request.getSession();
101         ShoppingCart cart = getCartFromSession(request);
102         cart = cartService.calculate(cart);
103         session.setAttribute("cart", cart);//全部的商品
104         return "/common/pre/searchBar";
105     }
106 
107     /**
108      * 跳到结算页面
109      *
110      * @param request
111      * @param response
112      * @return
113      */
114     public String toSettlement(HttpServletRequest request, HttpServletResponse response) throws Exception {
115         List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
116         //封装返回
117         request.setAttribute("productCategoryVoList", productCategoryVoList);
118         return "/pre/settlement/toSettlement";
119     }
120 
121     /**
122      * 跳转到购物车页面
123      *
124      * @param request
125      * @param response
126      * @return
127      */
128     public String settlement1(HttpServletRequest request, HttpServletResponse response) throws Exception {
129         ShoppingCart cart = getCartFromSession(request);
130         cart = cartService.calculate(cart);
131         request.getSession().setAttribute("cart",cart);
132         return "/pre/settlement/settlement1";
133     }
134 
135     /**
136      * @param request
137      * @param response
138      * @return
139      */
140     public String settlement2(HttpServletRequest request, HttpServletResponse response) throws Exception {
141         User user = getUserFromSession(request);
142         List<UserAddress> userAddressList = userAddressService.queryUserAdressList(user.getId());
143         request.setAttribute("userAddressList", userAddressList);
144         return "/pre/settlement/settlement2";
145     }
146 
147     /**
148      * 生成订单
149      *
150      * @param request
151      * @param response
152      * @return
153      */
154     public Object settlement3(HttpServletRequest request, HttpServletResponse response) throws Exception {
155         ShoppingCart cart = getCartFromSession(request);
156         cart = cartService.calculate(cart);
157         User user = getUserFromSession(request);
158         ReturnResult result=checkCart(request);
159         if(result.getStatus()==Constants.ReturnResult.FAIL){
160             return result;
161         }
162         //新增地址
163         String addressId=request.getParameter("addressId");
164         String newAddress=request.getParameter("newAddress");
165         String newRemark=request.getParameter("newRemark");
166         UserAddress userAddress=new UserAddress();
167         if(addressId.equals("-1")){
168             userAddress.setRemark(newRemark);
169             userAddress.setAddress(newAddress);
170             userAddress.setId(userAddressService.addUserAddress(user.getId(),newAddress,newRemark));
171         }else{
172             userAddress=userAddressService.getUserAddressById(Integer.parseInt(addressId));
173         }
174         
175         //生成订单
176         Order order = orderService.payShoppingCart(cart,user,userAddress.getAddress());
177         clearCart(request, response);
178         request.setAttribute("currentOrder", order);
179         return "/pre/settlement/settlement3";
180     }
181 
182     /**
183      * 清空购物车
184      *
185      * @param request
186      * @param response
187      */
188     public ReturnResult clearCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
189         ReturnResult result = new ReturnResult();
190         //结账后清空购物车
191         request.getSession().removeAttribute("cart");
192         result.returnSuccess(null);
193         return result;
194     }
195 
196     /**
197      * 修改购物车信息
198      *
199      * @param request
200      * @return
201      */
202     public ReturnResult modCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
203         ReturnResult result = new ReturnResult();
204         HttpSession session = request.getSession();
205         String id = request.getParameter("entityId");
206         String quantityStr = request.getParameter("quantity");
207         ShoppingCart cart = getCartFromSession(request);
208         Product product=productService.getProductById(Integer.valueOf(id));
209         if(EmptyUtils.isNotEmpty(quantityStr)){
210             if(Integer.parseInt(quantityStr)>product.getStock()){
211                 return result.returnFail("商品数量不足");
212             }
213         }
214         cart = cartService.modifyShoppingCart(id, quantityStr, cart);
215         session.setAttribute("cart", cart);//全部的商品
216         return result.returnSuccess();
217     }
218 
219     /**
220      * 从session中获取购物车
221      *
222      * @param request
223      * @return
224      */
225     private ShoppingCart getCartFromSession(HttpServletRequest request) throws Exception {
226         HttpSession session = request.getSession();
227         ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
228         if (cart == null) {
229             cart = new ShoppingCart();
230             session.setAttribute("cart", cart);
231         }
232         return cart;
233     }
234     
235     private ReturnResult checkCart(HttpServletRequest request) throws Exception {
236         ReturnResult result = new ReturnResult();
237         HttpSession session = request.getSession();
238         ShoppingCart cart = getCartFromSession(request);
239         cart = cartService.calculate(cart);
240         for (ShoppingCartItem item : cart.getItems()) {
241            Product product=productService.getProductById(item.getProduct().getId());
242            if(product.getStock()<item.getQuantity()){
243                return result.returnFail(product.getName()+"商品数量不足");
244            }
245         }
246         return result.returnSuccess();
247     }
248 
249     /**
250      * @param request
251      * @return
252      */
253     private User getUserFromSession(HttpServletRequest request) {
254         HttpSession session = request.getSession();
255         User user = (User) session.getAttribute("loginUser");
256         return user;
257     }
258 }
CartServlet
技术分享
  1 package cn.easybuy.web.pre;
  2 
  3 import cn.easybuy.entity.Product;
  4 import cn.easybuy.entity.User;
  5 import cn.easybuy.service.product.ProductService;
  6 import cn.easybuy.service.product.ProductServiceImpl;
  7 import cn.easybuy.utils.EmptyUtils;
  8 import cn.easybuy.utils.MemcachedUtils;
  9 import cn.easybuy.utils.ReturnResult;
 10 import cn.easybuy.web.AbstractServlet;
 11 
 12 import javax.servlet.ServletException;
 13 import javax.servlet.annotation.WebServlet;
 14 import javax.servlet.http.HttpServletRequest;
 15 import javax.servlet.http.HttpServletResponse;
 16 import javax.servlet.http.HttpSession;
 17 import java.util.ArrayList;
 18 import java.util.List;
 19 
 20 
 21 @WebServlet(urlPatterns = {"/Favorite"}, name = "Favorite")
 22 public class FavoriteServlet extends AbstractServlet {
 23 
 24 
 25     private ProductService productService;
 26 
 27     public void init() throws ServletException {
 28         productService = new ProductServiceImpl();
 29     }
 30 
 31     @Override
 32     public Class getServletClass() {
 33         return FavoriteServlet.class;
 34     }
 35 
 36     /**
 37      * 跳转到历史记录
 38      *
 39      * @param request
 40      * @param response
 41      * @return
 42      */
 43     public String toFavoriteList(HttpServletRequest request, HttpServletResponse response)throws Exception {
 44         List<Product> recentProducts=queryFavoriteList(request);
 45         request.setAttribute("recentProducts",recentProducts);
 46         return "/pre/product/favoriteList";
 47     }
 48 
 49     /**
 50      * 添加到收藏
 51      *
 52      * @return
 53      */
 54     public ReturnResult addFavorite(HttpServletRequest request, HttpServletResponse response)throws Exception {
 55         ReturnResult result = new ReturnResult();
 56         String id = request.getParameter("id");
 57         Product product = productService.getProductById(Integer.valueOf(id));
 58         List<Product> favoriteList = queryFavoriteList(request);
 59         //判断是否满了
 60         if (favoriteList.size() > 0 && favoriteList.size() == 5) {
 61             favoriteList.remove(0);
 62         }
 63         boolean temp = false;
 64         for (int i = 0; i < favoriteList.size(); i++) {
 65             if (favoriteList.get(i).getId().equals(product.getId())) {
 66                 temp = true;
 67                 break;
 68             }
 69         }
 70         if (!temp) {
 71             favoriteList.add(favoriteList.size(), product);
 72         }
 73         MemcachedUtils.add(getFavoriteKey(request),favoriteList);
 74         result.returnSuccess();
 75         return result;
 76     }
 77 
 78     /**
 79      * 查询最近商品
 80      *
 81      * @return
 82      */
 83     private List<Product> queryFavoriteList(HttpServletRequest request) throws Exception{
 84         HttpSession session = request.getSession();
 85         User user = (User) session.getAttribute("loginUser");
 86         //判断用户是否登录
 87         String key = EmptyUtils.isEmpty(user) ? session.getId() : user.getLoginName();
 88         List<Product> recentProducts = (List<Product>) MemcachedUtils.get(key);
 89         if (EmptyUtils.isEmpty(recentProducts)) {
 90             recentProducts = new ArrayList<Product>();
 91         }
 92         return recentProducts;
 93     }
 94     /**
 95      *
 96      * @param request
 97      * @return
 98      */
 99     private String getFavoriteKey(HttpServletRequest request)throws Exception{
100         HttpSession session = request.getSession();
101         User user = (User) session.getAttribute("loginUser");
102         return EmptyUtils.isEmpty(user) ? session.getId() : user.getLoginName();
103     }
104 }
FavoriteServlet
技术分享
 1 package cn.easybuy.web.pre;
 2 
 3 import java.util.List;
 4 import javax.servlet.ServletException;
 5 import javax.servlet.annotation.WebServlet;