纯jsp技术创建一个小的商品管理系统,在这之前,你应该了解JDBC,sql,Tomcat,Servlet,jsp等相关知识。
源代码(配合食用效果更佳):
-
在数据库中建表,eclipse中建Dynamic Web project,选2.5版本。
建表语句:create table jspproduct( id int primary key auto_increment, name varchar(30) not null, description varchar(100) , price double check( price >= 0 ), account int check( account >= 0 ), status int default 1 check( status in (0, 1) ), addtime date ); create table jspuser( id int(10) primary key auto_increment, username varchar(15) unique, password varchar(6) not null check( length(password)=6), realname varchar(20) not null );
-
添加servlet-api.jar和数据库驱动jar包到lib目录下,bulid path。
-
com.xx.util包,添加工具类baseDAO.java,复制它的配置文件到src目录下,更改配置文件确保可以连接到数据库。
-
com.xx.util包下新建过滤器EncodingFilter,处理中文乱码,更改web.xml文件使过滤器生效。代码:
request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8");
-
com.xx.entity包下新建Product类(标准javaBean)对应数据库中的product表,私有属性统一用包装类型。
// 定义私有属性,和数据库总jspproduct表中的字段对应,数据类型统一用包装类 private Integer id; private String name; private String description; private Double price;// 记得去修改sql建表语句 private Integer account; private Integer status; private Date addtime;// 改为timestample类型,自动添加时间 // 提供setter和getter方法 ... // 提供无参构造 ...
-
com.xx.dao包下新建ProductDAO接口,
com.xx.dao.impl包下新建其实现类ProductDAOImpl并继承BaseDAO类(操作数据库的工具类)。
-
com.xx.service新建接口ProductService。
com.xx.serviceImpl新建其实现类ProductServiceImpl,拿到ProductDAO接口的实现类ProductDAOImpl的实例化对象供后续操作:private ProductDAO productDAOImpl = new ProductDAOImpl();
-
查询功能,com.xx.servlet包下新建QueryProductListServlet,用来查询商品列表,拿到ProductService接口的实现类ProductServiceImpl的实例化对象供后续操作:
private ProductService productService = new ProductServiceImpl();
-
新建index.jsp,添加链接到QueryProductListServlet。
<a href="QueryProductListServlet">商品管理</a>
-
发布项目,测试一下链接是否有效。
-
链接有效,现在返回QueryProductListServlet来写(doGet里)查询商品列表的逻辑:
// 1. 调用service的QueryProductList()方法,返回一个商品列表 List<Product> products = productService.selectAllProduct(); // 2. 保存商品列表 request.setAttribute("products", products); // 3. 请求转发到product_list.jsp,在页面上遍历商品列表,显示商品信息。 request.getRequestDispatcher("product_list.jsp").forward(request, response);
-
完成selectAllProduct()方法,这个方法的调用顺序是:
QueryProductListServlet——>ProductService接口——>ProductServiceImpl——>ProductDAO接口——>ProductDAOImpl——>selectAllProduct()方法。
操作步骤是,在QueryProductListServlet页面,光标置于红线处(方法名),点击在接口中添加方法,跳转到ProductService接口页面,ctrl+t,找到这个接口的实现类,跳转到ProductServiceImpl实现类界面,光标置于红线处,重写方法,
return productDAO.selectAllProduct()
。(productDAO是ProductDAOImpl的实例化对象,用它直接调用这个方法。)此时仍然会报红,利用上面的步骤继续完成对ProductDAO和ProductDAOImpl的修改,最终在ProductDAOImpl重写selectAllProduct()方法:public class ProductDAOImpl extends BaseDAO implements ProductDAO { @Override public List<Product> selectAllProduct() { // TODO 调用BaseDAO里面的findList()来查询所有商品信息 return findList(Product.class, "select * from jspproduct"); } }
-
新建product_list.jsp。
-
测试,点击商品管理后是否跳转到product_list.jsp页面。
-
在product_list.jsp页面完成对商品信息的展示,加在body标签里:
<table border="1px" width="300px" height="300px" align="center"> <tr> <th>id</th> <th>商品名称</th> <th>商品描述</th> <th>商品单价</th> <th>商品数量</th> <th>商品状态</th> <th>商品上架时间</th> <th>操作</th> </tr> <% /* 获取products */ List<Product> products = (List<Product>) request.getAttribute("products"); /* 遍历 */ for (Product product : products) { %> <tr> <td><%=product.getId()%></td> <td><%=product.getName()%></td> <td><%=product.getDescription()%></td> <td><%=product.getPrice()%></td> <td><%=product.getAccount()%></td> <td><%=product.getStatus()%></td> <td><%=product.getAddtime()%></td> <td><a href="#">删除</a></td> </tr> <% } %> </table>
-
测试,往数据库中添加数据,访问index.jsp页面点击 商品管理 测试是否展示出信息。
-
商品状态我们规定一下,如果是1,就显示上架,如果是其它,就显示下架,我们在product_list.jsp里面修改一下:
<td> <% if (product.getStatus() == 1) { %> 上架 <% } else { %> 下架 <% } %> </td>
-
格式化时间,需要添加jar包:jstl.jar和standard.jar放到lib目录下,build path。
-
在product_list.jsp页面引入标签库:
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
修改表格中的时间列:
<td><fmt:formatDate value="<%=product.getAddtime() %>" pattern="yyyy-MM-dd"/> </td>
这是此时完整的product_list.jsp页面:
<%@page import="com.xx.entity.Product"%> <%@page import="java.util.List"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <table border="1px" width="800px" height="300px" align="center"> <tr> <th>id</th> <th>商品名称</th> <th>商品描述</th> <th>商品单价</th> <th>商品数量</th> <th>商品状态</th> <th>商品上架时间</th> <th>操作</th> </tr> <% /* 获取products */ List<Product> products = (List<Product>) request.getAttribute("products"); /* 遍历 */ for (Product product : products) { %> <tr align="center"> <td><%=product.getId()%></td> <td><%=product.getName()%></td> <td><%=product.getDescription()%></td> <td><%=product.getPrice()%></td> <td><%=product.getAccount()%></td> <td> <% if (product.getStatus() == 1) { %> 上架 <% } else { %> 下架 <% } %> </td> <!-- 格式化日期 --> <td><fmt:formatDate value="<%=product.getAddtime() %>" pattern="yyyy-MM-dd"/> </td> <td><a href="#">删除</a></td> </tr> <% } %> </table> </body> </html>
-
现在来做删除商品功能,首先,从product_list.jsp页面上获取当前商品的id,修改这行代码:
<td><a href="#">删除</a></td>
改为:
<td><a href="DeleteProductServlet?id=<%=product.getId()%>">删除</a></td>
相当于在product_list.jsp点击删除后会请求跳转到DeleteProductServlet页面,
?id=
是URL请求提交数据的格式,这样在DeleteProductServlet里通过request.getParameter("id");
就可以拿到这个值。 -
接着在com.xx.servlet新建DeleteProductServlet,在这个servlet里拿到ProductService接口的实现类ProductServiceImpl的实例化对象:
private ProductService productService = new ProductServiceImpl();
在doGet()方法里实现逻辑:
// 获取id Integer id = Integer.parseInt(request.getParameter("id")); // 调用deleteProductById方法 productService.deleteProductById(id); // 删除后,重定向到QueryProductListServlet展示新的商品列表 response.sendRedirect("QueryProductListServlet");
然后仿照上面新建查询方法时的步骤,完成DeleteProductServlet——ProductService——ProductServiceImpl,在这里重写DeleteProductById方法
return productService.DeleteProductById(id);
——ProductDAO——ProductDAOImpl——实现DeleteProductById()方法:@Override public void deleteProductById(Integer id) { // TODO Auto-generated method stub update("delete from jspproduct where id = ?", id); }
-
测试。
-
删除功能后,做添加商品的功能,在index.jsp页面中添加超链接:
<a href="product_add.jsp">添加商品</a>
-
新建product_add.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <!-- 新建表单,提交到AddProductServlet --> <form action="AddProductServlet" method="post"> <table border="1px" width="500px" height="300px" align="center"> <tr> <td>商品名称</td> <td><input type="text" name="name" size="25" /></td> </tr> <tr> <td>商品单价</td> <td><input type="text" name="price" size="25" /></td> </tr> <tr> <td>商品数量</td> <td><input type="text" name="account" size="25" /></td> </tr> <tr> <td>商品状态</td> <td><input type="radio" name="status" value="0" />下架 <input type="radio" name="status" value="1" checked="checked" />上架</td> </tr> <tr> <td>商品描述</td> <td><textarea rows="10" cols="30" name="description"></textarea></td> </tr> <tr> <td colspan="2"><input type="submit" value="保存" /></td> </tr> </table> </form> </body> </html>
-
com.xx.servlet下新建AddProductServlet,拿到service对象:
private ProductService productService = new ProductServiceImpl();
在doGet里面实现逻辑:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1、拿到表单中的数据 String name = request.getParameter("name"); Double price = Double.parseDouble(request.getParameter("price")); Integer account = Integer.parseInt(request.getParameter("account")); Integer status = Integer.parseInt(request.getParameter("status")); String description = request.getParameter("description"); // 2、创建商品对象,同时对商品对象赋值 Product product = new Product(); product.setName(name); product.setPrice(price); product.setAccount(account); product.setStatus(status); product.setDescription(description); // 3、调用添加方法 productService.saveProduct(); // 4、请求重定向到QueryProductListServlet response.sendRedirect("QueryProductListServlet"); }
然后仿照上面的方法使得方法的调用完整,最后在PproductDAOImpl中实现:
@Override public void saveProduct(Product product) { // TODO Auto-generated method stub // id和time赋null就可以 update("insert into jspproduct values(null,?,?,?,?,?,null)", product.getName(), product.getDescription(),product.getPrice(), product.getAccount(), product.getStatus()); }
-
测试。添加商品。
-
现在来做修改功能:思路是,点击修改,先根据id把这个商品的信息展示出来,然后直接在上面修改,点击保存。
在product_list.jsp页面中添加修改链接:
<td><a href="DeleteProductServlet?id=<%=product.getId()%>">删除</a></td>
改为:
<td> <a href="DeleteProductServlet?id=<%=product.getId()%>">删除</a> <a href="QueryProductByIdServlet?id=<%=product.getId()%>">修改</a> </td>
-
com.xx.servlet下新建QueryProductByIdServlet:
package com.xx.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xx.entity.Product; import com.xx.service.ProductService; import com.xx.service.impl.ProductServiceImpl; /** * Servlet implementation class QueryProductByIdServlet */ public class QueryProductByIdServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ProductService productService = new ProductServiceImpl(); /** * @see HttpServlet#HttpServlet() */ public QueryProductByIdServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获取id Integer id = Integer.parseInt(request.getParameter("id")); // 2.根据id查询商品信息,返回商品对象 Product product = productService.selectProductById(id); // 3.保存商品对象 request.setAttribute("product", product); // 4.请求转发到product_update.jsp request.getRequestDispatcher("product_update.jsp").forward(request, response); } /** * @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); } }
-
完成selectProductById方法的调用,最终在ProductDAOImpl:
@Override public Product selectProductById(Integer id) { // TODO Auto-generated method stub return findOne(Product.class, "select * from jspproduct where id=?", id); }
-
新建product_update.jsp页面:
<%@page import="com.xx.entity.Product"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% Product product = (Product) request.getAttribute("product"); %> <form action="UpdateProductServlet" method="post"> <input type="hidden" name="id" value="<%=product.getId()%>"> <table border="1" width="100%" height="100%" align="center"> <tr> <td>商品名称</td> <td><input type="text" name="name" size="25" value="<%=product.getName()%>" /></td> </tr> <tr> <td>商品单价</td> <td><input type="text" name="price" size="25" value="<%=product.getPrice()%>" /></td> </tr> <tr> <td>商品数量</td> <td><input type="text" name="account" size="25" value="<%=product.getAccount()%>" /></td> </tr> <tr> <td>商品状态</td> <td><input type="radio" name="status" value="0" />下架 <input type="radio" name="status" value="1" checked="checked" />上架</td> </tr> <tr> <td>商品描述</td> <td><textarea rows="10" cols="30" name="description"><%=product.getDescription()%></textarea> </td> </tr> <tr> <td colspan="2"><input type="submit" value="保存" /></td> </tr> </table> </form> </body> </html>
-
com.xx.servlet新建UpdateProductServlet:
package com.xx.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.xx.entity.Product; import com.xx.service.ProductService; import com.xx.service.impl.ProductServiceImpl; /** * Servlet implementation class UpdateProductServlet */ public class UpdateProductServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ProductService productService = new ProductServiceImpl(); /** * @see HttpServlet#HttpServlet() */ public UpdateProductServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.接收页面上输入的商品信息 Integer id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); String description = request.getParameter("description"); Double price = Double.parseDouble(request.getParameter("price")); Integer account = Integer.parseInt(request.getParameter("account")); Integer status = Integer.parseInt(request.getParameter("status")); // 2.创建商品对象,同时对商品对象的属性赋值 Product product = new Product(); product.setName(name); product.setAccount(account); product.setDescription(description); product.setPrice(price); product.setStatus(status); product.setId(id); // 3.调用service的保存商品的方法 productService.updateProduct(product); // 4.请求重定向到查询的servlet response.sendRedirect("QueryProductListServlet"); } /** * @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); } }
-
完成updateProduct的调用,最终在ProductDAOImpl中实现:
@Override public void updateProduct(Product product) { // TODO Auto-generated method stub update("update jspproduct set name=?,description=?,price=?,account=?,status=? where id=?",product.getName(),product.getDescription(),product.getPrice(),product.getAccount(),product.getStatus(),product.getId()); }
-
-
至此,列表显示,删除,添加,修改的功能都完成了。