java web 網上零食商城後端代碼

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

import java.util.List;web

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

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<User> 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;sql

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

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{session

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;app

import java.util.List;異步

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

/**

  • 商品查詢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<Product> 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<ProductCategory> queryProductCategorylist(ProductCategoryParam param); //查詢商品分類列表 分頁 public List<ProductCategory> 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<Product> 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<Product> 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<ProductCategory> queryProductCategoryList(ProductCategoryParam params) { Connection connection = null; List<ProductCategory> 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<ProductCategory> queryProductCategorylistBySql(ProductCategoryParam params) { Connection connection = null; List<ProductCategory> 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<ProductCategoryVo> queryAllProductCategoryList() { //查詢一級分類的列表 List<ProductCategoryVo> productCategory1VoList = new ArrayList<ProductCategoryVo>(); //查詢一級分類 List<ProductCategory> productCategory1List = getProductCategories(null); //根據父ID查詢全部子商品分類 //查詢二級分類 for (ProductCategory product1Category : productCategory1List) { //封裝一級分類 ProductCategoryVo productCategoryVo = new ProductCategoryVo(); productCategoryVo.setProductCategory(product1Category); List<ProductCategoryVo> productCategoryVo1ChildList = new ArrayList<ProductCategoryVo>(); //根據一級分類查詢二級分類 List<ProductCategory> productCategory2List = getProductCategories(product1Category.getId()); for (ProductCategory productCategory2 : productCategory2List) { ProductCategoryVo productCategoryVo2 = new ProductCategoryVo(); productCategoryVo1ChildList.add(productCategoryVo2); productCategoryVo2.setProductCategory(productCategory2); List<ProductCategoryVo> productCategoryVo2ChildList = new ArrayList<ProductCategoryVo>(); productCategoryVo2.setProductCategoryVoList(productCategoryVo2ChildList); //根據二級分類查詢三級分類的列表 List<ProductCategory> 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<ProductCategory> getProductCategories(Integer parentId) {//根據父ID查詢全部子商品分類 Connection connection = null; List<ProductCategory> 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<User> 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<ShoppingCartItem> items = new ArrayList<ShoppingCartItem>(); 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<ProductCategoryVo> 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"; } }
相關文章
相關標籤/搜索