Initial commit

This commit is contained in:
2022-10-30 11:02:41 +08:00
commit a93cdd1a1e
190 changed files with 27813 additions and 0 deletions

15
src/c3p0-config.xml Normal file
View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://bj-cynosdbmysql-grp-68yeo4fq.sql.tencentcdb.com:29208/shopping?useSSL=true&amp;characterEncoding=UTF-8</property>
<property name="user">mysql</property>
<property name="password">MYSQLmysql123</property>
<property name="checkoutTimeout">30000</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</default-config>
</c3p0-config>

View File

@@ -0,0 +1,26 @@
package com.qf.controller;
import com.qf.service.CartService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.utils.Constants;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
@WebServlet("/address")
public class AddressController extends BaseServlet {
public String show(HttpServletRequest request, HttpServletResponse response){
//1.获取请求参数
//2.调用对应的业务逻辑 清空购物车
//3.转发到展示方法中
return Constants.FORWARD + "/cart?method=show";
}
}

View File

@@ -0,0 +1,73 @@
package com.qf.controller;
import com.qf.utils.Constants;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
public class BaseServlet extends HttpServlet {
//重写service方法来处理反射的业务逻辑
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
//1.获取请求参数(标识符)
String methodStr =req.getParameter(Constants.TAG);
//我们在这做一个处理。2.如果method没有获取到值我们就跳转到首页标识符异常处理
if (methodStr==null&& methodStr.equals("")){
methodStr= Constants.INDEX;
}
//3.反射调用对应的业务逻辑方法
Class clazz=this.getClass();
try {
Method method=clazz.getMethod(methodStr, HttpServletRequest.class, HttpServletResponse.class);
Object result= method.invoke(this,req,resp);
//4.集中处理返回值响应
if (result != null) {
//转发 重定向 返回字符串
String str=(String)result;
if (str.startsWith(Constants.FORWARD)){
//转发 截取
String path= str.substring(str.indexOf(Constants.FLAG)+1);
req.getRequestDispatcher(path).forward(req,resp);
}else if (str.startsWith(Constants.REDIRECT)){
//重定向
String path=str.substring(str.indexOf(Constants.FLAG)+1);
resp.sendRedirect(path);
}else{
//就是要返回一个字符串
resp.getWriter().println(str);
}
}
} catch (Exception e) {
e.printStackTrace();
//没有反射到方法
}
}
// /user?method=""
//返回到首页的方法
/**
* 当method标识符"没有值"或者是空字符串时我们默认赋index 访问每个Controller的index方法
* 我们将方法提取到BaseServlet中即可!
* 默认处理:跳转到程序的首页!
* @param req
* @param resp
* @return
* @throws
* @throws ServletException
*/
public String index (HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
return Constants.FORWARD+"/index.jsp";
}
}

View File

@@ -0,0 +1,114 @@
package com.qf.controller;
import com.qf.entity.Cart;
import com.qf.entity.User;
import com.qf.service.CartService;
import com.qf.service.impl.CartServiceImpl;
import com.qf.utils.Constants;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/cart")
public class CartController extends BaseServlet {
//加入购物车
public String create(HttpServletRequest request, HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException {
//1.判断用户是否登录,没有登录跳转到登录页面
HttpSession session = request.getSession();
//获取session中的用户信息
User user = (User) session.getAttribute("loginUser");
if (user == null) {
session.setAttribute("msg", "添加购物车必须先登录!");
return Constants.FORWARD + "/login.jsp";
}
//2.获取到对应的商品 id 和用户 id
int uid = user.getUid();
String pid = request.getParameter("pid");
//3.调用对应的业务逻辑
CartService cartService = new CartServiceImpl();
cartService.createCart(uid, pid);
//4.跳转到添加购物车成功页面
return Constants.FORWARD + "/cartSuccess.jsp";
}
//查看购物车
public String show(HttpServletRequest request, HttpServletResponse response) throws SQLException, InvocationTargetException, IllegalAccessException {
//1.判断用户是否登录
HttpSession session = request.getSession();
//获取session中的用户信息
User user = (User) session.getAttribute("loginUser");
if (user == null) {
session.setAttribute("msg", "查看购物车必须先登录!");
return Constants.FORWARD + "/login.jsp";
}
//2.获取请求参数
int uid = user.getUid();
//3.调用对应业务逻辑进行数据查询(查询当前客户购物车中信息)
CartService cartService = new CartServiceImpl();
//查询当前用户购物车中所有信息
List<Cart> list = cartService.findAll(uid);
//4.将获取到的信息转发到共享域中
request.setAttribute("list", list);
return Constants.FORWARD + "/cart.jsp";
}
//购物车中删除物品
public String delete(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取请求参数
String cid = request.getParameter("cid");
//2.调用对应的业务逻辑
CartService cartService = new CartServiceImpl();
cartService.deleteCartByCid(cid);
//3.转达到展示的处理方法中
return Constants.FORWARD + "/cart?method=show";
}
//购物车中数量更改
public String update(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取请求参数 cid 商品单价price 商品修改后数量cnum
String cid = request.getParameter("cid");
String price = request.getParameter("price");
String cnum = request.getParameter("cnum");
//2.调用对应的业务逻辑
CartService cartService = new CartServiceImpl();
cartService.updateCartByCid(cid, price, cnum);
//3.转发到展示方法中
return Constants.FORWARD + "/cart?method=show";
}
//清空购物车
public String clear(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取请求参数
String uid = request.getParameter("uid");
//2.调用对应的业务逻辑 清空购物车
CartService cartService = new CartServiceImpl();
cartService.clearCartByUid(uid);
//3.转发到展示方法中
return Constants.FORWARD + "/cart?method=show";
}
}

View File

@@ -0,0 +1,26 @@
package com.qf.controller;
import cn.dsna.util.images.ValidateCode;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet("/code")
public class CodeController extends BaseServlet {
public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
//1.生成验证码的对象
ValidateCode validateCode = new ValidateCode(100, 35, 4, 25);
//2.获取到对应的验证码
String code = validateCode.getCode();
//3.将获取到的验证码存到session中
request.getSession().setAttribute("code", code);
//4.创建出对应的字节文件对象
ServletOutputStream outputStream = response.getOutputStream();
//写回 表示验证码通过这个字节文件写回页面
validateCode.write(outputStream);
}
}

View File

@@ -0,0 +1,51 @@
package com.qf.controller;
import com.qf.entity.PageBean;
import com.qf.entity.Product;
import com.qf.service.ProductService;
import com.qf.service.impl.ProductServiceImpl;
import com.qf.utils.Constants;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
@WebServlet("/product")
public class ProductController extends BaseServlet {
public String show(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取请求参数
String tid = request.getParameter("tid");
//获取当前页和页容量
int pageSize = 8;
//当前页
String currentPage = request.getParameter("currentPage");
//默认值 1
int page = 1;
if (currentPage != null) {
page = Integer.parseInt(currentPage);
}
//2.调用业务逻辑
ProductService productService = new ProductServiceImpl();
PageBean<Product> pageBean = productService.findPage(tid, page, pageSize);
//3.响应
request.setAttribute("pageBean", pageBean);
return Constants.FORWARD + "/goodsList.jsp";
}
public String detail(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取请求参数
String pid = request.getParameter("pid");
//2.调用业务逻辑
ProductService productService = new ProductServiceImpl();
//3.声明方法
Product product = productService.findProductByPid(pid);
//3.响应
request.setAttribute("product",product);
//4.跳转到对应的商品页面
return Constants.FORWARD+"/goodsDetail.jsp";
}
}

View File

@@ -0,0 +1,29 @@
package com.qf.controller;
import com.google.gson.Gson;
import com.qf.entity.Type;
import com.qf.service.TypeService;
import com.qf.service.impl.TypeServiceImpl;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/type")
public class TypeController extends BaseServlet {
public String findAll(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//将查询到的数据转换成json的格式传递给前端进行展示
//1.调用对象调用查询方法
TypeService typeService = new TypeServiceImpl();
List<Type> types = typeService.findAll();
//2.将集合转换为 json 数据
Gson gson = new Gson();
String json = gson.toJson(types);
return json;
}
}

View File

@@ -0,0 +1,118 @@
package com.qf.controller;
import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Constants;
import com.qf.utils.MD5Utils;
import com.qf.utils.RandomUtils;
import org.apache.commons.beanutils.BeanUtils;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.Map;
@WebServlet("/user")
public class UserController extends BaseServlet {
//1.查询用户是否存在
public String check(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取用户名
String username = request.getParameter("username");
if (username == null) {
return "1";
}
//2.调用对应的业务逻辑判断用户名是否存在
UserService userService = new UserServiceImpl();
boolean b = userService.checkedUser(username);
//3.响应
if (b) {
//用户名存在
return "1";
}
return "0";
}
//2.注册功能
public String register(HttpServletRequest request, HttpServletResponse response) {
//1.获取到我们的用户信息
Map<String, String[]> parameterMap = request.getParameterMap();
//定义一个User
User user = new User();
try {
BeanUtils.populate(user, parameterMap);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
//2.完善我们用户信息
user.setUstatus("0");
user.setUrole(0);
user.setCode(RandomUtils.createActive());
//对密码进行加密处理
user.setUpassword(MD5Utils.md5(user.getUpassword()));
//3.调用对应的业务逻辑进行注册
UserService userService = new UserServiceImpl();
try {
userService.registerUser(user);
} catch (SQLException e) {
e.printStackTrace();
request.setAttribute("registerMsg", "注册失败!");
return Constants.FORWARD + "/register.jsp";
}
//4.响应
return Constants.FORWARD + "/registerSuccess.jsp";
}
//3.登录功能
public String login(HttpServletRequest request, HttpServletResponse response) throws SQLException {
//1.获取请求参数
String username = request.getParameter("username");
String password = request.getParameter("password");
//用户输入的验证码
String code = request.getParameter("code");
//2.获取正确的验证码在session中
HttpSession session = request.getSession();
String codestr = (String) session.getAttribute("code");
//3.判断验证码是否正确(空或者不匹配)
if (code == null || !code.equalsIgnoreCase(codestr)) {
//错误提示
request.setAttribute("msg", "验证码错误!");
//将页面返回登录页面
return Constants.FORWARD + "login.jsp";
}
//4.调用业务逻辑判断账号密码是否正确(验证码正确的情况下)
UserService userService = new UserServiceImpl();
User user = userService.login(username, password);
//5.响应
if (user == null) {
//错误提示
request.setAttribute("msg", "用户名或密码错误!");
//将页面返回登录页面
return Constants.FORWARD + "login.jsp";
}
//6.进行登录
session.setAttribute("loginUser", user);
return Constants.FORWARD + "/index.jsp";
}
//4.注销登录
public String logOut(HttpServletRequest request, HttpServletResponse response) {
//1.清空session中的用户数据
HttpSession session = request.getSession();
session.removeAttribute("loginUser");
//2.提示注销并将页面转发到登录页面
request.setAttribute("msg", "注销登录成功!");
return Constants.FORWARD + "login.jsp";
}
}

View File

@@ -0,0 +1,4 @@
package com.qf.dao;
public interface AddressDao {
}

View File

@@ -0,0 +1,25 @@
package com.qf.dao;
import com.qf.entity.Cart;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;
public interface CartDao {
Cart hasCart(int uid, String pid) throws SQLException, InvocationTargetException, IllegalAccessException;
void updateCart(Cart cart) throws SQLException;
void insertCart(Cart cart) throws SQLException;
List<Cart> selectCartByUid(int uid) throws SQLException, InvocationTargetException, IllegalAccessException;
void deleteCartByCid(String cid) throws SQLException;
void updateByCid(BigDecimal count, BigDecimal cnumbig, String cid) throws SQLException;
void clearCartByUid(String uid) throws SQLException;
}

View File

@@ -0,0 +1,14 @@
package com.qf.dao;
import com.qf.entity.Product;
import java.sql.SQLException;
import java.util.List;
public interface ProductDao {
long selectCountByTid(String tid) throws SQLException;
List<Product> selectProductByPage(int page, int pageSize, String tid) throws SQLException;
Product selectProductByPid(String pid) throws SQLException;
}

View File

@@ -0,0 +1,11 @@
package com.qf.dao;
import com.qf.entity.Type;
import java.sql.SQLException;
import java.util.List;
public interface TypeDao {
//需要一个方法查询数据库类别表返回Type
List<Type> selectAll() throws SQLException;
}

View File

@@ -0,0 +1,15 @@
package com.qf.dao;
import com.qf.entity.User;
import java.sql.SQLException;
//数据库访问接口
public interface UserDao {
//根据用户名查询用户是否存在
User selectUserByUname(String username) throws SQLException;
//保存数据的方法
int insertUser(User user) throws SQLException;
}

View File

@@ -0,0 +1,6 @@
package com.qf.dao.impl;
import com.qf.dao.AddressDao;
public class AddressDaoImpl implements AddressDao {
}

View File

@@ -0,0 +1,163 @@
package com.qf.dao.impl;
import com.qf.dao.CartDao;
import com.qf.entity.Cart;
import com.qf.entity.Product;
import com.qf.utils.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.MapListHandler;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class CartDaoImpl implements CartDao {
@Override
public Cart hasCart(int uid, String pid) throws SQLException, InvocationTargetException, IllegalAccessException {
//cart-->product 间接查询,多表查询
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "select p.p_name as pname, p.p_id as pid, p.t_id as tid, " +
"p.p_time as ptime, p.p_image as piamge, p.p_state as pstate, " +
"p.p_info as pinfo, p.p_price as pprice, c.c_id as cid, " +
"c.u_id as uid, c.c_count as ccount, c.c_num as cnum " +
"from product p join cart c on p.p_id = c.p_id where c.u_id = ? and c.p_id = ?";
//3.执行sql语句
Map<String, Object> query = queryRunner.query(sql, new MapHandler(), uid, pid);
//4.判断并处理信息
if (query == null) {
return null;
}
// Product product = queryRunner.query(sql, new BeanHandler<Product>(Product.class), uid, pid);
// Cart cart = queryRunner.query(sql, new BeanHandler<Cart>(Cart.class), uid, pid);
Product product = new Product();
Cart cart = new Cart();
//通过工具类 BeanUtils 将对应 key 值的信息进行赋值
BeanUtils.populate(cart, query);
BeanUtils.populate(product, query);
cart.setProduct(product);
return cart;
}
@Override
public void updateCart(Cart cart) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "update cart set c_num = ? , c_count = ? where c_id = ?;";
//3.执行sql
queryRunner.update(sql, cart.getCnum(), cart.getCcount(), cart.getCid());
}
@Override
public void insertCart(Cart cart) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "insert into cart ( u_id , p_id , c_num , c_count ) value ( ? , ? , ? , ? );";
//3.执行sql
queryRunner.update(sql, cart.getUid(), cart.getPid(), cart.getCnum(), cart.getCcount());
}
@Override
public List<Cart> selectCartByUid(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "select p.p_name as pname, p.p_id as pid, p.t_id as tid, " +
"p.p_time as ptime, p.p_image as piamge, p.p_state as pstate, " +
"p.p_info as pinfo, p.p_price as pprice, c.c_id as cid, " +
"c.u_id as uid, c.c_count as ccount, c.c_num as cnum " +
"from product p join cart c on p.p_id = c.p_id where c.u_id = ? ;";
//3.执行sql
List<Map<String, Object>> list = queryRunner.query(sql, new MapListHandler(), uid);
//判空
if (list == null) {
return null;
}
//4.创建集合放购物车中对应的商品
List<Cart> carts = new ArrayList<>();
//for循环遍历存储信息
for (Map<String, Object> map : list) {
Product product = new Product();
Cart cart = new Cart();
//通过工具类 BeanUtils 将对应 key 值的信息进行赋值
BeanUtils.populate(cart, map);
BeanUtils.populate(product, map);
//手动将 product 关联到 Cart
cart.setProduct(product);
//添加数据到 carts
carts.add(cart);
}
return carts;
}
@Override
public void deleteCartByCid(String cid) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "delete from cart where c_id = ? ;";
//3.执行sql
queryRunner.update(sql, cid);
}
@Override
public void updateByCid(BigDecimal count, BigDecimal cnumbig, String cid) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "update cart set c_count = ? , c_num = ? where c_id = ? ;";
//3.执行sql
queryRunner.update(sql, count, cnumbig, cid);
}
@Override
public void clearCartByUid(String uid) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "delete from cart where u_id = ? ;";
//3.执行sql
queryRunner.update(sql, uid);
}
}

View File

@@ -0,0 +1,61 @@
package com.qf.dao.impl;
import com.qf.dao.ProductDao;
import com.qf.entity.Product;
import com.qf.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;
public class ProductDaoImpl implements ProductDao {
@Override
public long selectCountByTid(String tid) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "select count(1) from product where t_id=?;";
Object result = queryRunner.query(sql, new ScalarHandler(), tid);
Long total = (Long) result;
return total;
}
@Override
public List<Product> selectProductByPage(int page, int pageSize, String tid) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "select p_id as pid ,t_id as tid ,p_name as pname ,p_time as ptime ," +
"p_image as pimage ,p_state as pstate ,p_info as pinfo ,p_price as pprice " +
"from product where t_id=? limit ?,?;";
//3.
List<Product> list = queryRunner.query(sql, new BeanListHandler<Product>(Product.class), tid, (page - 1) * pageSize, pageSize);
return list;
}
@Override
public Product selectProductByPid(String pid) throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "select p_id as pid ,t_id as tid ,p_name as pname ,p_time as ptime ," +
"p_image as pimage ,p_state as pstate ,p_info as pinfo ,p_price as pprice " +
"from product where p_id=?;";
//3.
Product product = queryRunner.query(sql,new BeanHandler<Product>(Product.class),pid);
return product;
}
}

View File

@@ -0,0 +1,26 @@
package com.qf.dao.impl;
import com.qf.dao.TypeDao;
import com.qf.entity.Type;
import com.qf.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import java.sql.SQLException;
import java.util.List;
public class TypeDaoImpl implements TypeDao {
@Override
public List<Type> selectAll() throws SQLException {
//1.创建 QueryRunner对象
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql(limit 5)
String sql = "select t_id as tid ,t_name as tname ,t_info as tinfo from type limit 5;";
//3.执行sql语句
List<Type> list = queryRunner.query(sql, new BeanListHandler<Type>(Type.class));
return list;
}
}

View File

@@ -0,0 +1,41 @@
package com.qf.dao.impl;
import com.qf.dao.UserDao;
import com.qf.entity.User;
import com.qf.utils.C3P0Utils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import javax.management.Query;
import java.sql.SQLException;
public class UserDaoImpl implements UserDao {
//根据用户名查询用户是否存在
@Override
public User selectUserByUname(String username) throws SQLException {
//1.创建一个QueryRunner 对象,传入我们对应的连接池
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql语句完成查询操作
String sql = "select u_id as uid ,u_name as username , u_password as upassword ," +
"u_sex as usex ,u_status as ustatus ,u_code as code, u_email as email ," +
"u_role as urole from user where u_name=?;";
//3.执行sql
User user = queryRunner.query(sql, new BeanHandler<User>(User.class), username);
return user;
}
//保存数据的方法
@Override
public int insertUser(User user) throws SQLException {
//1.创建一个QueryRunner对象传入我们对应的连接池
QueryRunner queryRunner = new QueryRunner(C3P0Utils.getDataSource());
//2.编写sql
String sql = "insert into user(u_name ,u_password,u_sex,u_status, " +
"u_code ,u_email,u_role) value(?,?,?,?,?,?,?);";
//执行sql
int rows = queryRunner.update(sql, user.getUsername(), user.getUpassword(), user.getUsex(),
user.getUstatus(), user.getCode(), user.getEmail(), user.getUrole());
return rows;
}
}

View File

@@ -0,0 +1,74 @@
package com.qf.entity;
import java.io.Serializable;
public class Address implements Serializable {
private static final long serialVersionUID =1L;
private int aid;
private int uid;
private String aname;
private String aphone;
private String adetail;
private int astate;
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public String getAphone() {
return aphone;
}
public void setAphone(String aphone) {
this.aphone = aphone;
}
public String getAdetail() {
return adetail;
}
public void setAdetail(String adetail) {
this.adetail = adetail;
}
public int getAstate() {
return astate;
}
public void setAstate(int astate) {
this.astate = astate;
}
@Override
public String toString() {
return "Address{" +
"aid=" + aid +
", uid=" + uid +
", aname='" + aname + '\'' +
", aphone='" + aphone + '\'' +
", adetail='" + adetail + '\'' +
", astate=" + astate +
'}';
}
}

View File

@@ -0,0 +1,84 @@
package com.qf.entity;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 数据库对应的购物车表
*/
public class Cart implements Serializable {
private static final long serialVersionUID = 1L;
private int cid;
private int uid;
private int pid;
private Product product;
private int cnum = 0; //购车商品数量
private BigDecimal ccount; //购物车小计
public Cart() {
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
@Override
public String toString() {
return "Cart{" +
"cid=" + cid +
", uid=" + uid +
", cnum=" + cnum +
", ccount=" + ccount +
'}';
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getCnum() {
return cnum;
}
public void setCnum(int cnum) {
this.cnum = cnum;
}
public BigDecimal getCcount() {
BigDecimal pprice = product.getPprice();
BigDecimal bigDecimal = new BigDecimal(cnum);
return pprice.multiply(bigDecimal);
}
public void setCcount(BigDecimal ccount) {
this.ccount = ccount;
}
}

View File

@@ -0,0 +1,79 @@
package com.qf.entity;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 对应数据库订单项
*/
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
private int iid;
private String oid;
private int pid;
private Product product;
private BigDecimal icount;
private int inum;
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public int getIid() {
return iid;
}
public void setIid(int iid) {
this.iid = iid;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public BigDecimal getIcount() {
return icount;
}
public void setIcount(BigDecimal icount) {
this.icount = icount;
}
public int getInum() {
return inum;
}
public void setInum(int inum) {
this.inum = inum;
}
@Override
public String toString() {
return "Item{" +
"iid=" + iid +
", oid='" + oid + '\'' +
", pid=" + pid +
", icount=" + icount +
", inum=" + inum +
'}';
}
}

View File

@@ -0,0 +1,102 @@
package com.qf.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
/**
* 对应数据库的订单表
*/
public class Orders implements Serializable {
private static final long serialVersionUID = 1L;
private String oid;
private int uid;
private int aid;
private Address address;
private BigDecimal ocount; //订单总金额
private Date otime;
private int ostate; //订单状态 0 未付款1已经付款未发货 2发货待收货 3 收货待评价 4订单完成 5 退货状态
private List<Item> items;
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public String getOid() {
return oid;
}
public void setOid(String oid) {
this.oid = oid;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public int getAid() {
return aid;
}
public void setAid(int aid) {
this.aid = aid;
}
public BigDecimal getOcount() {
return ocount;
}
public void setOcount(BigDecimal ocount) {
this.ocount = ocount;
}
public Date getOtime() {
return otime;
}
public void setOtime(Date otime) {
this.otime = otime;
}
public int getOstate() {
return ostate;
}
public void setOstate(int ostate) {
this.ostate = ostate;
}
@Override
public String toString() {
return "Orders{" +
"oid='" + oid + '\'' +
", uid=" + uid +
", aid=" + aid +
", ocount=" + ocount +
", otime=" + otime +
", ostate=" + ostate +
'}';
}
}

View File

@@ -0,0 +1,64 @@
package com.qf.entity;
import java.util.List;
//PageBean<T>加一个泛型T
public class PageBean<T> {
private List<T> list;//展示的数据
private int currentPage;//当前页数
private int pageSize;//页容量,每页显示的数据条数
private long totalCount; //总条数
private int totalPage; //总页数
//不传入总页数(构造方法)
public PageBean(List<T> list, int currentPage, int pageSize, long totalCount) {
this.list = list;
this.currentPage = currentPage;
this.pageSize = pageSize;
this.totalCount = totalCount;
}
//添加get/set方法
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
public int getCurrentPage() {
return currentPage;
}
public void setCurrentPage(int currentPage) {
this.currentPage = currentPage;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public long getTotalCount() {
return totalCount;
}
public void setTotalCount(long totalCount) {
this.totalCount = totalCount;
}
public int getTotalPage() {
//需要进行一个运算
//13条数据 每页显示5 3Math.ceil向下舍余totalCount*1.0转成double类型
return (int) Math.ceil(totalCount*1.0/pageSize);
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
}

View File

@@ -0,0 +1,100 @@
package com.qf.entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 对应数据库的商品表
*/
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
private int pid;
private int tid;
private String pname;
private Date ptime; //商品的上架时间! 数据库date --> java.util.Date
private String pimage; //商品的图片名称
private int pstate; //商品的热门指数
private String pinfo; //商品的描述
private BigDecimal pprice; //价格
public BigDecimal getPprice() {
return pprice;
}
public void setPprice(BigDecimal pprice) {
this.pprice = pprice;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Date getPtime() {
return ptime;
}
public void setPtime(Date ptime) {
this.ptime = ptime;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public int getPstate() {
return pstate;
}
public void setPstate(int pstate) {
this.pstate = pstate;
}
public String getPinfo() {
return pinfo;
}
public void setPinfo(String pinfo) {
this.pinfo = pinfo;
}
@Override
public String toString() {
return "Product{" +
"pid=" + pid +
", tid=" + tid +
", pname='" + pname + '\'' +
", ptime=" + ptime +
", pimage='" + pimage + '\'' +
", pstate=" + pstate +
", pinfo='" + pinfo + '\'' +
'}';
}
}

View File

@@ -0,0 +1,161 @@
package com.qf.entity;
public class Result {
private String appid;
private String bank_type;
private String cash_fee;
private String is_subscribe;
private String mch_id;
private String nonce_str;
private String openid;
private String out_trade_no;
private String result_code;//支付结果
private String return_code;
private String sign;
private String time_end;
private String total_fee;//总支付价格
private String trade_type;
private String transaction_id;
public String getAppid() {
return appid;
}
public void setAppid(String appid) {
this.appid = appid;
}
public String getBank_type() {
return bank_type;
}
public void setBank_type(String bank_type) {
this.bank_type = bank_type;
}
public String getCash_fee() {
return cash_fee;
}
public void setCash_fee(String cash_fee) {
this.cash_fee = cash_fee;
}
public String getIs_subscribe() {
return is_subscribe;
}
public void setIs_subscribe(String is_subscribe) {
this.is_subscribe = is_subscribe;
}
public String getMch_id() {
return mch_id;
}
public void setMch_id(String mch_id) {
this.mch_id = mch_id;
}
public String getNonce_str() {
return nonce_str;
}
public void setNonce_str(String nonce_str) {
this.nonce_str = nonce_str;
}
public String getOpenid() {
return openid;
}
public void setOpenid(String openid) {
this.openid = openid;
}
public String getOut_trade_no() {
return out_trade_no;
}
public void setOut_trade_no(String out_trade_no) {
this.out_trade_no = out_trade_no;
}
public String getResult_code() {
return result_code;
}
public void setResult_code(String result_code) {
this.result_code = result_code;
}
public String getReturn_code() {
return return_code;
}
public void setReturn_code(String return_code) {
this.return_code = return_code;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
public String getTime_end() {
return time_end;
}
public void setTime_end(String time_end) {
this.time_end = time_end;
}
public String getTotal_fee() {
return total_fee;
}
public void setTotal_fee(String total_fee) {
this.total_fee = total_fee;
}
public String getTrade_type() {
return trade_type;
}
public void setTrade_type(String trade_type) {
this.trade_type = trade_type;
}
public String getTransaction_id() {
return transaction_id;
}
public void setTransaction_id(String transaction_id) {
this.transaction_id = transaction_id;
}
public Result(String appid, String bank_type, String cash_fee, String is_subscribe, String mch_id, String nonce_str,
String openid, String out_trade_no, String result_code, String return_code, String sign, String time_end,
String total_fee, String trade_type, String transaction_id) {
super();
this.appid = appid;
this.bank_type = bank_type;
this.cash_fee = cash_fee;
this.is_subscribe = is_subscribe;
this.mch_id = mch_id;
this.nonce_str = nonce_str;
this.openid = openid;
this.out_trade_no = out_trade_no;
this.result_code = result_code;
this.return_code = return_code;
this.sign = sign;
this.time_end = time_end;
this.total_fee = total_fee;
this.trade_type = trade_type;
this.transaction_id = transaction_id;
}
}

View File

@@ -0,0 +1,48 @@
package com.qf.entity;
import java.io.Serializable;
/**
* 对应的数据库的类别表
*/
public class Type implements Serializable {
private static final long serialVersionUID = 1L;
private int tid; // '类别的主键id',
private String tname; // '类别的名称',
private String tinfo; //'类别的描述',
public int getTid() {
return tid;
}
public void setTid(int tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getTinfo() {
return tinfo;
}
public void setTinfo(String tinfo) {
this.tinfo = tinfo;
}
@Override
public String toString() {
return "Type{" +
"tid=" + tid +
", tname='" + tname + '\'' +
", tinfo='" + tinfo + '\'' +
'}';
}
}

View File

@@ -0,0 +1,99 @@
package com.qf.entity;
import java.io.Serializable;
/**
* 对应数据库的用户表
*/
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private int uid;
private String username; //对应的是数据库的uname字段
private String upassword; //密码
private String usex; //性别
private String ustatus; //用户的激活状态 0 未激活 1 激活
private String code;
private String email; //对应的是数据库的uemail字段
private int urole; //用户 0 管理员 1
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getUpassword() {
return upassword;
}
public void setUpassword(String upassword) {
this.upassword = upassword;
}
public String getUsex() {
return usex;
}
public void setUsex(String usex) {
this.usex = usex;
}
public String getUstatus() {
return ustatus;
}
public void setUstatus(String ustatus) {
this.ustatus = ustatus;
}
public int getUrole() {
return urole;
}
public void setUrole(int urole) {
this.urole = urole;
}
@Override
public String toString() {
return "User{" +
"uid=" + uid +
", username='" + username + '\'' +
", upassword='" + upassword + '\'' +
", usex='" + usex + '\'' +
", ustatus='" + ustatus + '\'' +
", code='" + code + '\'' +
", email='" + email + '\'' +
", urole=" + urole +
'}';
}
}

View File

@@ -0,0 +1,28 @@
package com.qf.entity;
public class WeiXin {
private Result result;
private String type;
public Result getResult() {
return result;
}
public void setResult(Result result) {
this.result = result;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public WeiXin(Result result, String type) {
super();
this.result = result;
this.type = type;
}
public WeiXin() {
super();
}
}

View File

@@ -0,0 +1,27 @@
package com.qf.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter(urlPatterns = "/*")
public class EncodingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//1.设置编码格式
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
//2放行
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}

View File

@@ -0,0 +1,4 @@
package com.qf.service;
public interface AddressService {
}

View File

@@ -0,0 +1,19 @@
package com.qf.service;
import com.qf.entity.Cart;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.List;
public interface CartService {
void createCart(int uid, String pid) throws SQLException, InvocationTargetException, IllegalAccessException;
List<Cart> findAll(int uid) throws SQLException, InvocationTargetException, IllegalAccessException;
void deleteCartByCid(String cid) throws SQLException;
void updateCartByCid(String cid, String price, String cnum) throws SQLException;
void clearCartByUid(String uid) throws SQLException;
}

View File

@@ -0,0 +1,12 @@
package com.qf.service;
import com.qf.entity.PageBean;
import com.qf.entity.Product;
import java.sql.SQLException;
public interface ProductService {
PageBean<Product> findPage(String tid, int page, int pageSize) throws SQLException;
Product findProductByPid(String pid) throws SQLException;
}

View File

@@ -0,0 +1,13 @@
package com.qf.service;
import com.qf.entity.Type;
import java.sql.SQLException;
import java.util.List;
public interface TypeService {
//查询返回所有类别表中对应的type信息
List<Type> findAll() throws SQLException;
}

View File

@@ -0,0 +1,17 @@
package com.qf.service;
import com.qf.entity.User;
import java.sql.SQLException;
public interface UserService {
//查询用户名是否存在
boolean checkedUser(String username) throws SQLException;
//注册业务逻辑
int registerUser(User user) throws SQLException;
//登录的业务逻辑
User login(String username, String password) throws SQLException;
}

View File

@@ -0,0 +1,6 @@
package com.qf.service.impl;
import com.qf.service.AddressService;
public class AddressServiceImpl implements AddressService {
}

View File

@@ -0,0 +1,88 @@
package com.qf.service.impl;
import com.qf.dao.CartDao;
import com.qf.dao.ProductDao;
import com.qf.dao.impl.CartDaoImpl;
import com.qf.dao.impl.ProductDaoImpl;
import com.qf.entity.Cart;
import com.qf.entity.Product;
import com.qf.service.CartService;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.sql.SQLException;
import java.util.List;
public class CartServiceImpl implements CartService {
//1.向购物车中添加物品
@Override
public void createCart(int uid, String pid) throws SQLException, InvocationTargetException, IllegalAccessException {
//1.判断商品是否已经存在
CartDao cartDao = new CartDaoImpl();
Cart cart = cartDao.hasCart(uid, pid);
if (cart != null) {
//已存在该物品,修改数量
cart.setCnum(cart.getCnum() + 1);
cartDao.updateCart(cart);
} else {
//不存在该物品,添加该物品
ProductDao productDao = new ProductDaoImpl();
Product product = productDao.selectProductByPid(pid);
//完成添加
cart = new Cart();
cart.setCnum(1);
cart.setPid(Integer.parseInt(pid));
cart.setProduct(product);
cart.setUid(uid);
//完成插入操作
cartDao.insertCart(cart);
}
}
//2.根据uid查询所有商品
@Override
public List<Cart> findAll(int uid) throws SQLException, InvocationTargetException, IllegalAccessException {
CartDao cartDao = new CartDaoImpl();
//1.根据用户 id 查询对应购物车里面的商品
List<Cart> carts = cartDao.selectCartByUid(uid);
return carts;
}
//3.根据cid删除购物车中物品
@Override
public void deleteCartByCid(String cid) throws SQLException {
CartDao cartDao = new CartDaoImpl();
cartDao.deleteCartByCid(cid);
}
//4.购物车修改数量
@Override
public void updateCartByCid(String cid, String price, String cnum) throws SQLException {
//1.将对应的 cnum 和 price 转换成对应的大数据类型
BigDecimal cnumbig = new BigDecimal(cnum);
BigDecimal prciebig = new BigDecimal(price);
//2.进行小计计算
BigDecimal count = prciebig.multiply(cnumbig);
//3.数据库中修改
CartDao cartDao = new CartDaoImpl();
cartDao.updateByCid(count, cnumbig, cid);
}
//5.清空购物车
@Override
public void clearCartByUid(String uid) throws SQLException {
CartDao cartDao = new CartDaoImpl();
cartDao.clearCartByUid(uid);
}
}

View File

@@ -0,0 +1,34 @@
package com.qf.service.impl;
import com.qf.dao.ProductDao;
import com.qf.dao.impl.ProductDaoImpl;
import com.qf.entity.PageBean;
import com.qf.entity.Product;
import com.qf.service.ProductService;
import java.sql.SQLException;
import java.util.List;
public class ProductServiceImpl implements ProductService {
@Override
public PageBean<Product> findPage(String tid, int page, int pageSize) throws SQLException {
ProductDao productDao = new ProductDaoImpl();
//1.查询有多少条数据
long count = productDao.selectCountByTid(tid);
//
List<Product> list = productDao.selectProductByPage(page, pageSize, tid);
return new PageBean<Product>(list, page, pageSize, count);
}
@Override
public Product findProductByPid(String pid) throws SQLException {
//1.先到数据库中进行商品查询
ProductDao productDao = new ProductDaoImpl();
//2.定义一个productdao里面对应的方法返回product
Product product = productDao.selectProductByPid(pid);
//3.返回product信息
return product;
}
}

View File

@@ -0,0 +1,20 @@
package com.qf.service.impl;
import com.qf.dao.TypeDao;
import com.qf.dao.impl.TypeDaoImpl;
import com.qf.entity.Type;
import com.qf.service.TypeService;
import java.sql.SQLException;
import java.util.List;
public class TypeServiceImpl implements TypeService {
@Override
public List<Type> findAll() throws SQLException {
//这里调用TypeDao接口Dao层
TypeDao typeDao = new TypeDaoImpl();
List<Type> types = typeDao.selectAll();
return types;
}
}

View File

@@ -0,0 +1,52 @@
package com.qf.service.impl;
import com.qf.dao.UserDao;
import com.qf.dao.impl.UserDaoImpl;
import com.qf.entity.User;
import com.qf.service.UserService;
import com.qf.utils.MD5Utils;
import java.sql.SQLException;
public class UserServiceImpl implements UserService {
//查询用户名是否存在
@Override
public boolean checkedUser(String username) throws SQLException {
//根据dao访问对象
UserDao userDao = new UserDaoImpl();
User user = userDao.selectUserByUname(username);
//处理返回值
if (user != null) {
return true;
}
//没有查询到
return false;
}
//注册业务逻辑
@Override
public int registerUser(User user) throws SQLException {
UserDao userDao = new UserDaoImpl();
int row = userDao.insertUser(user);
return row;
}
//登录的业务逻辑
@Override
public User login(String username, String password) throws SQLException {
//1.密码加密处理(数据库中密码已加密处理)便于比较
String md5password = MD5Utils.md5(password);
//2.根据用户名查询用户
UserDao userDao = new UserDaoImpl();
User user = userDao.selectUserByUname(username);
//3.账号密码对比正确返回user
if (user != null && user.getUpassword().equals(md5password)) {
return user;
}
//错误返回空 null
return null;
}
}

View File

@@ -0,0 +1,16 @@
package com.qf.utils;
import java.util.Base64;
//base64 加密 解密 激活邮件的时候 为 邮箱地址 code验证码 进行加密
//当 回传回来后 进行邮箱地址 和 code 的解密
public class Base64Utils {
//加密
public static String encode(String msg){
return Base64.getEncoder().encodeToString(msg.getBytes());
}
//解密
public static String decode(String msg){
return new String(Base64.getDecoder().decode(msg));
}
}

View File

@@ -0,0 +1,43 @@
package com.qf.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class C3P0Utils {
//获取数据源 C3P0配置文件信息 自动获取
private static DataSource ds = new ComboPooledDataSource();
//对外提供一个get方法 可以通过外部访问到DataSource
public static DataSource getDataSource(){
return ds;
}
//获取连接
public static Connection getConnection(){
try {
return ds.getConnection();
} catch (SQLException e) {
throw new RuntimeException("服务器繁忙....");
}
}
//释放资源
public static void release(ResultSet rs,Statement stmt,Connection conn){
try {
if(rs!=null){
rs.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

View File

@@ -0,0 +1,49 @@
package com.qf.utils;
/**
* 项目的常量类
*/
public class Constants {
//声明method标识
public static final String TAG = "method";
public static final String FORWARD = "forward:";
public static final String REDIRECT="redirect:";
public static final String FLAG=":";
public static final String INDEX="index";
/*
定义用户模块涉及的常量
*/
public static final String HAS_USER="1";
public static String NOT_HAS_USER = "0";
//用户的状态
public static final String USER_ACTIVE ="1";
public static final String USER_NOT_ACTIVE = "0";
//角色
public static final int ROLE_CUSTOMER = 0;//用户
public static final int ROLE_ADMIN= 1;//管理员
/**
* 用户模块激活状态
*/
public static final int ACTIVE_FAIL= 0;
public static final int ACTIVE_SUCCESS= 1;
public static final int ACTIVE_ALREADY= 2;
/**
* 自动登录cookie名
*/
public static final String AUTO_NAME="autoUser";
}

View File

@@ -0,0 +1,95 @@
package com.qf.utils;
import com.qf.entity.User;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.net.Inet4Address;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.Properties;
/*
* 1.首先需要获取发送邮件的Session对象
* Session session = Session.getDefaultInstance(Properties prop)
* 2.使用session对象 获取待发送的邮件信息
* MimeMessage mime = new MimeMessage(session)
* 3.设置发件人 收件人 标题 邮件内容 附件 发送时间等等
* 4.利用Transport 发送邮件
* */
public class EmailUtils {
public static void sendEmail(User user){
//发送方
String myAccount = "cqjava1701@163.com";
//授权码
String myPass = "cq1701";
//发件人 邮箱的 SMTP 服务器地址
String SMTPHost = "smtp.163.com";
//组成 properties
Properties prop = new Properties();
prop.setProperty("mail.transport.protocol", "smtp");//设置协议类型
prop.setProperty("mail.smtp.host", SMTPHost);//定义发件人的邮箱服务器地址
prop.setProperty("mail.smtp.auth", "true");//设置请求验证
//1.Session对象 创建会话 用于和邮箱服务器进行交互
Session session = Session.getDefaultInstance(prop);
//设置debug模式 可以查看详细发送信息 可略
session.setDebug(true);
//2.创建方法 用来组成一封完整的邮件
//参数 session(参数配置), myAccount 发送方 , user.getEmail() 接收方
MimeMessage message = createMsg(session,myAccount,user);
//4.利用Transport 发送邮件
try {
Transport tran = session.getTransport();
//连接服务器 确认发送方 是否授权
tran.connect(myAccount, myPass);
//发送邮件 将message 对象 传给 Transport 对象 将邮件发送出去
//参数1 要发的内容 参数2 要给哪些人发
//message.getAllRecipients() 获取到所有的收件人 | 抄送 | 密送
tran.sendMessage(message, message.getAllRecipients());
//关闭连接
tran.close();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static MimeMessage createMsg(Session session, String myAccount, User user) {
//使用session对象 获取待发送的邮件信息
MimeMessage message = new MimeMessage(session);
//3.设置发件人 收件人 标题 邮件内容 附件 发送时间等等
try {
//3.1发件人 from
message.setFrom(new InternetAddress(myAccount, "小米", "utf-8"));
//3.2收件人 to 支持可以添加多个收件人 | 抄送 | 密送 如果想要发送给多个人 可以重复下面代码多次
/*
* MimeMessage.RecipientType.TO 发送
* MimeMessage.RecipientType.CC 抄送
* MimeMessage.RecipientType.BCC 密送
* */
message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(user.getEmail(), user.getUsername(), "utf-8"));
//3.3生成邮件主题
message.setSubject("小米商城账号激活邮件","utf-8");
String ip = Inet4Address.getLocalHost().getHostAddress();
String url = "http://"+ip+":8080/activate?e="+ Base64Utils.encode(user.getEmail())+"&c="+Base64Utils.encode(user.getCode());
//设置邮件正文 setContent 可以使用html标签
message.setContent(user.getUsername()+",你好<br>欢迎注册小米商城! 请点击链接进行激活:<a href='"+url+"'>"+url+"</a>","text/html;charset=utf-8");
//设置邮件的发送时间 是立即发送
message.setSentDate(new Date());
//保存设置
message.saveChanges();
} catch (UnsupportedEncodingException | MessagingException | UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return message;
}
}

View File

@@ -0,0 +1,24 @@
package com.qf.utils;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
//MD5 生成器
public class MD5Utils {
public static String md5(String password){
//生成一个md5加密器
try {
MessageDigest md = MessageDigest.getInstance("MD5");
//计算MD5 的值
md.update(password.getBytes());
//BigInteger 将8位的字符串 转成16位的字符串 得到的字符串形式是哈希码值
//BigInteger(参数1,参数2) 参数1 是 1为正数 0为0 -1为负数
return new BigInteger(1, md.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}

View File

@@ -0,0 +1,214 @@
package com.qf.utils;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class PaymentUtil {
private static String encodingCharset = "UTF-8";
/**
* 生成hmac方法
*
* @param p0_Cmd 业务类型
* @param p1_MerId 商户编号
* @param p2_Order 商户订单号
* @param p3_Amt 支付金额
* @param p4_Cur 交易币种
* @param p5_Pid 商品名称
* @param p6_Pcat 商品种类
* @param p7_Pdesc 商品描述
* @param p8_Url 商户接收支付成功数据的地址
* @param p9_SAF 送货地址
* @param pa_MP 商户扩展信息
* @param pd_FrpId 银行编码
* @param pr_NeedResponse 应答机制
* @param keyValue 商户密钥
* @return
*/
public static String buildHmac(String p0_Cmd,String p1_MerId,
String p2_Order, String p3_Amt, String p4_Cur,String p5_Pid, String p6_Pcat,
String p7_Pdesc,String p8_Url, String p9_SAF,String pa_MP,String pd_FrpId,
String pr_NeedResponse,String keyValue) {
StringBuilder sValue = new StringBuilder();
// 业务类型
sValue.append(p0_Cmd);
// 商户编号
sValue.append(p1_MerId);
// 商户订单号
sValue.append(p2_Order);
// 支付金额
sValue.append(p3_Amt);
// 交易币种
sValue.append(p4_Cur);
// 商品名称
sValue.append(p5_Pid);
// 商品种类
sValue.append(p6_Pcat);
// 商品描述
sValue.append(p7_Pdesc);
// 商户接收支付成功数据的地址
sValue.append(p8_Url);
// 送货地址
sValue.append(p9_SAF);
// 商户扩展信息
sValue.append(pa_MP);
// 银行编码
sValue.append(pd_FrpId);
// 应答机制
sValue.append(pr_NeedResponse);
return PaymentUtil.hmacSign(sValue.toString(), keyValue);
}
/**
* 返回校验hmac方法
*
* @param hmac 支付网关发来的加密验证码
* @param p1_MerId 商户编号
* @param r0_Cmd 业务类型
* @param r1_Code 支付结果
* @param r2_TrxId 易宝支付交易流水号
* @param r3_Amt 支付金额
* @param r4_Cur 交易币种
* @param r5_Pid 商品名称
* @param r6_Order 商户订单号
* @param r7_Uid 易宝支付会员ID
* @param r8_MP 商户扩展信息
* @param r9_BType 交易结果返回类型
* @param keyValue 密钥
* @return
*/
public static boolean verifyCallback(String hmac, String p1_MerId,
String r0_Cmd, String r1_Code, String r2_TrxId, String r3_Amt,
String r4_Cur, String r5_Pid, String r6_Order, String r7_Uid,
String r8_MP, String r9_BType, String keyValue) {
StringBuilder sValue = new StringBuilder();
// 商户编号
sValue.append(p1_MerId);
// 业务类型
sValue.append(r0_Cmd);
// 支付结果
sValue.append(r1_Code);
// 易宝支付交易流水号
sValue.append(r2_TrxId);
// 支付金额
sValue.append(r3_Amt);
// 交易币种
sValue.append(r4_Cur);
// 商品名称
sValue.append(r5_Pid);
// 商户订单号
sValue.append(r6_Order);
// 易宝支付会员ID
sValue.append(r7_Uid);
// 商户扩展信息
sValue.append(r8_MP);
// 交易结果返回类型
sValue.append(r9_BType);
String sNewString = PaymentUtil.hmacSign(sValue.toString(), keyValue);
return sNewString.equals(hmac);
}
/**
* @param aValue
* @param aKey
* @return
*/
public static String hmacSign(String aValue, String aKey) {
byte k_ipad[] = new byte[64];
byte k_opad[] = new byte[64];
byte keyb[];
byte value[];
try {
keyb = aKey.getBytes(encodingCharset);
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
keyb = aKey.getBytes();
value = aValue.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
for (int i = 0; i < keyb.length; i++) {
k_ipad[i] = (byte) (keyb[i] ^ 0x36);
k_opad[i] = (byte) (keyb[i] ^ 0x5c);
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
md.update(k_ipad);
md.update(value);
byte dg[] = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return toHex(dg);
}
public static String toHex(byte input[]) {
if (input == null)
return null;
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++) {
int current = input[i] & 0xff;
if (current < 16)
output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}
/**
*
* @param args
* @param key
* @return
*/
public static String getHmac(String[] args, String key) {
if (args == null || args.length == 0) {
return (null);
}
StringBuffer str = new StringBuffer();
for (int i = 0; i < args.length; i++) {
str.append(args[i]);
}
return (hmacSign(str.toString(), key));
}
/**
* @param aValue
* @return
*/
public static String digest(String aValue) {
aValue = aValue.trim();
byte value[];
try {
value = aValue.getBytes(encodingCharset);
} catch (UnsupportedEncodingException e) {
value = aValue.getBytes();
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
return toHex(md.digest(value));
}
// public static void main(String[] args) {
// System.out.println(hmacSign("AnnulCard1000043252120080620160450.0http://localhost/SZXpro/callback.asp杩?4564868265473632445648682654736324511","8UPp0KE8sq73zVP370vko7C39403rtK1YwX40Td6irH216036H27Eb12792t"));
// }
}

View File

@@ -0,0 +1,21 @@
package com.qf.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
//生成邮箱验证 激活码 使用的随机数
public class RandomUtils {
//当前时间 + 随机数
public static String createActive(){
return getTime()+Integer.toHexString(new Random().nextInt(900)+100);
}
public static String getTime(){
return new SimpleDateFormat("yyyyMMddHHmmssSSS").format(Calendar.getInstance().getTime());
}
//生成订单编号
public static String createOrderId(){
return getTime();
}
}

View File

@@ -0,0 +1,17 @@
package com.qf.utils;
//字符串工具类 判定字符串是否为空
public class StrUtils {
public static boolean empty(String msg){
return msg!=null && msg.length()>0;
}
public static boolean empty(String...msg){
boolean res = true;
for(String s:msg){
res = (s!=null && s.length()>0);
if(!res){
break;
}
}
return res;
}
}