java web 网上零食商城后端代码

(1)、dao层:
//user
package com.skeyedu.mall.dao.user;

import java.util.List;

import com.skeyedu.mall.dao.IBaseDao;
import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.param.UserParam;

public interface UserDao extends IBaseDao {
User findByLoginName(String loginName) throws Exception;//根据ID查询用户信息
int save(User user) throws Exception; //新增用户信息
void update(User user) throws Exception; //更新用户信息
public void deleteById(String id) throws Exception;
public List queryUserList(UserParam params) throws Exception;
public Integer queryUserCount(UserParam params) throws Exception;
public User queryUserById(Integer id) throws Exception;
}
//
package com.skeyedu.mall.dao.user;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.skeyedu.mall.dao.BaseDaoImpl;
import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.param.UserParam;
import com.skeyedu.mall.utils.EmptyUtils;

public class UserDaoImpl extends BaseDaoImpl implements UserDao{

public UserDaoImpl(Connection connection) {
	super(connection);
	// TODO Auto-generated constructor stub
}

@Override
public User findByLoginName(String loginName) throws Exception {
	// TODO Auto-generated method stub
	User user = null;
	try {
		UserParam param = new UserParam();
		param.setLoginName(loginName);
		List<User> userList = queryUserList(param);
		if(EmptyUtils.isEmpty(userList)) {
			return null;
		}else {
			return userList.get(0);
		}
		
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	return user;
}

@Override
public int save(User user) throws Exception {
	// TODO Auto-generated method stub
	Integer id = 0;
	try {
		String sql = "INSERT INTO skeyedu_user(loginName,userName,password,sex,identityCode,email,mobile) value(?,?,?,?,?,?,?)";
		try {
			Object param[] = new Object[] {user.getLoginName(),user.getUserName(),user.getPassword(),user.getSex(),user.getIdentityCode(),user.getEmail(),user.getMobile()};
			id = this.executeInsert(sql, param);
			user.setId(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		this.closeResource();
	}
	return id;
}

@Override
public void update(User user) throws Exception {
	// TODO Auto-generated method stub
	try {
		Object[] params = new Object[] {user.getUserName(),user.getType(),user.getSex(),user.getIdentityCode(),user.getEmail(),user.getMobile(),user.getId()};
		String sql = "UPDATE skeyedu_user SET userName = ?,type = ?,sex = ?,identityCode = ?,email=?,mobile=? WHERE 1=1 ";
		this.executeUpdate(sql, params);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		this.closeResource();
	}
}

@Override
public void deleteById(String id) throws Exception {
	// TODO Auto-generated method stub
	try {
		String sql = "delete from skeyedu_user where id = ?";
		Object params[] = new Object[] {id};
		this.executeUpdate(sql.toString(), params);
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		this.closeResource();
	}
}

@Override
public Object tableToClass(ResultSet rs) throws Exception {
	// TODO Auto-generated method stub
	User user = new User();
	user.setLoginName(rs.getString("loginName"));
	user.setUserName(rs.getString("userName"));
	user.setPassword(rs.getString("password"));
	user.setSex(rs.getInt("sex"));
	user.setIdentityCode(rs.getString("identityCode"));
	user.setEmail(rs.getString("email"));
	user.setMobile(rs.getString("mobile"));
	user.setType(rs.getInt("type"));
	user.setId(rs.getInt("id"));
	return user;
}

@Override
public List<User> queryUserList(UserParam params) throws Exception {
	// TODO Auto-generated method stub
	List<Object> paramsList = new ArrayList<Object>();
	List<User> userList = new ArrayList<User>();
	StringBuffer sql = new StringBuffer("SELECT id,loginName,password,userName,sex,identityCode,email,mobile,type FROM skeyedu_user WHERE 1=1 ");
	ResultSet resultSet = null;
	try {
		if(EmptyUtils.isNotEmpty(params.getLoginName())) {
			sql.append(" AND loginName = ? ");
			paramsList.add(params.getLoginName());
		}
		if(EmptyUtils.isNotEmpty(params.getSort())) {
			sql.append(" ORDER BY " + params.getSort() + " ");
		}
		if(params.getIsPage()) {
			sql.append(" LIMIT " + params.getStartIndex() + ","+params.getPageSize());
		}
		resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
		while(resultSet.next()) {
			User user= (User) this.tableToClass(resultSet);
			userList.add(user);
		}
		
	} catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		this.closeResource();
		this.closeResource(resultSet);
	}
	return userList;
}

@Override
public Integer queryUserCount(UserParam params) throws Exception {
	// TODO Auto-generated method stub
	List<Object> paramsList = new ArrayList<Object>();
	StringBuffer sql = new StringBuffer("SELECT COUNT(*) count FROM skeyedu_user WHERE 1=1 ");
	Integer count = 0;
	if(EmptyUtils.isNotEmpty(params.getLoginName())) {
		sql.append(" AND loginName = ? ");
		paramsList.add(params.getLoginName());
	}
	ResultSet resultSet = this.executeQuery(sql.toString(), paramsList.toArray());
	try {
		while(resultSet.next()) {
			count = resultSet.getInt("count");
		}
	}catch (SQLException e) {
		e.printStackTrace();
	}catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		this.closeResource();
		this.closeResource(resultSet);
	}
	
	return count;
}

@Override
public User queryUserById(Integer id) throws Exception {
	// TODO Auto-generated method stub
	List<Object> paramsList = new ArrayList<Object>();
	List<User> userList = new ArrayList<User>();
	StringBuffer sql = new StringBuffer("SELECT id,loginName,userName,password,sex,identityCode,email,mobile,type from skeyedu_user WHERE id = ? ");
	ResultSet resultSet = this.executeQuery(sql.toString(), new Object[] {id});
	User user = null;
	try {
		while(resultSet.next()) {
			user= (User) this.tableToClass(resultSet);
		}
	}catch (SQLException e) {
		e.printStackTrace();
	}catch (Exception e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		this.closeResource();
	}
	return user;
}

}
//
prodauct
//
package com.skeyedu.mall.dao.product;

import java.util.List;

import com.skeyedu.mall.dao.IBaseDao;
import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.param.ProductParam;

/**

  • 商品查询Dao
  • deleteById(Integer id)
  • getById(Integer id)
  • getRowCount(params)
  • getRowList(params)
    */
    public interface ProductDao extends IBaseDao {
    void updateStock(Integer id, Integer quantity) throws Exception;
    public void save(Product product) throws Exception;
    public void update(Product product) throws Exception;
    public void deleteById(Integer id) throws Exception;
    public Product getProductById(Integer id)throws Exception;
    public List queryProductList(ProductParam params)throws Exception;
    public Integer queryProductCount(ProductParam params)throws Exception;
    }

////
package com.skeyedu.mall.dao.product;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.skeyedu.mall.dao.BaseDaoImpl;
import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.param.ProductParam;
import com.skeyedu.mall.utils.EmptyUtils;

public class ProductDaoImpl extends BaseDaoImpl implements ProductDao {

public ProductDaoImpl(Connection connection) {
    super(connection);
}

/**
 * 字段 和 列名 的对应
 *
 * @param rs
 * @return
 * @throws Exception
 */
@Override
public Product tableToClass(ResultSet rs) throws Exception {
    Product product = new Product();
    product.setId(rs.getInt("id"));
    product.setName(rs.getString("name"));
    product.setDescription(rs.getString("description"));
    product.setPrice(rs.getFloat("price"));
    product.setStock(rs.getInt("stock"));
    product.setCategoryLevel1Id(rs.getInt("categoryLevel1Id"));
    product.setCategoryLevel2Id(rs.getInt("categoryLevel2Id"));
    product.setCategoryLevel3Id(rs.getInt("categoryLevel3Id"));
    product.setFileName(rs.getString("fileName"));
    product.setSalenumber(rs.getInt("salenumber"));
    return product;
}

public void updateStock(Integer id, Integer quantity) {
    try {
    	Object[] params = new Object[] {quantity,id};
    	String sql = "update skeyedu_product set stock=? where id=? ";
		this.executeUpdate(sql, params);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
		this.closeResource();
	}
}

@Override
public void save(Product product) {
	Integer id=0;
	String sql="insert into skeyedu_product(name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,fileName,isDelete,salenumber) values(?,?,?,?,?,?,?,?,?,?) ";
    try {
        Object param[]=new Object[]{product.getName(),product.getDescription(),product.getPrice(),product.getStock(),product.getCategoryLevel1Id(),product.getCategoryLevel2Id(),product.getCategoryLevel3Id(),product.getFileName(),0,product.getSalenumber()};
        id=this.executeInsert(sql,param);
        product.setId(id);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
		this.closeResource();
	}
}

@Override
public void update(Product product) {
	try {
    	Object[] params = new Object[] {product.getStock(),product.getSalenumber(),product.getId()};
    	String sql = "update skeyedu_product set stock=?,salenumber=? where id=? ";
		this.executeUpdate(sql, params);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
		this.closeResource();
	}
	System.out.println("更新成功!");
}

@Override
public void deleteById(Integer id) throws Exception {
	String sql = "delete from skeyedu_product where id = ? ";
	Object params[] = new Object[] { id };
	try{
		this.executeUpdate(sql.toString(), params);
	}catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource();
	}
}

@Override
public Product getProductById(Integer id) throws Exception {
	String sql = "select id,name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,fileName,isDelete,salenumber from skeyedu_product where id = ? ";
	ResultSet resultSet = null;
	Product product = null;
	try {
		Object params[] = new Object[] { id };
		resultSet = this.executeQuery(sql, params);
		while (resultSet.next()) {
			product = tableToClass(resultSet);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		this.closeResource(resultSet);
		this.closeResource();
		return product;
	}
}

@Override
public List<Product> queryProductList(ProductParam params) throws Exception {
	List<Object> paramsList=new ArrayList<Object>();   
	List<Product> productList=new ArrayList<Product>();
	StringBuffer sql=new StringBuffer("select id,name,description,price,stock,categoryLevel1Id,categoryLevel2Id,categoryLevel3Id,fileName,isDelete,salenumber from skeyedu_product  where 1=1 ");
	ResultSet resultSet = null;
	try {
		if(EmptyUtils.isNotEmpty(params.getName())){
			sql.append(" and name = ? ");
			paramsList.add(params.getName());
		}
		if(EmptyUtils.isNotEmpty(params.getKeyword())){
			sql.append(" and name like ? ");
			paramsList.add("%"+params.getKeyword()+"%");
		}
		
		if(EmptyUtils.isNotEmpty(params.getCategoryId())){
			sql.append(" and (categoryLevel1Id = ? or categoryLevel2Id=? or categoryLevel3Id=? )");
			paramsList.add(params.getCategoryId());
			paramsList.add(params.getCategoryId());
			paramsList.add(params.getCategoryId());
		}
		
		if(EmptyUtils.isNotEmpty(params.getSort())){
			sql.append(" order by " + params.getSort()+" ");
		}
		
		if(params.isPage()){
			sql.append(" limit  " + params.getStartIndex() + "," + params.getPageSize());
		}
		resultSet=this.executeQuery(sql.toString(),paramsList.toArray());
		while (resultSet.next()) {
			Product product = this.tableToClass(resultSet);
			productList.add(product);
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource(resultSet);
		this.closeResource();
	}
			
	return productList;
}


@Override
public Integer queryProductCount(ProductParam params) throws Exception {
	List<Object> paramsList=new ArrayList<Object>();   
	Integer count=0;
	StringBuffer sql=new StringBuffer("select count(*) count from skeyedu_product where 1=1 ");
	if(EmptyUtils.isNotEmpty(params.getName())){
		sql.append(" and name = ? ");
		paramsList.add(params.getName());
	}
	if(EmptyUtils.isNotEmpty(params.getKeyword())){
		sql.append(" and name like ? ");
		paramsList.add("%"+params.getKeyword()+"%");
	}
	ResultSet resultSet = this.executeQuery(sql.toString(),paramsList.toArray());
	try {
		while (resultSet.next()) {
			count=resultSet.getInt("count");
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource(resultSet);
		this.closeResource();
	}
	return count;
}

}

///
package com.skeyedu.mall.dao.product;

import java.util.List;

import com.skeyedu.mall.dao.IBaseDao;
import com.skeyedu.mall.entity.ProductCategory;
import com.skeyedu.mall.param.ProductCategoryParam;

public interface ProductCategoryDao extends IBaseDao{
void deleteById(Integer parseLong);//删除商品分类
public List queryProductCategorylist(ProductCategoryParam param); //查询商品分类列表 分页
public List queryAllProductCategorylist(ProductCategoryParam param); //查询商品分类列表 分页
public ProductCategory queryProductCategoryById(Integer id);
public Integer save(ProductCategory productCategory) ;
public Integer queryProductCategoryCount(ProductCategoryParam param);
public void update(ProductCategory productCategory);
}
////
package com.skeyedu.mall.dao.product;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.skeyedu.mall.dao.BaseDaoImpl;
import com.skeyedu.mall.entity.ProductCategory;
import com.skeyedu.mall.param.ProductCategoryParam;
import com.skeyedu.mall.utils.EmptyUtils;

public class ProductCategoryDaoImpl extends BaseDaoImpl implements ProductCategoryDao{

public ProductCategoryDaoImpl(Connection connection) {
	super(connection);
	// TODO Auto-generated constructor stub
}


@Override
public ProductCategory tableToClass(ResultSet rs) throws Exception {
	ProductCategory productCategory = new ProductCategory();
	productCategory.setId(rs.getInt("id"));
	productCategory.setName(rs.getString("name"));
	productCategory.setParentId(rs.getInt("parentId"));
	productCategory.setType(rs.getInt("type"));
	productCategory.setIconClass(rs.getString("iconClass"));
	return productCategory;
}

public ProductCategory mapToClass(Map map) throws Exception {
	ProductCategory productCategory = new ProductCategory();
	Object idObject=map.get("id");
	Object nameObject=map.get("name");
	Object parentIdObject=map.get("parentId");
	Object typeObject=map.get("type");
	Object iconClassObject=map.get("iconClass");
	Object parentNameObject=map.get("parentName");
	productCategory.setId(EmptyUtils.isEmpty(idObject)?null:(Integer)idObject);
	productCategory.setName(EmptyUtils.isEmpty(nameObject)?null:(String)nameObject);
	productCategory.setParentId(EmptyUtils.isEmpty(parentIdObject)?null:(Integer)parentIdObject);
	productCategory.setType(EmptyUtils.isEmpty(typeObject)?null:(Integer)typeObject);
	productCategory.setIconClass(EmptyUtils.isEmpty(iconClassObject)?null:(String)iconClassObject);
	productCategory.setParentName(EmptyUtils.isEmpty(parentNameObject)?null:(String)parentNameObject);
	return productCategory;
}

public List<ProductCategory> queryAllProductCategorylist(ProductCategoryParam params){
	List<ProductCategory> list=new ArrayList<ProductCategory>();
	List<Object> paramsList=new ArrayList<Object>();
	StringBuffer sqlBuffer=new StringBuffer("SELECT epc1.*,epc2.name as parentName FROM skeyedu_product_category epc1 LEFT JOIN skeyedu_product_category epc2 ON epc1.parentId=epc2.id where 1=1 ");
	ResultSet resultSet=null;
	try{
		if(EmptyUtils.isNotEmpty(params.getName())){
			sqlBuffer.append(" and name like ? ");
			paramsList.add("%"+params.getName()+"%");
		}
		if(EmptyUtils.isNotEmpty(params.getParentId())){
			sqlBuffer.append(" and parentId = ? ");
			paramsList.add(params.getParentId());
		}
		if(EmptyUtils.isNotEmpty(params.getSort())){
			sqlBuffer.append(" order by " + params.getSort()+" ");
		}
		if(params.isPage()){
			sqlBuffer.append(" limit  " + params.getStartIndex() + "," + params.getPageSize());
		}
		resultSet=this.executeQuery(sqlBuffer.toString(),paramsList.toArray());
		ResultSetMetaData md=resultSet.getMetaData();
		Map<String,Object> rowData=new HashMap<String,Object>();
		int count=md.getColumnCount();
		for(int i=1;i<=count;i++){
			rowData.put(md.getColumnLabel(i),resultSet.getObject(i));
		}
		list.add(mapToClass(rowData));
	}catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource();
		this.closeResource(resultSet);
	}

	
	return list;
}

@Override
public void deleteById(Integer id){
	String sql = "delete from skeyedu_product_category where id = ? ";
	Object params[] = new Object[] { id };
	this.executeUpdate(sql.toString(), params);	
}

@Override
public List<ProductCategory> queryProductCategorylist(ProductCategoryParam params) {
	List<Object> paramsList=new ArrayList<Object>();   
	List<ProductCategory> productList=new ArrayList<ProductCategory>();
	StringBuffer sql=new StringBuffer("SELECT id,name,parentId,type,iconClass  FROM skeyedu_product_category where 1=1 ");
	ResultSet resultSet=null;
	try {
		if(EmptyUtils.isNotEmpty(params.getName())){
			sql.append(" and name like ? ");
			paramsList.add("%"+params.getName()+"%");
		}
		if(EmptyUtils.isNotEmpty(params.getParentId())){
			sql.append(" and parentId = ? ");
			paramsList.add(params.getParentId());
		}
		if(EmptyUtils.isNotEmpty(params.getType())){
			sql.append(" and type = ? ");
			paramsList.add(params.getType());
		}
		if(params.isPage()){
			sql.append(" limit  " + params.getStartIndex() + "," + params.getPageSize());
		}
		resultSet=this.executeQuery(sql.toString(), paramsList.toArray());
		while (resultSet.next()) {
			ProductCategory productCategory = this.tableToClass(resultSet);
			productList.add(productCategory);
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource();
		this.closeResource(resultSet);
	}
	return productList;
}

public Integer queryProductCategoryCount(ProductCategoryParam params){
	List<Object> paramsList=new ArrayList<Object>();   
	Integer count=0;
	StringBuffer sql=new StringBuffer("SELECT count(*) count FROM skeyedu_product_category where 1=1 ");
	if(EmptyUtils.isNotEmpty(params.getName())){
		sql.append(" and name like ? ");
		paramsList.add("%"+params.getName()+"%");
	}
	if(EmptyUtils.isNotEmpty(params.getParentId())){
		sql.append(" and parentId = ? ");
		paramsList.add(params.getParentId());
	}
	ResultSet resultSet=this.executeQuery(sql.toString(), paramsList.toArray());
	try {
		while (resultSet.next()) {
			count=resultSet.getInt("count");
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource();
		this.closeResource(resultSet);
	}
	return count;
}

public ProductCategory queryProductCategoryById(Integer id){
	List<Object> paramsList=new ArrayList<Object>();   
	ProductCategory productCategory=null;
	StringBuffer sql=new StringBuffer("SELECT id,name,parentId,type,iconClass  FROM skeyedu_product_category where id = ? ");
	ResultSet resultSet=this.executeQuery(sql.toString(),new Object[]{id});
	try {
		while (resultSet.next()) {
			productCategory = this.tableToClass(resultSet);
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} catch (Exception e) {
		e.printStackTrace();
	}finally{
		this.closeResource();
		this.closeResource(resultSet);
	}
	return productCategory;
}

public Integer save(ProductCategory productCategory)  {//新增用户信息
	Integer id=0;
	try {
		String sql="INSERT into skeyedu_product_category(name,parentId,type,iconClass) values(?,?,?,?) ";
        Object param[]=new Object[]{productCategory.getName(),productCategory.getParentId(),productCategory.getType(),productCategory.getIconClass()};
        id=this.executeInsert(sql,param);
        productCategory.setId(id);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
    	this.closeResource();
    }
	return id;
}

@Override
public void update(ProductCategory productCategory) {
	try {
    	Object[] params = new Object[] {productCategory.getName(),productCategory.getParentId(),productCategory.getType(),productCategory.getIconClass(),productCategory.getId()};
    	String sql = "UPDATE skeyedu_product_category SET name=?,parentId=?,type=?,iconClass=? WHERE id =?  ";
		this.executeUpdate(sql, params);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
    	this.closeResource();
    }		
}

}
/////
package com.skeyedu.mall.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import org.apache.log4j.Logger;

public abstract class BaseDaoImpl {
protected Connection connection;

protected PreparedStatement pstm;

static Logger logger=Logger.getLogger(BaseDaoImpl.class);
		
public BaseDaoImpl(Connection connection) {
	this.connection = connection;
}
//这里面传入的sql  都是带有???
public ResultSet executeQuery(String sql,Object[] params){
	ResultSet rs=null;
	try {
		pstm = connection.prepareStatement(sql);
		for(int i = 0; i < params.length; i++){
			pstm.setObject(i+1, params[i]);
		}
		rs = pstm.executeQuery();
	} catch (Exception e) {
		e.printStackTrace();
	}
	
	return rs;
}

//增删改操作 delete from news_detail where id=? and title=?
public int executeUpdate(String sql,Object[] params){
	int updateRows = 0;
	try {
		pstm = connection.prepareStatement(sql);
		for(int i = 0; i < params.length; i++){
			pstm.setObject(i+1, params[i]);
		}
		updateRows = pstm.executeUpdate();
	} catch (Exception e) {
		e.printStackTrace();
		updateRows = -1;
	}
	
	return updateRows;
}

public int executeInsert(String sql,Object[] params){
	Long id = 0L;
	try {
		pstm = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
		for(int i = 0; i < params.length; i++){
			pstm.setObject(i+1, params[i]);
		}
		pstm.executeUpdate();
		ResultSet rs = pstm.getGeneratedKeys(); 
		if (rs.next()) { 
			id = rs.getLong(1);
		} 
		
	} catch (Exception e) {
		e.printStackTrace();
		id =null;
	}	
	return id.intValue();
}


//释放资源
public boolean closeResource(){
	if(pstm != null){
		try {
			pstm.close();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}
	return true;
}

public boolean closeResource(ResultSet reSet){
	if(reSet != null){
		try {
			reSet.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}
	return true;
}

/**
 * 需要重写的方法
 *
 * @param rs
 * @return
 * @throws Exception
 */
public abstract Object tableToClass(ResultSet rs) throws Exception;

}

//////
(2)、entity层:
//product
package com.skeyedu.mall.entity;

import java.io.Serializable;

public class Product implements Serializable{
private Integer id;//ID
private String name;//商品名
private String description;//描述
private Float price;//单价
private Integer stock;//数量
private Integer categoryLevel1Id;//一级分类
private Integer categoryLevel2Id;//二级分类
private Integer categoryLevel3Id;//三级分类
private String fileName;//图片名称
private int salenumber;

public int getSalenumber() {
	return salenumber;
}

public void setSalenumber(int salenumber) {
	this.salenumber = salenumber;
}

public Integer getId() {
	return id;
}

public void setId(Integer id) {
	this.id = id;
}

public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public String getDescription() {
	return description;
}

public void setDescription(String description) {
	this.description = description;
}

public Float getPrice() {
	return price;
}

public void setPrice(Float price) {
	this.price = price;
}



public Integer getStock() {
	return stock;
}

public void setStock(Integer stock) {
	this.stock = stock;
}

public Integer getCategoryLevel1Id() {
	return categoryLevel1Id;
}

public void setCategoryLevel1Id(Integer categoryLevel1Id) {
	this.categoryLevel1Id = categoryLevel1Id;
}

public Integer getCategoryLevel2Id() {
	return categoryLevel2Id;
}

public void setCategoryLevel2Id(Integer categoryLevel2Id) {
	this.categoryLevel2Id = categoryLevel2Id;
}

public Integer getCategoryLevel3Id() {
	return categoryLevel3Id;
}

public void setCategoryLevel3Id(Integer categoryLevel3Id) {
	this.categoryLevel3Id = categoryLevel3Id;
}

public String getFileName() {
	return fileName;
}

public void setFileName(String fileName) {
	this.fileName = fileName;
}

}
///
package com.skeyedu.mall.entity;
import java.io.Serializable;
public class ProductCategory implements Serializable{

private Integer id;//ID
private String name;//名称
private Integer parentId;//父级ID
private Integer type;//级别(1:一级 2:二级 3:三级)
private String iconClass;//图标
private String parentName; //父级名称

public String getIconClass() {
	return iconClass;
}

public void setIconClass(String iconClass) {
	this.iconClass = iconClass;
}

public Integer getType() {
	return type;
}

public void setType(Integer type) {
	this.type = type;
}


public String getName() {
	return name;
}

public void setName(String name) {
	this.name = name;
}

public Integer getId() {
	return id;
}

public void setId(Integer id) {
	this.id = id;
}

public Integer getParentId() {
	return parentId;
}

public void setParentId(Integer parentId) {
	this.parentId = parentId;
}

public String getParentName() {
	return parentName;
}

public void setParentName(String parentName) {
	this.parentName = parentName;
}

}
////
package com.skeyedu.mall.entity;

import java.io.Serializable;
import java.util.Date;

public class User implements Serializable{

private Integer id;
private String loginName;//ID
private String userName;//用户名
private String password;//密码
private Integer sex;//性别
private String identityCode;
private String email;//电子邮箱
private String mobile;//电话
private Integer type;//类型(1:后台 0:前台)
public Integer getId() {
	return id;
}
public void setId(Integer id) {
	this.id = id;
}
public String getLoginName() {
	return loginName;
}
public void setLoginName(String loginName) {
	this.loginName = loginName;
}
public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getPassword() {
	return password;
}
public void setPassword(String password) {
	this.password = password;
}
public Integer getSex() {
	return sex;
}
public void setSex(Integer sex) {
	this.sex = sex;
}
public String getIdentityCode() {
	return identityCode;
}
public void setIdentityCode(String identityCode) {
	this.identityCode = identityCode;
}
public String getEmail() {
	return email;
}
public void setEmail(String email) {
	this.email = email;
}
public String getMobile() {
	return mobile;
}
public void setMobile(String mobile) {
	this.mobile = mobile;
}
public Integer getType() {
	return type;
}
public void setType(Integer type) {
	this.type = type;
}

}
////
package com.skeyedu.mall.entity;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

public class Order implements Serializable {

private Integer id;//ID
private String serialNumber;//订单号
private Integer userId;//登录id
private String userAddress;//收货地址
private Date createTime;//创建时间
private Float cost;//订单总计价格

private String loginName;//登录名
private List<OrderDetail> orderDetailList;  //订单详情 OrderDetail泛型List集合

public List<OrderDetail> getOrderDetailList() {
	return orderDetailList;
}

public void setOrderDetailList(List<OrderDetail> orderDetailList) {
	this.orderDetailList = orderDetailList;
}

public int getId() {
	return id;
}

public void setId(int id) {
	this.id = id;
}


public String getLoginName() {
	return loginName;
}

public void setLoginName(String loginName) {
	this.loginName = loginName;
}

public Date getCreateTime() {
	return createTime;
}

public void setCreateTime(Date createTime) {
	this.createTime = createTime;
}

public Float getCost() {
	return cost;
}

public void setCost(Float cost) {
	this.cost = cost;
}

public Integer getUserId() {
	return userId;
}

public void setUserId(Integer userId) {
	this.userId = userId;
}

public void setId(Integer id) {
	this.id = id;
}

public String getUserAddress() {
	return userAddress;
}

public void setUserAddress(String userAddress) {
	this.userAddress = userAddress;
}

public String getSerialNumber() {
	return serialNumber;
}

public void setSerialNumber(String serialNumber) {
	this.serialNumber = serialNumber;
}

}
////
package com.skeyedu.mall.entity;

import java.io.Serializable;

public class OrderDetail implements Serializable{
private Integer id;//ID
private Integer orderId;//订单ID
private Integer quantity;//数量
private Float cost;//单价
private Integer productId;

private Product product;//商品
public Integer getProductId() {
	return productId;
}

public void setProductId(Integer productId) {
	this.productId = productId;
}

public Integer getId() {
	return id;
}

public void setId(Integer id) {
	this.id = id;
}


public Integer getOrderId() {
	return orderId;
}

public void setOrderId(Integer orderId) {
	this.orderId = orderId;
}

public Product getProduct() {
	return product;
}

public void setProduct(Product product) {
	this.product = product;
}


public Integer getQuantity() {
	return quantity;
}

public void setQuantity(Integer quantity) {
	this.quantity = quantity;
}

public Float getCost() {
	return cost;
}

public void setCost(Float cost) {
	this.cost = cost;
}

}
////
package com.skeyedu.mall.entity;
import java.io.Serializable;
import java.util.Date;

/**
*

  • @ClassName UserAddress

  • @Description TODO(用户地址实体类)

  • @author Mr.Yan

  • @Email 10947@163.com

  • @Date 2019年5月8日 下午6:14:30

  • @version 1.0.0
    */
    public class UserAddress implements Serializable {

    private Integer id;

    private String address; //地址

    private Integer userId; //用户ID

    private Date createTime;//创建时间

    private String remark; //备注

    private Integer isDefault; //是否是默认地址(1:是 0否)

    public Integer getIsDefault() {
    return isDefault;
    }

    public void setIsDefault(Integer isDefault) {
    this.isDefault = isDefault;
    }

    public String getRemark() {
    return remark;
    }

    public void setRemark(String remark) {
    this.remark = remark;
    }

    public Integer getId() {
    return id;
    }

    public void setId(Integer id) {
    this.id = id;
    }

    public String getAddress() {
    return address;
    }

    public void setAddress(String address) {
    this.address = address;
    }

    public Date getCreateTime() {
    return createTime;
    }

    public void setCreateTime(Date createTime) {
    this.createTime = createTime;
    }

    public Integer getUserId() {
    return userId;
    }

    public void setUserId(Integer userId) {
    this.userId = userId;
    }

}
///
(3)service层
///
package com.skeyedu.mall.service.order;

import com.skeyedu.mall.utils.ShoppingCart;

/**

  • Created by bdqn on 2016/5/11.
    */
    public interface CartService {

    public ShoppingCart modifyShoppingCart(String productId,String quantityStr,ShoppingCart cart) throws Exception;

    public ShoppingCart calculate(ShoppingCart cart)throws Exception;
    }

////
package com.skeyedu.mall.service.order;

import java.sql.Connection;

import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.ShoppingCart;
import com.skeyedu.mall.utils.ShoppingCartItem;

/**

  • Created by bdqn on 2016/5/11.
    */
    public class CartServiceImpl implements CartService {
    @Override
    public ShoppingCart modifyShoppingCart(String productId, String quantityStr, ShoppingCart cart) throws Exception {
    Integer quantity = 0;
    if (!EmptyUtils.isEmpty(quantityStr))
    quantity = Integer.parseInt(quantityStr);
    //便利购物车寻找该商品 修改其数量
    for (ShoppingCartItem item : cart.getItems()) {
    if (item.getProduct().getId().toString().equals(productId)) {
    if (quantity == 0 || quantity < 0) {
    cart.getItems().remove(item);
    break;
    } else {
    item.setQuantity(quantity);
    }
    }
    }
    //重新计算金额
    calculate(cart);
    return cart;
    }

    /**

    • 核算购物车的金额
    • @param cart
    • @return
    • @throws Exception
      */
      @Override
      public ShoppingCart calculate(ShoppingCart cart) throws Exception {
      double sum = 0.0;
      for (ShoppingCartItem item : cart.getItems()) {
      sum = sum + item.getQuantity() * item.getProduct().getPrice();
      item.setCost(item.getQuantity() * item.getProduct().getPrice());
      }
      cart.setSum(sum);
      return cart;
      }
      }
      /////
      package com.skeyedu.mall.service.product;

import java.util.List;

import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.param.ProductParam;
import com.skeyedu.mall.utils.Pager;

public interface ProductService {
/**
* 根据分类查询商品列表
* @param categoryId
* @param level
* @param pager
* @return
/
public List getProductsByCategory(Integer categoryId, int level, Pager pager,String keyWord);
/
*
* 根据分类查询商品数目
* @param categoryId
* @param level
* @return
/
int getProductRowCount(String categoryId,int level,String keyWord);
/
*
* 根据id查询商品
* @param id
* @return
/
Product findById(String id);//根据ID查询商品
/
*
* 保存商品返回id
* @param product
* @return
/
Integer saveOrUpdate(Product product);//保存一款商品
/
*
* 查询商品数目
* @param params
* @return
/
public int getProductRowCount(ProductParam params);
/
*
* 查询商品列表
* @param params
* @return
/
List queryProductsList(ProductParam params);
/
*
* 根据id删除商品
* @param id
/
public void deleteById(Integer id);
/
*
* 根据分类id查询数目
* @param categoryId
* @return
*/
public int getProductCountBycategory(Integer categoryId);

}
///
package com.skeyedu.mall.service.product;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import com.skeyedu.mall.dao.product.ProductCategoryDao;
import com.skeyedu.mall.dao.product.ProductCategoryDaoImpl;
import com.skeyedu.mall.entity.ProductCategory;
import com.skeyedu.mall.param.ProductCategoryParam;
import com.skeyedu.mall.utils.DataSourceUtil;
import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.ProductCategoryVo;

public class ProductCategoryServiceImpl implements ProductCategoryService{
/**
*
* @param id
* @return
*/
@Override
public ProductCategory getById(Integer id) {
Connection connection = null;
ProductCategory productCategory = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
productCategory =productCategoryDao.queryProductCategoryById(id);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
return productCategory;
}

@Override
public List queryProductCategoryList(ProductCategoryParam params) {
Connection connection = null;
List rtn = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
rtn = productCategoryDao.queryProductCategorylist(params);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
return rtn;
}

public List queryProductCategorylistBySql(ProductCategoryParam params) {
Connection connection = null;
List rtn = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
rtn = productCategoryDao.queryProductCategorylist(params);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
return rtn;
}

@Override
public int queryProductCategoryCount(ProductCategoryParam params) {
Connection connection = null;
int rtn = 0;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
rtn = productCategoryDao.queryProductCategoryCount(params);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
return rtn;
}

@Override
public void modifyProductCategory(ProductCategory productCategory) {
Connection connection = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
productCategoryDao.update(productCategory);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
}
/**
* 新增商品分类
* @param params
/
@Override
public void addProductCategory(ProductCategory productCategory) {
Connection connection = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
productCategoryDao.save(productCategory);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
}
/
*
* 根据Id删除商品
* @param id
/
@Override
public void deleteById(Integer id) {
Connection connection = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
productCategoryDao.deleteById(id);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
}
}
/
*
* 查询全部的商品分类
* @return
/
@Override
public List queryAllProductCategoryList() {
//查询一级分类的列表
List productCategory1VoList = new ArrayList();
//查询一级分类
List productCategory1List = getProductCategories(null); //根据父ID查询所有子商品分类
//查询二级分类
for (ProductCategory product1Category : productCategory1List) {
//封装一级分类
ProductCategoryVo productCategoryVo = new ProductCategoryVo();
productCategoryVo.setProductCategory(product1Category);
List productCategoryVo1ChildList = new ArrayList();
//根据一级分类查询二级分类
List productCategory2List = getProductCategories(product1Category.getId());
for (ProductCategory productCategory2 : productCategory2List) {
ProductCategoryVo productCategoryVo2 = new ProductCategoryVo();
productCategoryVo1ChildList.add(productCategoryVo2);
productCategoryVo2.setProductCategory(productCategory2);
List productCategoryVo2ChildList = new ArrayList();
productCategoryVo2.setProductCategoryVoList(productCategoryVo2ChildList);
//根据二级分类查询三级分类的列表
List productCategory3List = getProductCategories(productCategory2.getId());
for (ProductCategory productCategory3 : productCategory3List) {
ProductCategoryVo productCategoryVo3 = new ProductCategoryVo();
productCategoryVo3.setProductCategory(productCategory3);
productCategoryVo2ChildList.add(productCategoryVo3);
}
}
productCategoryVo.setProductCategoryVoList(productCategoryVo1ChildList);
productCategory1VoList.add(productCategoryVo);
}
return productCategory1VoList;
}
/
*
* 查询子分类
* @param parentId
* @return
*/
private List getProductCategories(Integer parentId) {//根据父ID查询所有子商品分类
Connection connection = null;
List productCategoryList = null;
try {
connection = DataSourceUtil.openConnection();
ProductCategoryDao productCategoryDao = new ProductCategoryDaoImpl(connection);
ProductCategoryParam params = new ProductCategoryParam();
if (EmptyUtils.isNotEmpty(parentId)) {
params.setParentId(parentId);
} else {
params.setParentId(0);
}
productCategoryList = productCategoryDao.queryProductCategorylist(params);
} catch (Exception e) {
e.printStackTrace();
} finally {
DataSourceUtil.closeConnection(connection);
return productCategoryList;
}
}

}
///
package com.skeyedu.mall.service.user;

import java.util.List;

import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.param.UserParam;

public interface UserService {
public void update(User user);//更新用户信息
public User findByLoginName(String loginName); //根据ID查询用户信息
public boolean save(User user); //新增用户
void delete(String id);//根据用户名删除用户
public List queryUserList(UserParam userParam);
public int queryUserCount(UserParam params);
public User queryUserById(Integer userId);
}
////
package com.skeyedu.mall.service.user;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.skeyedu.mall.dao.user.UserDao;
import com.skeyedu.mall.dao.user.UserDaoImpl;
import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.param.UserParam;
import com.skeyedu.mall.utils.DataSourceUtil;

public class UserServiceImpl implements UserService{

@Override 
public void update(User user) {   //更新用户信息
	// TODO Auto-generated method stub
	Connection connection = null;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		try {
			userDao.update(user);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
	}
}

@Override
public User findByLoginName(String loginName) {
	// TODO Auto-generated method stub
	Connection connection = null;
	User user = null;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		try {
			user = userDao.findByLoginName(loginName);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
	}
	return user;
}

@Override
public boolean save(User user) {  //新增用户信息
	// TODO Auto-generated method stub
	boolean flag = false;
	Connection connection = null;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		int count = userDao.save(user);
		flag = count>0;
	} catch (SQLException e) {
		flag = false;
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
		return flag;
	}
}

@Override
public void delete(String id) {
	// TODO Auto-generated method stub
	Connection connection = null;
	List<User> userList = null;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		try {
			userDao.deleteById(id);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
	}
}

@Override
public List<User> queryUserList(UserParam userParam) {
	// TODO Auto-generated method stub
	Connection connection = null;
	List<User> userList = null;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		try {
			userList = userDao.queryUserList(userParam);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
	}
	return userList;
}

@Override
public int queryUserCount(UserParam params) {
	// TODO Auto-generated method stub
	Connection connection = null;
	int count = 0;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		try {
			count = userDao.queryUserCount(params);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
	}
	
	return count;
}

@Override
public User queryUserById(Integer userId) {
	// TODO Auto-generated method stub
	Connection connection = null;
	User user = null;
	try {
		connection = DataSourceUtil.openConnection();
		UserDao userDao = new UserDaoImpl(connection);
		try {
			user = (User)userDao.queryUserById(userId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		DataSourceUtil.closeConnection(connection);
	}
	return user;
}

}
////
(3)、Utils层:
////
package com.skeyedu.mall.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.util.Properties;

/**
*

  • @ClassName DataSourceUtil

  • @Description TODO(获取JDBC的Connection接口并连接、关闭连接的封装类)

  • @author Mr.Yan

  • @Email 10947@163.com

  • @Date 2019年5月8日 下午4:01:34

  • @version 1.0.0
    */
    public class DataSourceUtil {

    private static String driver;
    private static String url;
    private static String user;
    private static String password;

    static {
    init();
    }

    public static void init(){
    Properties params=new Properties();
    String configFile = "database.properties";
    InputStream is=DataSourceUtil.class.getClassLoader().getResourceAsStream(configFile);
    try {
    params.load(is);
    } catch (IOException e) {
    e.printStackTrace();
    }
    driver=params.getProperty("driver");
    url=params.getProperty("url");
    user=params.getProperty("username");
    password=params.getProperty("password");
    }

    //获取连接
    public static Connection openConnection() throws SQLException {
    Connection connection = null;
    try {
    Class.forName(driver);
    connection = DriverManager.getConnection(url, user, password);
    } catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }

     return connection;
    

    }
    //关闭连接
    public static void closeConnection(Connection connection) {
    try {
    if (connection != null)
    connection.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }

}
/////
package com.skeyedu.mall.utils;
import java.util.Collection;
import java.util.Map;

/**
*

  • @ClassName EmptyUtils

  • @Description TODO(判断是否是空的 工具类)

  • @author Mr.Yan

  • @Email 10947@163.com

  • @Date 2019年5月8日 下午2:25:28

  • @version 1.0.0
    */
    public class EmptyUtils {
    //判空
    public static boolean isEmpty(Object obj){
    if (obj == null)
    return true;
    if (obj instanceof CharSequence)
    return ((CharSequence) obj).length() == 0;
    if (obj instanceof Collection)
    return ((Collection) obj).isEmpty();
    if (obj instanceof Map)
    return ((Map) obj).isEmpty();
    if (obj instanceof Object[]) {
    Object[] object = (Object[]) obj;
    if (object.length == 0) {
    return true;
    }
    boolean empty = true;
    for (int i = 0; i < object.length; i++) {
    if (!isEmpty(object[i])) {
    empty = false;
    break;
    }
    }
    return empty;
    }
    return false;
    }

    /**
    *

    • author: Mr.Yan
    • Qq: 7631990
    • @Description (判断不为空)
    • @param obj
    • @return
      */
      public static boolean isNotEmpty(Object obj){
      return !isEmpty(obj);
      }

    /**
    *

    • author: Mr.Yan
    • Qq: 7631990
    • @Description (效验一个对象数组中的每个对象是否为空,如果有空返回true,没有返回false)
    • @param args
    • @return
      */
      private boolean validPropertyEmpty(Object ...args) {
      for (int i = 0; i < args.length; i++) {
      if(EmptyUtils.isEmpty(args[i])){
      return true;
      }
      }
      return false;
      }
      }
      ////
      package com.skeyedu.mall.utils;

import java.io.Serializable;
import java.util.List;

import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.entity.ProductCategory;

public class ProductCategoryVo implements Serializable {

private ProductCategory productCategory;
private List<ProductCategoryVo> productCategoryVoList;
private List<Product> productList;

public ProductCategory getProductCategory() {
    return productCategory;
}

public void setProductCategory(ProductCategory productCategory) {
    this.productCategory = productCategory;
}

public List<ProductCategoryVo> getProductCategoryVoList() {
    return productCategoryVoList;
}

public void setProductCategoryVoList(List<ProductCategoryVo> productCategoryVoList) {
    this.productCategoryVoList = productCategoryVoList;
}

public List<Product> getProductList() {
    return productList;
}

public void setProductList(List<Product> productList) {
    this.productList = productList;
}

}

///
package com.skeyedu.mall.utils;

import java.io.Serializable;
import java.util.List;

import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.entity.ProductCategory;

public class ProductCategoryVo implements Serializable {

private ProductCategory productCategory;
private List<ProductCategoryVo> productCategoryVoList;
private List<Product> productList;

public ProductCategory getProductCategory() {
    return productCategory;
}

public void setProductCategory(ProductCategory productCategory) {
    this.productCategory = productCategory;
}

public List<ProductCategoryVo> getProductCategoryVoList() {
    return productCategoryVoList;
}

public void setProductCategoryVoList(List<ProductCategoryVo> productCategoryVoList) {
    this.productCategoryVoList = productCategoryVoList;
}

public List<Product> getProductList() {
    return productList;
}

public void setProductList(List<Product> productList) {
    this.productList = productList;
}

}

////
package com.skeyedu.mall.utils;

import java.io.Serializable;

/**
*

  • @ClassName ReturnResult

  • @Description TODO(定义ajax返回结果类)

  • @author Mr.Yan

  • @Email 10947@163.com

  • @Date 2019年5月8日 下午2:00:15

  • @version 1.0.0
    */
    public class ReturnResult implements Serializable{

    private int status;
    private Object data;
    private String message="操作成功";

    public int getStatus() {
    return status;
    }

    public void setStatus(int status) {
    this.status = status;
    }

    public Object getData() {
    return data;
    }

    public void setData(Object data) {
    this.data = data;
    }

    public String getMessage() {
    return message;
    }

    public void setMessage(String message) {
    this.message = message;
    }
    /**

    • 返回成功状态
    • @param obj
      /
      public ReturnResult returnSuccess(Object obj){
      this.status=Constants.ReturnResult.SUCCESS;
      this.data=obj;
      return this;
      }
      /
      *
    • 返回默认成功状态
      /
      public ReturnResult returnSuccess(){
      this.status=Constants.ReturnResult.SUCCESS;
      return this;
      }
      /
      *
    • 返回失败状态
    • @param message
    • 成功:status=1,
    • 失败:status=0;
      */
      public ReturnResult returnFail(String message){
      this.status=Constants.ReturnResult.FAIL;
      this.message=message;
      return this;
      }

    public ReturnResult(String message, int status, Object data) {
    this.message = message;
    this.status = status;
    this.data = data;
    }

    public ReturnResult(Object data) {
    this.status=Constants.ReturnResult.SUCCESS;
    this.data = data;
    }

    public ReturnResult(){

    }
    }
    /////
    package com.skeyedu.mall.utils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import com.skeyedu.mall.entity.Product;

public class ShoppingCart implements Serializable{
public List items = new ArrayList();
private Double sum;

//获取购物车中所有商品
public List<ShoppingCartItem> getItems() {
	return items;
}	
//添加一项
public ReturnResult addItem(Product product, Integer quantity) {
	ReturnResult result=new ReturnResult();
	int flag=0;
	for(int i=0;i<items.size();i++){
		//判断购物车中是否已有此商品,如果有则累计数量
		if((items.get(i).getProduct().getId()).equals(product.getId())){
			if(items.get(i).getQuantity()+quantity>product.getStock()){
				return result.returnFail("商品数量不足");
			}else{
				items.get(i).setQuantity(items.get(i).getQuantity()+quantity);
				flag=1;
			}
		}
	}
	if(quantity>product.getStock()){
		return result.returnFail("商品数量不足");
	}
	if(flag==0){
		items.add(new ShoppingCartItem(product, quantity));
	}
	return result.returnSuccess();
}

//移除一项
public void removeItem(int index) {
	items.remove(index);
}

//修改数量
public void modifyQuantity(int index, Integer quantity) {
	items.get(index).setQuantity(quantity);
}

//计算总价格
public float getTotalCost() {
	float sum = 0;
	for (ShoppingCartItem item : items) {
		sum = sum + item.getCost();
	}
	return sum;
}

public void setItems(List<ShoppingCartItem> items) {
	this.items = items;
}

public Double getSum() {
	return sum;
}

public void setSum(Double sum) {
	this.sum = sum;
}

}
/////
package com.skeyedu.mall.utils;

import java.io.Serializable;

import com.skeyedu.mall.entity.Product;

public class ShoppingCartItem implements Serializable {
private Product product;// 商品
private Integer quantity;// 数量
private float cost;// 总价格

public ShoppingCartItem(Product product, Integer quantity) {
	this.product = product;
	this.quantity = quantity;
	this.cost = product.getPrice() * quantity;
}

public Integer getQuantity() {
	return quantity;
}

public void setQuantity(Integer quantity) {
	this.quantity = quantity;
	this.cost = product.getPrice() * quantity;
}

public Product getProduct() {
	return product;
}

public float getCost() {
	return cost;
}

public void setProduct(Product product) {
	this.product = product;
}

public void setCost(float cost) {
	this.cost = cost;
}

}
////
package com.skeyedu.mall.utils;

import org.apache.commons.codec.digest.DigestUtils;

public class SecurityUtils {
public static String md5Hex(String value) {
return DigestUtils.md5Hex(value);
}

    /**
     * 3次md5操作
     * @param value
     * @return
     */
    public static String md5Hex3(String value) {
    	for (int i = 0; i < 3; i++) {
    		value = DigestUtils.md5Hex(value);
    	}
    	return value;
    }
    
    
    /**
     * sha256加密
     *
     * @param value 要加密的值
     * @return sha256加密后的值
     */
    public static String sha256Hex(String value) {
        return DigestUtils.sha256Hex(value);
    }

    public static String sha512Hex(String value) {
        return DigestUtils.sha512Hex(value);
    }
    
    public static void main(String[] args) {
    	System.out.println(SecurityUtils.md5Hex("zhangsan"));
	}

}
////
(4)、param层
package com.skeyedu.mall.param;

import com.skeyedu.mall.entity.User;

public class UserParam extends User {
private Integer startIndex;
private Integer pageSize;
private Boolean isPage = false;
private String sort;
public Integer getStartIndex() {
return startIndex;
}
public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Boolean getIsPage() {
return isPage;
}
public void setIsPage(Boolean isPage) {
this.isPage = isPage;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}

public void openPage(Integer startIndex,Integer pageSize) {
	this.isPage = true;
	this.startIndex = startIndex;
	this.pageSize = pageSize;
}

}

/////
package com.skeyedu.mall.param;

import com.skeyedu.mall.entity.Product;

public class ProductParam extends Product{

private Integer startIndex;

private Integer pageSize;

private boolean isPage=false;

private String sort;

private String keyword;

private Integer categoryId;

public Integer getCategoryId() {
	return categoryId;
}

public void setCategoryId(Integer categoryId) {
	this.categoryId = categoryId;
}

public String getKeyword() {
	return keyword;
}

public void setKeyword(String keyword) {
	this.keyword = keyword;
}

public Integer getStartIndex() {
	return startIndex;
}

public void setStartIndex(Integer startIndex) {
	this.startIndex = startIndex;
}

public Integer getPageSize() {
	return pageSize;
}

public void setPageSize(Integer pageSize) {
	this.pageSize = pageSize;
}

public boolean isPage() {
	return isPage;
}

public void setPage(boolean isPage) {
	this.isPage = isPage;
}

public void openPage(Integer startIndex, Integer pageSize) {
	this.isPage = true;
	this.startIndex = startIndex;
	this.pageSize = pageSize;
}

public String getSort() {
	return sort;
}

public void setSort(String sort) {
	this.sort = sort;
}

}
////
package com.skeyedu.mall.param;

import com.skeyedu.mall.entity.ProductCategory;

public class ProductCategoryParam extends ProductCategory{
private Integer startIndex; //SQL LIMIT 起始位置 用于分页
private Integer pageSize; //SQL LIMIT 结束位置 用于分页
private boolean isPage=false; //默认不开启分页
private String sort; //排序

public Integer getStartIndex() {
	return startIndex;
}

public void setStartIndex(Integer startIndex) {
	this.startIndex = startIndex;
}

public Integer getPageSize() {
	return pageSize;
}

public void setPageSize(Integer pageSize) {
	this.pageSize = pageSize;
}

public boolean isPage() {
	return isPage;
}

public void setPage(boolean isPage) {
	this.isPage = isPage;
}

public void openPage(Integer startIndex, Integer pageSize) {
	this.isPage = true;
	this.startIndex = startIndex;
	this.pageSize = pageSize;
}

public String getSort() {
	return sort;
}

public void setSort(String sort) {
	this.sort = sort;
}

}
(5)、web, servlet层
/////
package com.skeyedu.mall.web.pre;

import java.sql.Connection;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.skeyedu.mall.dao.product.ProductDao;
import com.skeyedu.mall.dao.product.ProductDaoImpl;
import com.skeyedu.mall.entity.Order;
import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.entity.UserAddress;
import com.skeyedu.mall.service.order.CartService;
import com.skeyedu.mall.service.order.CartServiceImpl;
import com.skeyedu.mall.service.order.OrderService;
import com.skeyedu.mall.service.order.OrderServiceImpl;
import com.skeyedu.mall.service.product.ProductCategoryService;
import com.skeyedu.mall.service.product.ProductCategoryServiceImpl;
import com.skeyedu.mall.service.product.ProductService;
import com.skeyedu.mall.service.product.ProductServiceImpl;
import com.skeyedu.mall.service.user.UserAddressService;
import com.skeyedu.mall.service.user.UserAddressServiceImpl;
import com.skeyedu.mall.service.user.UserService;
import com.skeyedu.mall.service.user.UserServiceImpl;
import com.skeyedu.mall.utils.Constants;
import com.skeyedu.mall.utils.DataSourceUtil;
import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.ProductCategoryVo;
import com.skeyedu.mall.utils.ReturnResult;
import com.skeyedu.mall.utils.ShoppingCart;
import com.skeyedu.mall.utils.ShoppingCartItem;
import com.skeyedu.mall.web.AbstractServlet;

/**

  • Created by bdqn 2016/5/3.
    */
    @WebServlet(urlPatterns = { "/Cart" }, name = "Cart")
    public class CartServlet extends AbstractServlet {

    private ProductService productService;

    private OrderService orderService;

    private UserService userService;

    private ProductCategoryService productCategoryService;

    private CartService cartService;

    private UserAddressService userAddressService;

    public void init() throws ServletException {
    productService = new ProductServiceImpl();
    orderService = new OrderServiceImpl();
    userService = new UserServiceImpl();
    productCategoryService = new ProductCategoryServiceImpl();
    cartService = new CartServiceImpl();
    userAddressService = new UserAddressServiceImpl();
    }

    @Override
    public Class getServletClass() {
    return CartServlet.class;
    }

    /**

    • 添加到购物车
    • @return
      */
      public ReturnResult add(HttpServletRequest request, HttpServletResponse response) throws Exception {
      HttpSession session = request.getSession();
      ReturnResult result = new ReturnResult();
      String id = request.getParameter("entityId");
      String quantityStr = request.getParameter("quantity");
      Integer quantity = 1;
      if(session.getAttribute("loginUser")null){
      return result.returnFail("请先登录!");
      }
      else {if (!EmptyUtils.isEmpty(quantityStr))
      quantity = Integer.parseInt(quantityStr);
      //查询出商品
      Product product = productService.findById(id);
      if(product.getStock()<quantity){
      return result.returnFail("商品数量不足");
      }
      //获取购物车
      ShoppingCart cart = getCartFromSession(request);
      //往购物车放置商品
      result=cart.addItem(product, quantity);
      if(result.getStatus()
      Constants.ReturnResult.SUCCESS){
      cart.setSum((EmptyUtils.isEmpty(cart.getSum()) ? 0.0 : cart.getSum()) + (product.getPrice() * quantity * 1.0));
      }
      return result;
      }
      }

    /**

    • 刷新购物车
    • @param request
    • @param response
    • @return
      */
      public String refreshCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
      HttpSession session = request.getSession();
      ShoppingCart cart = getCartFromSession(request);
      cart = cartService.calculate(cart);
      session.setAttribute("cart", cart);//全部的商品
      return "/common/pre/searchBar";
      }

    /**

    • 跳到结算页面
    • @param request
    • @param response
    • @return
      */
      public String toSettlement(HttpServletRequest request, HttpServletResponse response) throws Exception {
      List productCategoryVoList = productCategoryService.queryAllProductCategoryList();
      //封装返回
      request.setAttribute("productCategoryVoList", productCategoryVoList);
      return "/pre/settlement/toSettlement";
      }

    public String settlement1(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ShoppingCart cart = getCartFromSession(request);
    cart = cartService.calculate(cart);
    request.getSession().setAttribute("cart", cart);
    return "/pre/settlement/settlement1";
    }

    /**

    • 跳转到购物车页面
    • @param request
    • @param response
    • @return
      */
      public String settlement2(HttpServletRequest request, HttpServletResponse response) throws Exception {
      User user = getUserFromSession(request);
      return "/pre/settlement/settlement2";
      }

    /**

    • 生成订单
    • @param request
    • @param response
    • @return
      */
      public Object settlement3(HttpServletRequest request, HttpServletResponse response) throws Exception {
      ShoppingCart cart = getCartFromSession(request);
      cart = cartService.calculate(cart);
      User user = getUserFromSession(request);
      ReturnResult result=checkCart(request);
      if(result.getStatus()==Constants.ReturnResult.FAIL){
      return result;
      }
      updateproduct(request,response);
      clearCart(request, response);
      return "/pre/settlement/settlement3";
      }

    /**

    • 清空购物车
    • @param request
    • @param response
      */
      public void updateproduct(HttpServletRequest request, HttpServletResponse response) throws Exception{
      ShoppingCart cart = getCartFromSession(request);
      cart = cartService.calculate(cart);
      Connection connection=DataSourceUtil.openConnection();
      ProductDao productDao=new ProductDaoImpl(connection);
      for (ShoppingCartItem item : cart.getItems()) {
      Product product=item.getProduct();
      int stock=product.getStock();
      int saleNumber=product.getSalenumber();
      int quantity=item.getQuantity();
      product.setStock( stock-quantity);
      product.setSalenumber(saleNumber+quantity);
      productDao.update(product);
      System.out.println("商品名称:"+product.getName()+"商品库存:"+product.getStock()+",商品销量:"+product.getSalenumber());
      }
      }

    public ReturnResult clearCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
    ReturnResult result = new ReturnResult();
    //结账后清空购物车
    request.getSession().removeAttribute("cart");
    result.returnSuccess(null);
    return result;
    }

    /**

    • 修改购物车信息
    • @param request
    • @return
      */
      public ReturnResult modCart(HttpServletRequest request, HttpServletResponse response) throws Exception {
      ReturnResult result = new ReturnResult();
      HttpSession session = request.getSession();
      String id = request.getParameter("entityId");
      String quantityStr = request.getParameter("quantity");
      ShoppingCart cart = getCartFromSession(request);
      Product product=productService.findById(id);
      if(EmptyUtils.isNotEmpty(quantityStr)){
      if(Integer.parseInt(quantityStr)>product.getStock()){
      return result.returnFail("商品数量不足");
      }
      }
      cart = cartService.modifyShoppingCart(id, quantityStr, cart);
      session.setAttribute("cart", cart);//全部的商品
      return result.returnSuccess();
      }

    /**

    • 从session中获取购物车
    • @param request
    • @return
      */
      private ShoppingCart getCartFromSession(HttpServletRequest request) throws Exception {
      HttpSession session = request.getSession();
      ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
      if (cart == null) {
      cart = new ShoppingCart();
      session.setAttribute("cart", cart);
      }
      return cart;
      }

    private ReturnResult checkCart(HttpServletRequest request) throws Exception {
    ReturnResult result = new ReturnResult();
    HttpSession session = request.getSession();
    ShoppingCart cart = getCartFromSession(request);
    cart = cartService.calculate(cart);
    for (ShoppingCartItem item : cart.getItems()) {
    Product product=productService.findById(item.getProduct().getId()+"");
    if(product.getStock()<item.getQuantity()){
    return result.returnFail(product.getName()+"商品数量不足");
    }
    }
    return result.returnSuccess();
    }

    /**

    • @param request
    • @return
      */
      private User getUserFromSession(HttpServletRequest request) {
      HttpSession session = request.getSession();
      User user = (User) session.getAttribute("loginUser");
      return user;
      }
      }
      ////
      package com.skeyedu.mall.web.pre;

import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.param.ProductParam;
import com.skeyedu.mall.service.product.ProductCategoryService;
import com.skeyedu.mall.service.product.ProductCategoryServiceImpl;
import com.skeyedu.mall.service.product.ProductService;
import com.skeyedu.mall.service.product.ProductServiceImpl;
import com.skeyedu.mall.utils.Pager;
import com.skeyedu.mall.utils.ProductCategoryVo;
import com.skeyedu.mall.web.AbstractServlet;

@WebServlet(urlPatterns = {"/Home"}, name = "Home")
public class HomeServlet extends AbstractServlet {

private ProductService productService;
private ProductCategoryService productCategoryService;

public void init() throws ServletException {
    productService = new ProductServiceImpl();
    productCategoryService = new ProductCategoryServiceImpl();
}

/**
 * 商城主页的方法
 * @param request
 * @param response
 * @return
 */
public String index(HttpServletRequest request, HttpServletResponse response)throws Exception {
    //查询商品分裂
    List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
    //查询一楼
    for (ProductCategoryVo vo : productCategoryVoList) {
    	ProductParam params = new ProductParam();
    	params.setCategoryId(vo.getProductCategory().getId());
    	params.openPage(0,7);
        List<Product> productList = productService.queryProductsList(params);
        vo.setProductList(productList);
    }
    //封装返回
    request.setAttribute("productCategoryVoList", productCategoryVoList);
    return "/pre/index";
}

@Override
public Class getServletClass() {
    return HomeServlet.class;
}

}

////
package com.skeyedu.mall.web.pre;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.service.user.UserService;
import com.skeyedu.mall.service.user.UserServiceImpl;
import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.ReturnResult;
import com.skeyedu.mall.utils.SecurityUtils;
import com.skeyedu.mall.web.AbstractServlet;
@WebServlet(urlPatterns = { "/Login" }, name = "Login")
public class LoginServlet extends AbstractServlet{
//注入用户业务类
private UserService userService;

public void init() throws ServletException {
    userService = new UserServiceImpl();
}
/**
 * 重写相关方法
 * @return
 */
@Override
public Class getServletClass() {
    return LoginServlet.class;
}
/**
 * 跳转到登陆界面
 * @param request
 * @param response
 * @return
 */
public String toLogin(HttpServletRequest request,HttpServletResponse response)throws Exception{
    return "/pre/login";
}
/**
 * 登陆的方法
 * @param request
 * @return
 */
public ReturnResult login(HttpServletRequest request,HttpServletResponse response)throws Exception{
    ReturnResult result=new ReturnResult();
    //参数获取
    String loginName=request.getParameter("loginName");
    String password=request.getParameter("password");
    User user=userService.findByLoginName(loginName);
    if(EmptyUtils.isEmpty(user)){
        result.returnFail("用户不存在");
    }else{
       if(user.getPassword().equals(SecurityUtils.md5Hex(password))){
           //登陆成功
           request.getSession().setAttribute("loginUser", user);
           result.returnSuccess("登陆成功");
       }else{
           result.returnFail("密码错误");
       }
    }
    return result;
}
/**
 * 登陆的方法
 * @param request
 * @return
 */
public String loginOut(HttpServletRequest request,HttpServletResponse response)throws Exception{
    ReturnResult result=new ReturnResult();
    try {
        User user=(User)request.getSession().getAttribute("loginUser");
        request.getSession().removeAttribute("loginUser");
        // 清除购物车
        request.getSession().removeAttribute("cart");
        request.getSession().removeAttribute("cart2");
    } catch (Exception e) {
        e.printStackTrace();
    }
    result.returnSuccess("注销成功");
    return "/pre/login";
}

}

///
package com.skeyedu.mall.web.pre;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.skeyedu.mall.entity.Product;
import com.skeyedu.mall.service.product.ProductCategoryService;
import com.skeyedu.mall.service.product.ProductCategoryServiceImpl;
import com.skeyedu.mall.service.product.ProductService;
import com.skeyedu.mall.service.product.ProductServiceImpl;
import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.Pager;
import com.skeyedu.mall.utils.ProductCategoryVo;
import com.skeyedu.mall.web.AbstractServlet;

@WebServlet(urlPatterns = {"/Product"}, name = "Product")
public class ProductServlet extends AbstractServlet {

private ProductService productService;
private ProductCategoryService productCategoryService;


public void init() throws ServletException {
    productService = new ProductServiceImpl();
    productCategoryService=new ProductCategoryServiceImpl();
}

/**
 * 查询商品列表
 *
 * @param request
 * @param response
 * @return
 */
public String queryProductList(HttpServletRequest request, HttpServletResponse response) throws Exception{
    String category = request.getParameter("category");
    String levelStr = request.getParameter("level");
    String currentPageStr = request.getParameter("currentPage");
    String keyWord = request.getParameter("keyWord");
    //获取页大小
    String pageSizeStr = request.getParameter("pageSize");
    int rowPerPage = EmptyUtils.isEmpty(pageSizeStr) ? 20:Integer.parseInt(pageSizeStr);
    int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
    int  level=EmptyUtils.isNotEmpty(levelStr)?Integer.parseInt(levelStr):0;
    int total = productService.getProductRowCount(category,level,keyWord);
    Pager pager = new Pager(total, rowPerPage, currentPage);
    pager.setUrl("/Product?action=queryProductList&level="+level+"&category="+(EmptyUtils.isEmpty(category)?"":category));
    List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
    List<Product> productList = productService.getProductsByCategory(EmptyUtils.isEmpty(category)?0:Integer.parseInt(category),level,pager,keyWord);
    request.setAttribute("productList", productList);
    request.setAttribute("pager", pager);
    request.setAttribute("total", total);
    request.setAttribute("keyWord", keyWord);
    request.setAttribute("productCategoryVoList", productCategoryVoList);
    return "/pre/product/queryProductList";
}
/**
 *
 * @param request
 * @param response
 * @return
 */
public String queryProductList1(HttpServletRequest request, HttpServletResponse response) throws Exception{
    String category = request.getParameter("category");
    String levelStr = request.getParameter("level");
    String currentPageStr = request.getParameter("currentPage");
    String keyWord = request.getParameter("keyWord");
    keyWord = new String(request.getParameter("keyWord").getBytes("iso8859-1"), "utf-8");
    //获取页大小
    String pageSizeStr = request.getParameter("pageSize");
    int rowPerPage = EmptyUtils.isEmpty(pageSizeStr) ? 20:Integer.parseInt(pageSizeStr);
    int currentPage = EmptyUtils.isEmpty(currentPageStr) ? 1 : Integer.parseInt(currentPageStr);
    int  level=EmptyUtils.isNotEmpty(levelStr)?Integer.parseInt(levelStr):0;
    int total = productService.getProductRowCount(category,level,keyWord);
    Pager pager = new Pager(total, rowPerPage, currentPage);
    pager.setUrl("/Product?action=queryProductList&level="+level+"&category="+(EmptyUtils.isEmpty(category)?"":category));
    List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
    List<Product> productList = productService.getProductsByCategory(EmptyUtils.isEmpty(category)?0:Integer.parseInt(category),level,pager,keyWord);
    request.setAttribute("productList", productList);
    request.setAttribute("pager", pager);
    request.setAttribute("total", total);
    request.setAttribute("keyWord", keyWord);
    request.setAttribute("productCategoryVoList", productCategoryVoList);
    return "/pre/product/queryProductList";
}

public String queryProductDeatil(HttpServletRequest request, HttpServletResponse response) throws Exception{
    String id = request.getParameter("id");
    Product product = productService.findById(id);
    List<ProductCategoryVo> productCategoryVoList = productCategoryService.queryAllProductCategoryList();
    request.setAttribute("product", product);
    request.setAttribute("productCategoryVoList", productCategoryVoList);
    addRecentProduct(request,product);
    return "/pre/product/productDeatil"; 
}
/**
 * 查询最近商品
 * @return
 */
private List<Product> queryRecentProducts(HttpServletRequest request)throws Exception{
    HttpSession session=request.getSession();
    List<Product> recentProducts= (List<Product>) session.getAttribute("recentProducts");
    if(EmptyUtils.isEmpty(recentProducts)){
        recentProducts=new ArrayList<Product>();
    }
    return recentProducts;
} 
/**
 * 添加最近浏览商品
 * @param request
 * @param product
 */
private void addRecentProduct(HttpServletRequest request,Product product)throws Exception{
    HttpSession session=request.getSession();
    List<Product> recentProducts=queryRecentProducts(request);
    //判断是否满了
    if(recentProducts.size()>0 &&  recentProducts.size()==10){
      recentProducts.remove(0);
    }
    recentProducts.add(recentProducts.size(),product);
    session.setAttribute("recentProducts",recentProducts);
}

@Override
public Class getServletClass() {
    return ProductServlet.class;
}

}
/////
package com.skeyedu.mall.web.pre;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skeyedu.mall.entity.User;
import com.skeyedu.mall.service.user.UserService;
import com.skeyedu.mall.service.user.UserServiceImpl;
import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.ReturnResult;
import com.skeyedu.mall.utils.SecurityUtils;
import com.skeyedu.mall.web.AbstractServlet;

@WebServlet(urlPatterns = { "/Register" }, name = "Register")
public class RegisterServlet extends AbstractServlet{

private UserService userService;
 public void init() throws ServletException {
        userService = new UserServiceImpl();
    }

public Class getServletClass() {
    return RegisterServlet.class;
}

public String toRegister(HttpServletRequest request,HttpServletResponse response)throws Exception{
    return "/pre/register";
}

public ReturnResult saveUserToDatabase(HttpServletRequest request,HttpServletResponse response)throws Exception{
    ReturnResult result=new ReturnResult();
    String loginName=request.getParameter("loginName");
    String password=request.getParameter("password");
    String password1=SecurityUtils.md5Hex(password);
    String userName=request.getParameter("userName");
    String sex=request.getParameter("sex");
    int sex1=Integer.valueOf(sex);
    String identityCode=request.getParameter("identityCode");
    String email=request.getParameter("email");
    String mobile=request.getParameter("mobile");
    User user=userService.findByLoginName(loginName);
    User user1=new User();
    if(EmptyUtils.isNotEmpty(user)){
        result.returnFail("用户已存在");
    }else{
    	user1.setLoginName(loginName);
        user1.setPassword(password1);
        user1.setUserName(userName);
        user1.setSex(sex1);
        user1.setIdentityCode(identityCode);
        user1.setEmail(email);
        user1.setMobile(mobile);
        result.returnSuccess("注册成功!");
    	userService.save(user1);
    }
    return result;
   
}

}
/////
package com.skeyedu.mall.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.skeyedu.mall.utils.EmptyUtils;
import com.skeyedu.mall.utils.PrintUtil;
import com.skeyedu.mall.utils.ReturnResult;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
*

  • @ClassName AbstractServlet

  • @Description TODO(公共的Servlet抽象类)

  • @author Mr.Yan

  • @Email 10947@163.com

  • @Date 2019年5月8日 上午10:43:24

  • @version 1.0.0
    */
    public abstract class AbstractServlet extends HttpServlet {

    /**
    *

    • author: Mr.Yan
    • Qq: 7631990
    • @Description (定义获取Servlet类的抽象方法)
    • @return
      */
      public abstract Class getServletClass();

    /**

    • 将所有GET请求由POST来处理
      */
      protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
      doPost(req, resp);
      }

    /**

    • 处理POST请求
      */
      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      String actionIndicator = req.getParameter("action");
      Method method = null;
      Object result = null;
      try {
      if (EmptyUtils.isEmpty(actionIndicator)) {
      result = execute(req, resp);
      } else {
      method = getServletClass().getDeclaredMethod(actionIndicator, HttpServletRequest.class, HttpServletResponse.class);
      result = method.invoke(this, req, resp);
      }
      toView(req, resp, result);
      } catch (NoSuchMethodException e) {
      String viewName = "404.jsp";
      req.getRequestDispatcher(viewName).forward(req, resp);
      } catch (Exception e) {
      e.printStackTrace();
      if (!EmptyUtils.isEmpty(result)) {
      if (result instanceof String) {
      String viewName = "500.jsp";
      req.getRequestDispatcher(viewName).forward(req, resp);
      } else {
      ReturnResult returnResult = new ReturnResult();
      returnResult.returnFail("系统错误");
      PrintUtil.write(returnResult, resp);
      }
      } else {
      String viewName = "500.jsp";
      req.getRequestDispatcher(viewName).forward(req, resp);
      }

      }
      }

    /**
    *

    • author: Mr.Yan
    • Qq: 7631990
    • @Description (显示页面或异步返回)
    • @param req
    • @param resp
    • @param result
    • @throws IOException
    • @throws ServletException
      */
      protected void toView(HttpServletRequest req, HttpServletResponse resp, Object result) throws IOException, ServletException {
      if (!EmptyUtils.isEmpty(result)) {
      if (result instanceof String) {
      String viewName = result.toString() + ".jsp";
      req.getRequestDispatcher(viewName).forward(req, resp);
      } else {
      PrintUtil.write(result, resp);
      }
      }
      }

    /**
    *

    • author: Mr.Yan
    • Qq: 7631990
    • @Description (默认返回)
    • @param req
    • @param resp
    • @return
      */
      public Object execute(HttpServletRequest req, HttpServletResponse resp) {
      return "pre/index";
      }
      }
posted @ 2019-06-03 11:20  一只皮π虾  阅读(1168)  评论(0编辑  收藏  举报