商城管理系统
文章目录
- 商城管理系统
- 要求:
- 项目结构图
- AddProductServlet添加商品:
- AddToCart将商品添加至购物车
- ClearCart清空购物车
- DeleteProductServlet删除商品
- EditProductServlet修改商品
- FindProductServlet查找商品
- LoginServlet登录
- ProductControl商品管理页
- ProductListsPage商品列表页
- RegistServlet注册
- ShowCart订单生成
- ProductDao Dao层代码
- Cart购物车实体类
- Product 商品实体类
- User 用户实体类
- CharactFilter过滤器
- ContextListener监听器
- PageListener监听器
- ProductService service层代码
- DBUtil工具类
- InitTableJDBC 初始化数据库,创建表........
- add.html 商品添加页面
- findProduct.html 商品寻找条件确定页面
- login.html 登录页面
- order.html 用户订单信息填写界面
- regist.html 注册页面
- ifdelete.html 是否删除商品确定页面
要求:
编码要求如下:
1)使用HTML或者Servlet实现界面,发送请求给Servlet。
2)使用Servlet作为控制器调用Service层代码。
3)Service层调用Dao层代码。
4)Dao层代码完成数据增删改查。
结合JDBC和Servlet实现商城管理系统部分功能。
1)当新用户首次访问该网站时,需要先注册账号。在注册页面中新用户需要填写有邮箱、用户名、密码、重复密码、性别、联系电话、个人介绍。首先对填写的注册信息进行校验,比如用户名和密码不能为空;密码和重复密码表单输入的内容必须一致;输入的邮箱地址应该是合法的等。然后查询数据库判断用户名是否存在。如果存在,则注册失败。如果不存在,则注册成功。
2)商品列表页,当用户选择商品时,首先需要校验此用户是否登陆,如果未登录则提示用户登录,如果已经登陆则将商品添加至购物车,此时购物车中如已经有此商品,则商品数量加一,否则添加此商品。商品添加后可选择是继续购物、清空购物车还是进行结算,如果进行结算则让用户填写订单信息,之后生成订单。
3)商品管理页,主要的功能包括查询商品信息、添加商品信息、编辑商品信息和删除商品信息这4个功能。查询商品信息时可通过条件查询也可以查询所用商品。查询之后可进入商品列表页面,在此页面中提供了增加、修改和删除商品信息的功能。
单击添加按钮,打开商品添加页面,填写商品信息之后,单击确定按钮后,新添加的商品信息即可在列表页面中显示出来。单击商品列表中修改按钮,页面会跳转到该商品的编辑页面,修改其中显示出商品的具体信息之后,单击保存按钮,商品管理首页将显示修改后的商品信息。单击列表页面中商品后面的删除按钮,会提示是否删除,确定删除后,系统会将此条商品信息删除,商品管理页将不再显示此信息。
4)要求使用 过滤器,实现响应的字符过滤
response.setContentType(“text/html;charset=UTF-8”);
5)要求使用 监听器,在页面显示网站的访问人数
项目结构图
AddProductServlet添加商品:
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.Product;
import service.ProductService;
/**
* Servlet implementation class AddProductServlet
*/
@WebServlet("/addproduct")
public class AddProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddProductServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ProductService service=new ProductService();
String id=request.getParameter("id");
String name=request.getParameter("name");
String description=request.getParameter("description");
String price=request.getParameter("price");
String stock=request.getParameter("stock");
Product product=new Product(Integer.parseInt(id),name,description,Integer.parseInt(price),Integer.parseInt(stock));
service.addProduct(product);
response.sendRedirect("lists");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
AddToCart将商品添加至购物车
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.Cart;
import entity.Product;
import service.ProductService;
/**
* Servlet implementation class AddToCart
*/
@WebServlet("/add")
public class AddToCart extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public AddToCart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String sid=request.getParameter("id");
ProductService service=new ProductService();
Product product=service.findByid(Integer.parseInt(sid));
// 确定用户选定的商品,获取参数值
int id=product.getId();
String name = product.getName();
String description = product.getDescription();
int price_s = product.getPrice();
int stock_s = product.getStock();
int price = 0;
int stock = 0;
String cartStr;
try {
cartStr = service.findCartNameService(name);
if(cartStr==null) {
// 购物车里面没有对应的商品,将该商品加入购物车
price=price_s;
stock=stock_s;
Cart cart=new Cart(id,name,description,price,stock);
service.addToCartService(cart);
}else {
// 购物车里面有对应的商品,将该商品在购物车的数量加一
price=price_s;
int stock1;
try {
stock1 = service.findCartStockByNameService(name);
Cart cart=new Cart(id,name,description,price,stock1);
service.editCartService(cart);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
PrintWriter writer=response.getWriter();
writer.write("<h3>接下来您可以选择一下选项:</h3>");
writer.write("<a href='lists'>继续购物</a><br>");
writer.write("<a href='clear'>清空购物车</a><br>");
writer.write("<a href='order.html'>进行结算</a><br>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ClearCart清空购物车
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.ProductService;
/**
* Servlet implementation class ClearCart
*/
@WebServlet("/clear")
public class ClearCart extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ClearCart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ProductService service=new ProductService();
service.clearCartService();
PrintWriter out =response.getWriter();
out.write("<h3>购物车清空完成!</h3>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
DeleteProductServlet删除商品
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.ProductService;
/**
* Servlet implementation class DeleteProductServlet
*/
@WebServlet("/delete")
public class DeleteProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public DeleteProductServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ProductService service=new ProductService();
PrintWriter out=response.getWriter();
String sid=request.getParameter("id");
//根据ID,文本框显示用户信息,form,两个文本框,一个按钮
boolean flag=service.deleteProduct(Integer.parseInt(sid));
if(flag) {
out.write("修改成功");
response.sendRedirect("control");
}else {
out.write("修改失败");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
EditProductServlet修改商品
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import entity.Product;
import service.ProductService;
/**
* Servlet implementation class EditProductServlet
*/
@WebServlet("/edit")
public class EditProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public EditProductServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
ProductService service=new ProductService();
PrintWriter out=response.getWriter();
String sid=request.getParameter("id");
// String name=request.getParameter("name");
System.out.println(sid);
//根据ID,文本框显示用户信息,form,两个文本框,一个按钮
Product stu=service.findByid(Integer.parseInt(sid));
// Product stu=service.findByNameService(name);
out.print("<form action='edit' method='post'>");
out.write("<input type='hidden' name='id' value='"+sid+"'><br>");
out.write("商品名:<input type='text' name='name' value='"+stu.getName()+"'><br>");
out.write("描述:<input type='text' name='description' value='"+stu.getDescription()+"'><br>");
out.write("价格:<input type='text' name='price' value='"+stu.getPrice()+"'><br>");
out.write("数量:<input type='text' name='stock' value='"+stu.getStock()+"'><br>");
out.write("<input type='submit' value='修改'>");
out.write("</form>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// doGet(request, response);
String id=request.getParameter("id");
String name=request.getParameter("name");
String description=request.getParameter("description");
String price=request.getParameter("price");
String stock=request.getParameter("stock");
// 修改学生信息
Product stu=new Product(Integer.parseInt(id),name,description,Integer.parseInt(price),Integer.parseInt(stock));
ProductService service=new ProductService();
boolean flag=service.editProduct(stu);
if(flag) {
System.out.println("修改成功");
response.sendRedirect("control");
}else {
System.out.println("修改失败");
}
}
}
FindProductServlet查找商品
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.ProductService;
/**
* Servlet implementation class FindProductServlet
*/
@WebServlet("/findproduct")
public class FindProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public FindProductServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out = response.getWriter();
String select=request.getParameter("submit");
ProductService service=new ProductService();
if(select.equals("id查询")) {
try {
String condition=request.getParameter("idselect");
System.out.println("condition= "+condition);
String good=service.findOneProductService(condition);
System.out.println("good= "+good);
out.write("您所查询的商品的信息为: "+good);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(select.equals("查询")) {
List<Map<String, Object>> productLists=service.findRelaxConditionAllService(request.getParameter("select"));
out.write("<h3>您所查询的商品信息如下</h3>");
if(productLists !=null) {
out.print("<table align='center' border='1'>");
out.print("<tr>");
Set<String> colls=productLists.get(0).keySet();
for (String col:colls) {
out.print("<td>"+col+"</td>");
}
out.print("</tr>");
for(Map<String, Object> map:productLists) {
out.print("<tr>");
for (String col:colls) {
out.print("<td>"+map.get(col)+"</td>");
}
out.print("</tr>");
}
out.print("</table>");
}
}else {
out.write("非常抱歉,没有找到您需要的商品!");
}
out.write("您可以点击此处到达商品列表页: "+"<a href='lists'>商品列表页</a><br>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
LoginServlet登录
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.ProductService;
import utils.DBUtil;
/**
* Servlet implementation class LoginServlet
*/
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public LoginServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// 获取用户的操作
PrintWriter writer=response.getWriter();
// writer.write("这是loginServlet!!");
// System.out.println("这是loginServlet!!");
String operation=request.getParameter("submit");
if(operation.equals("登录")) {
String username=request .getParameter("username");
String password=request.getParameter("password");
// 如果用户名不为空值,则进行判断,从数据库中读取出密码与用户输入的密码进行匹配,看是否密码正确
if(!username.equals("")) {
ProductService service=new ProductService();
String pass;
try {
pass = service.findPasswordService(username);
System.out.println("pass= "+pass);
if(pass==null) {
response.sendRedirect("login.html");
}else if(pass.equals(password)) {
// 保存登录信息
HttpSession session=request.getSession();
session.setAttribute("username", username);
response.sendRedirect("lists");
}else {
// 密码不正确重新登录!
response.sendRedirect("login.html");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
response.sendRedirect("login.html");
}
}else if(operation.equals("注册")) {
response.sendRedirect("regist.html");
}else if(operation.equals("暂时不登录")) {
response.sendRedirect("lists");
}else {
response.sendRedirect("login.html");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ProductControl商品管理页
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import service.ProductService;
/**
* Servlet implementation class ProductControl
*/
@WebServlet("/control")
public class ProductControl extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ProductControl() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
ProductService service =new ProductService();
List<Map<String, Object>> student_list=
service.listProduct();
out.print("<a href='add.html'>增加商品</a><br>");
out.print("<a href='findProduct.html'>查询商品</a><br>");
if(student_list !=null) {
out.print("<table align='center' border='1'>");
out.print("<tr>");
Set<String> colls=student_list.get(0).keySet();
for (String col:colls) {
out.print("<td>"+col+"</td>");
}
out.print("<td>"+"操作"+"</td>");
out.print("</tr>");
for(Map<String, Object> map:student_list) {
out.print("<tr>");
for (String col:colls) {
out.print("<td>"+map.get(col)+"</td>");
}
out.print("<td><a href='edit?id="+map.get("id")+"'>修改商品 </a>"
+ "<a href='delete?id="+map.get("id")+"'>删除商品</a>"
+ "</td>");
out.print("</tr>");
}
out.print("</table>");
}
PrintWriter writer=response.getWriter();
HttpSession session=request.getSession();
ServletContext context=getServletContext();
int count = (int)context.getAttribute("userNum");
writer.write("<h1>访问人数为:</h1>"+count+"<br>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ProductListsPage商品列表页
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.User;
import service.ProductService;
/**
* Servlet implementation class ProductListsPage
*/
@WebServlet("/lists")
public class ProductListsPage extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ProductListsPage() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
// 判断用户登录,如果未登录则跳转至登录界面登录
HttpSession session = request.getSession();
String user=(String) session.getAttribute("username");
if(user==null) {
response.getWriter().write("您还未登陆,请点击 <a href='login.html'>登录</a><br>");
}
ProductService service =new ProductService();
List<Map<String, Object>> student_list=
service.listProduct();
out.print("<a href='add.html'>增加商品</a><br>");
if(student_list !=null) {
out.print("<table align='center' border='1'>");
out.print("<tr>");
Set<String> colls=student_list.get(0).keySet();
for (String col:colls) {
out.print("<td>"+col+"</td>");
}
out.print("<td>"+"操作"+"</td>");
out.print("</tr>");
for(Map<String, Object> map:student_list) {
out.print("<tr>");
for (String col:colls) {
out.print("<td>"+map.get(col)+"</td>");
}
out.print("<td><a href='edit?id="+map.get("id")+"'>修改商品 </a>"
+ "<a href='delete?id="+map.get("id")+"'>删除商品 </a>"
+"<a href='add?id="+map.get("id")+"'>加入购物车 </a>"+ "</td>");
out.print("</tr>");
}
out.print("</table>");
}
PrintWriter writer=response.getWriter();
HttpSession session1=request.getSession();
ServletContext context=getServletContext();
int count = (int)context.getAttribute("userNum");
writer.write("<h1>当前网站的访问人数为:</h1>"+count);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
RegistServlet注册
package controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import entity.User;
import service.ProductService;
import utils.DBUtil;
/**
* Servlet implementation class RegistServlet
*/
@WebServlet("/regist")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public RegistServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
String submit=request.getParameter("sub");
System.out.println(submit);
if(submit.equals("注册")) {
System.out.println("zhu ce");
String email =request.getParameter("uemail");
String username =request.getParameter("uname");
String password =request.getParameter("upwd");
String repeatPassword =request.getParameter("repeatupwd");
String sex =request.getParameter("usex");
String phone =request.getParameter("uphone");
String introduce =request.getParameter("uintroduce");
// 判断用户输入的合法性
if(username.equals("")||password.equals("")||!password.equals(repeatPassword)||email.indexOf("@")<0) {
System.out.println("用户的注册不合法,注册失败");
response.sendRedirect("regist.html");
}else {
// 检查是否用户名已经存在
ProductService service=new ProductService();
String user;
try {
user = service.findUsernameService(username);
// 判断查询出的用户名,是否为空值
if(user==null) {
// 将新注册用户的信息存入数据库
ProductService service2=new ProductService();
User adduser=new User(email,username,password,phone,introduce);
service2.addUserService(adduser);
HttpSession session = request.getSession();
session.setAttribute("username", username);
response.sendRedirect("lists");
}else {
response.sendRedirect("regist.html");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}else if(submit.equals("返回登录")) {
response.sendRedirect("login.html");
}else {
System.out.println("All falures!!!");
response.sendRedirect("regist.html");
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ShowCart订单生成
package controller;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import service.ProductService;
/**
* Servlet implementation class ShowCart
*/
@WebServlet("/showcart")
public class ShowCart extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ShowCart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
PrintWriter out=response.getWriter();
out.write("<h1>您的订单如下:</h1>");
String email =request.getParameter("uemail");
String username =request.getParameter("uname");
String phone =request.getParameter("uphone");
String address =request.getParameter("uintroduce");
out.write("姓名: "+username+"<br>");
out.write("邮箱: "+email+"<br>");
out.write("电话号码: "+phone+"<br>");
out.write("姓名收货地址: "+address+"<br>");
ProductService service =new ProductService();
List<Map<String, Object>> cart_list=
service.listCart();
if(cart_list !=null) {
out.print("<table align='center' border='1'>");
out.print("<tr>");
Set<String> colls=cart_list.get(0).keySet();
for (String col:colls) {
out.print("<td>"+col+"</td>");
}
out.print("</tr>");
for(Map<String, Object> map:cart_list) {
out.print("<tr>");
for (String col:colls) {
out.print("<td>"+map.get(col)+"</td>");
}
out.print("</tr>");
}
out.print("</table>");
}
out.write("<a href=''>点击此处进行结算</a><br>");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
ProductDao Dao层代码
package Dao;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Map;
import entity.Cart;
import entity.Product;
import entity.User;
import utils.DBUtil;
public class ProductDao {
public List<Map<String, Object>> findAll() {
return DBUtil.findAll("select * from product");
}
public List<Map<String, Object>> findRelaxConditionAll(String str) {
return DBUtil.findAll(str);
}
public List<Map<String, Object>> findAllInCart() {
return DBUtil.findAll("select * from dbcart");
}
public Product findByid(int id) {
Object object=DBUtil.findById(Product.class, id);
return object!=null?(Product)object:null;
}
public Product findByName(String name) {
Object object=DBUtil.findById(Product.class, name);
return object!=null?(Product)object:null;
}
public int addProduct(Product stu) {
return DBUtil.executeUpdate
("insert into product(id,name,description,price,stock) values(?,?,?,?,?)",
stu.getId(),
stu.getName(),
stu.getDescription(),
stu.getPrice(),
stu.getStock());
}
public int updateProduct(Product stu) {
String sql="update product set id=?,name=?,description=?,price=?,stock=? where id=?";
return DBUtil.executeUpdate(sql,
stu.getId(),
stu.getName(),
stu.getDescription(),
stu.getPrice(),
stu.getStock());
}
public int deleteProduct(int id) {
String sql="delete from product where id=?";
return DBUtil.executeUpdate(sql, id);
}
public String findPassword(String username) throws SQLException {
String sql="select password from dbuser where username='"+username+"'";
Connection conn=DBUtil.getConn();
Statement stmt;
String passString=null;
stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){ //这里必须循环遍历
passString = rs.getString("password");//返回一条记录
System.out.println(passString );
}
return passString;
}
public String findUsername(String username) throws SQLException {
String sql="select username from dbuser where username='"+username+"'";
Connection conn=DBUtil.getConn();
Statement stmt;
String userString=null;
stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){ //这里必须循环遍历
userString = rs.getString("username");//返回一条记录
System.out.println(userString );
}
return userString;
}
public int addToCart(Cart cart) {
return DBUtil.executeUpdate
("insert into dbcart(id,name,description,price,stock) values(?,?,?,?,?)",
cart.getId(),
cart.getName(),
cart.getDescription(),
cart.getPrice(),
cart.getStock());
}
public String findCartName(String cartname) throws SQLException {
String sql="select name from dbcart where name='"+cartname+"'";
Connection conn=DBUtil.getConn();
Statement stmt;
String cartnameString=null;
stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){ //这里必须循环遍历
cartnameString = rs.getString("name");//返回一条记录
System.out.println("cartname" );
}
return cartnameString;
}
// 实现对stock的加一操作
public int updateCart(Cart cart) {
String sql="update dbcart set id=?,name=?,description=?,price=?,stock=?";
return DBUtil.executeUpdate(sql,
cart.getId(),
cart.getName(),
cart.getDescription(),
cart.getPrice(),
cart.getStock()+1);
}
public int findCartStockByCartName(String cartname) throws SQLException {
String sql="select stock from dbcart where name='"+cartname+"'";
Connection conn=DBUtil.getConn();
Statement stmt;
int stock=0;
stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){ //这里必须循环遍历
stock=Integer.parseInt(rs.getString("stock"));//返回一条记录
System.out.println(stock);
}
return stock;
}
public int clearCart() {
String sql="delete from dbcart";
return DBUtil.executeUpdate(sql);
}
public String findOneProduct(String name) throws SQLException {
String sql="select * from product where name='"+name+"'";
Connection conn=DBUtil.getConn();
Statement stmt;
String cartnameString=null;
stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){ //这里必须循环遍历
cartnameString="id: "+rs.getString("id")+" name: "+rs.getString("name")+" | "+"description: "+rs.getString("description")+" | "+"price: "+rs.getString("price")+" | "+"stock: "+rs.getString("stock")+" | <br>";//返回一条记录
System.out.println(cartnameString);
}
return cartnameString;
}
public int addUser(User stu) {
return DBUtil.executeUpdate
("insert into dbuser(email,username,password,phone,introduce) values(?,?,?,?,?)",
stu.getEmail(),
stu.getUsername(),
stu.getPassword(),
stu.getPhone(),
stu.getIntroduce());
}
}
Cart购物车实体类
package entity;
public class Cart {
private int id;
private String name;
private String description;
private int price;
private int stock;
public int getStock() {
return stock;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Cart() {
}
public Cart(int id,String name, String description, int price, int stock) {
super();
this.id=id;
this.name = name;
this.description = description;
this.price = price;
this.stock = stock;
}
public void setStock(int stock) {
this.stock = stock;
}
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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
Product 商品实体类
package entity;
public class Product {
private int id;
private String name;
private String description;
private int price;
private int stock;
public int getStock() {
return stock;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Product() {
}
public Product(int id,String name, String description, int price, int stock) {
super();
this.id=id;
this.name = name;
this.description = description;
this.price = price;
this.stock = stock;
}
public void setStock(int stock) {
this.stock = stock;
}
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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
User 用户实体类
package entity;
public class User {
private String email;
private String username;
private String password;
private String phone;
private String introduce;
public User(String email, String username, String password, String phone, String introduce) {
this.email = email;
this.username = username;
this.password = password;
this.phone = phone;
this.introduce = introduce;
}
public User() {
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
}
CharactFilter过滤器
package filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* Servlet Filter implementation class CharacterFilter
*/
@WebFilter("/*")
public class CharactFilter implements Filter {
/**
* Default constructor.
*/
public CharactFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
// pass the request along the filter chain
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// System.out.println("过滤器起作用!!!");
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("Filter is initing!!!");
}
}
ContextListener监听器
package listener;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
/**
* Application Lifecycle Listener implementation class ContextListener
*
*/
@WebListener
public class ContextListener implements ServletContextListener {
/**
* Default constructor.
*/
public ContextListener() {
// TODO Auto-generated constructor stub
}
/**
* @see ServletContextListener#contextDestroyed(ServletContextEvent)
*/
public void contextDestroyed(ServletContextEvent sce) {
// TODO Auto-generated method stub
}
/**
* @see ServletContextListener#contextInitialized(ServletContextEvent)
*/
public void contextInitialized(ServletContextEvent sce) {
// TODO Auto-generated method stub
ServletContext context=sce.getServletContext();
context.setAttribute("userNum", 0);
}
}
PageListener监听器
package listener;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
/**
* Application Lifecycle Listener implementation class PageListener
*
*/
@WebListener
public class PageListener implements HttpSessionListener {
/**
* Default constructor.
*/
public PageListener() {
// TODO Auto-generated constructor stub
}
/**
* @see HttpSessionListener#sessionCreated(HttpSessionEvent)
*/
public void sessionCreated(HttpSessionEvent se) {
// TODO Auto-generated method stub
System.out.println("session被创建------------------------------------------------");
ServletContext context=se.getSession().getServletContext();
int count=(int)context.getAttribute("userNum");
count++;
context.setAttribute("userNum", count);
}
/**
* @see HttpSessionListener#sessionDestroyed(HttpSessionEvent)
*/
public void sessionDestroyed(HttpSessionEvent se) {
// TODO Auto-generated method stub
}
}
ProductService service层代码
package service;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import Dao.ProductDao;
import entity.Cart;
import entity.Product;
import entity.User;
public class ProductService {
public List<Map<String, Object>> listProduct(){
return new ProductDao().findAll();
}
public List<Map<String, Object>> findRelaxConditionAllService(String str){
return new ProductDao().findRelaxConditionAll(str);
}
public boolean editProduct(Product stu) {
int count= new ProductDao().updateProduct(stu);
return count>0;
}
public Product findByid(int id) {
return new ProductDao().findByid(id);
}
public Product findByNameService(String name) {
return new ProductDao().findByName(name);
}
public boolean deleteProduct(int id) {
int count= new ProductDao().deleteProduct(id);
return count>0;
}
public boolean addProduct(Product stu) {
int count=new ProductDao().addProduct(stu);
return count>0;
}
public String findPasswordService(String username) throws SQLException {
return new ProductDao().findPassword(username);
}
public String findUsernameService(String username) throws SQLException {
return new ProductDao().findUsername(username);
}
public boolean addToCartService(Cart cart) {
int count=new ProductDao().addToCart(cart);
return count>0;
}
public String findCartNameService(String cartname) throws SQLException {
return new ProductDao().findCartName(cartname);
}
public boolean editCartService(Cart cart) {
int count= new ProductDao().updateCart(cart);
return count>0;
}
public int findCartStockByNameService(String cartname) throws SQLException {
return new ProductDao().findCartStockByCartName(cartname);
}
public List<Map<String, Object>> listCart(){
return new ProductDao().findAllInCart();
}
public boolean clearCartService() {
int count= new ProductDao().clearCart();
return count>0;
}
public String findOneProductService(String name) throws SQLException {
return new ProductDao().findOneProduct(name);
}
public boolean addUserService(User stu) {
int count=new ProductDao().addUser(stu);
return count>0;
}
public static void main(String[] args) {
ProductService service=new ProductService();
Product product=service.findByid(1);
System.out.println(product.getName());
}
}
DBUtil工具类
package utils;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
public class DBUtil {
private static Properties dbProps = new Properties();
/**
* 读取配置文件,加载数据库驱动
*/
static {
try {
InputStream is = DBUtil.class.getResourceAsStream("/dbinfo.properties");
dbProps.load(is);
Class.forName(dbProps.getProperty("db.driver"));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接
*
* @return
*/
public static Connection getConn() {
try {
return DriverManager.getConnection(dbProps.getProperty("db.connectUrl"), dbProps.getProperty("db.user"),
dbProps.getProperty("db.pwd"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 关闭数据库连接等对象
*
* @param rs
* @param pstm
* @param con
*/
public static void close(PreparedStatement pstmt, Connection con) {
try {
if (pstmt != null)
pstmt.close();
if (con != null)
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs, PreparedStatement pstm, Connection conn) {
try {
if (rs != null)
rs.close();
close(pstm, conn);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 执行增删改
*
* @param sql
* @param params
* @return
*/
public static int executeUpdate(String sql, Object... params) {
Connection con = null;
PreparedStatement pstm = null;
try {
con = getConn();
pstm = con.prepareStatement(sql);
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++)
pstm.setObject(i+1 , params[i]);
}
return pstm.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
return -1;
} finally {
close(null, pstm, con);
}
}
/**
* 根据主键查询单个对象
*
* @param cls
* @param id
* @return
*/
public static Object findById(Class cls, Object id) {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
con = getConn();
pstm = con.prepareStatement("select * from " + cls.getSimpleName() + " where id=?");
pstm.setObject(1, id);
rs = pstm.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
Object obj = cls.newInstance();
if (rs.next()) {
for (int i = 0; i < metaData.getColumnCount(); i++) {
Field field = cls.getDeclaredField(metaData.getColumnLabel(i + 1));
field.setAccessible(true);
field.set(obj, rs.getObject(i + 1));
}
}
return obj;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
close(rs, pstm, con);
}
}
/**
* 查询某表全部数据(包含列名
*
* @param sql
* @return
*/
public static List<Map<String, Object>> findAll(String sql) {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
con = getConn();
pstm = con.prepareStatement(sql);
rs = pstm.executeQuery();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
Map<String, Object> map = new LinkedHashMap<String, Object>(metaData.getColumnCount());
for (int i = 0; i < metaData.getColumnCount(); i++) {
map.put(metaData.getColumnLabel(i + 1), rs.getObject(i + 1));
}
list.add(map);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
close(rs, pstm, con);
}
}
/**
* 根据条件查询,返回List集合,集合中存储表对应的对象
*
* @param cls
* @param sql
* @param params
* @return
*/
public static List find(Class cls, String sql, Object ... params) {
Connection con = null;
PreparedStatement pstm = null;
ResultSet rs = null;
try {
con = getConn();
pstm = con.prepareStatement(sql);
if (params != null && params.length > 0) {
for (int i = 0; i < params.length; i++)
pstm.setObject(i + 1, params[i]);
}
rs = pstm.executeQuery();
List list = new ArrayList();
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()) {
Object obj = cls.newInstance();
for (int i = 0; i < metaData.getColumnCount(); i++) {
Field field = cls.getDeclaredField(metaData.getColumnLabel(i + 1));
field.setAccessible(true);
field.set(obj, rs.getObject(i + 1));
}
list.add(obj);
}
return list;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
close(rs, pstm, con);
}
}
}
InitTableJDBC 初始化数据库,创建表…
package initJDBC;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
public class InitTableJDBC {
public static void main(String args[]) throws Exception {
Connection conn = null;
Statement stmt = null;
String connStr = "jdbc:mysql://127.0.0.1:3306?useSSL=true";
String driverStr="com.mysql.jdbc.Driver";
// 1、加载数据库的驱动程序
Class.forName(driverStr);
// 2、建立数据库的连接
conn = DriverManager.getConnection(connStr, "root", "123456");
if (!conn.isClosed()) {
System.out.println("数据库连接成功");
// 3、使用Statement执行SQL语句
stmt = conn.createStatement();
boolean flag = stmt.execute("create database demoFinally");
// 4、对执行结果进行处理
if (flag) {
System.out.println("数据库创建失败");
} else {
System.out.println("数据库创建成功");
}
stmt.execute("use demoFinally");
stmt.execute("create table if not exists user(id int auto_increment primary key ,username varchar(30) not null ,password varchar(32) not null) ;");
stmt.execute("create table dbuser(email varchar(50) primary key,username varchar(30),password varchar(32),phone varchar(20),introduce varchar(500));");
stmt.execute("create table dbcart(id int,name varchar(30) primary key,description varchar(500),price int,stock int);");
stmt.execute("create table product(id int,name varchar(30) primary key,description varchar(500),price int,stock int);");
}
}
}
add.html 商品添加页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="addproduct" >
id:<input type="text" name="id"><br>
商品名:<input type="text" name="name"><br>
商品简介:<input type="text" name="description"><br>
价格:<input type="number" name="price"><br>
数量:<input type="number" name="stock"><br>
<input type="submit" name ="submit" value="确定"><br>
<input type="submit" name ="submit" value="取消"><br>
</form>
</body>
</html>
findProduct.html 商品寻找条件确定页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<h3>您可以选择下列其中一种方法进行查询您所需要的商品</h3>
<form action="findproduct" method="get">
请输入要查询的商品名称:<input type=text name="idselect" ><br>
<input type="submit" name="submit" value="id查询"><br>
请输入查询条件(输入完整查询的SQL语句):<input type=text name="select"></br>
<input type="submit" name="submit" value="查询"><br>
</form>
</body>
</html>
login.html 登录页面
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
<input type="submit" name="submit" value="注册"><br>
<input type="submit" name="submit" value="登录"><br>
<input type="submit" name="submit" value="暂时不登录"><br>
</form>
</body>
</html>
order.html 用户订单信息填写界面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>请填写您的订单信息:</h1>
<form action="showcart" method="get">
邮箱:<input type="text" name="uemail"><br>
用户名:<input type="text" name="uname"><br>
联系电话:<input type="text" name="uphone"><br>
收货地址:<input type="text" name="uintroduce"><br>
<input type="submit" name="sub" value="提交信息"><br>
</form>
</body>
</html>
regist.html 注册页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="regist" method="get">
邮箱:<input type="text" name="uemail"><br>
用户名:<input type="text" name="uname"><br>
密码:<input type="text" name="upwd"><br>
重复密码:<input type="text" name="repeatupwd"><br>
性别:<input type="text" name="usex"><br>
联系电话:<input type="text" name="uphone"><br>
个人介绍:<input type="text" name="uintroduce"><br>
<input type="submit" name="sub" value="注册"><br>
<input type="submit" name="sub" value="返回登录"><br>
</form>
</body>
</html>
ifdelete.html 是否删除商品确定页面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3>您是否要删除这个商品?</h3>
<form action="delete" method="get">
<input type="submit" name="submit" value="是"><br>
<input type="submit" name="submit" value="否"><br>
</form>
</body>
</html>