一、MVC开发模式和JavaEE经典三层结构
1.JSP开发模式一: jsp(接收请求,响应请求,展示数据)+javabean(处理业务逻辑)
javaBean:可复用的java组件 -user -userDao
自己写的普通java类都可以称之为javaBean
user 实体bean,用来封装对象用的
userDao 业务bean,专门用来处理业务逻辑的
2.JSP开发模式二:Servlet(接收请求,转发request传递数据)+jsp(展示数据,响应给浏览器)+javaBean(处理业务逻辑)
3.JSP开发模式二的处理过程:
Servlet接收请求,调用javaBean处理业务,将业务处理结果返回给Servlet,然后Servlet转发request传递数据给JSP,最后JSP展示数据,并响应给浏览器
4.MVC模式结合JavaWeb进行开发的一套标准模型
M(Model模型) ---javaBean
V(View视图) ---jsp
C(Controller控制器) ---servlet
5.使用MVC开发模式怎么去做??
//将数据保存到request域对象中,并转发到jsp页面(一次请求范围内)
request.setAttribute("userList",userList);
request.getRequestDispatcher("/userList.jsp").forward(request,response);
//jsp只取出数据展示出来
List<User> userList=(List<User>)request.getAttribute("userlist");
//遍历输出
for (User user : userList) {
out.println("<tr>");
out.println("<td>"+ user.getId()+"</td>");
out.println("<td>"+ user.getUsername()+"</td>");
out.println("<td>"+ user.getPassword()+"</td>");
out.println("</tr>");
}
MVC侧重点:将前端代码和真正处理业务的逻辑分开(开发模式)
那么对于后端程序员而言--如何进行分工合作协同开发??
6.JavaEE经典三层结构---将Model模型分为了service和dao(写代码的一种约定)
1.Service层---处理业务逻辑,控制业务流程
2.Dao层---数据操作代码(不包含任何业务处理代码) 只封装对数据库的基本的增删改查代码
3.Web层---(Servlet和jsp)---和客户端交互
7.项目开发的基本流程
1.需求分析(老板 产品经理)
2.设计阶段 1个月
产品经理(项目流程)项目原型图
UI(用户设计师)/UE(用户体验师)
数据库的设计(DBA)
开发技术(项目经理)
前端 Android IOS
后端 Java
3.开发阶段 2-3个月
前端
Android
IOS
微信小程序
Java
4.测试
黑盒 白盒
5.运维
项目发布和运行环境信息的维护
二、商城后台管理系统的项目环境搭建
1.前端、服务器、数据库需要用到的技术点和开发工具
bootstrap--前端
servlet+jsp+beanutils+jdbctemplate+druid+jstl--后端
mysql+sqlyog--数据库
2.在IDEA中创建web项目,在web目录下引入bootstrap的三个文件css/js/fonts
链接:https://pan.baidu.com/s/1fE-y5s7nvJ3m3Ck2V_q21Q
提取码:uo45
复制这段内容后打开百度网盘手机App,操作更方便哦
3.在WEB-INF下新建一个lib文件夹,将jar包全部复制粘贴到里面,然后添加项目依赖
链接:https://pan.baidu.com/s/1yxz_ZdWnQfT1DOqyhuQ5HQ
提取码:a5pg
4.新建mysql数据库--shop,右击shop,导入,从SQL转储文件导入数据库
5.在src下创建五个包结构,同时在src下导入druid.properties配置文件
链接:https://pan.baidu.com/s/1x98erP3f98JC62BifmYF2A
提取码:rs41
复制这段内容后打开百度网盘手机App,操作更方便哦
dao---数据操作包(不包含任何业务处理代码) 只封装对数据库的基本的增删改查代码
domain---实体类包
service---处理业务逻辑,控制业务流程
util---工具类包
web---Servlet,接收请求,转发request传递数据
6.在domain下创建实体类Product.java
package com.bianyiit.domain;
import java.io.Serializable;
import java.util.Date;
public class Product implements Serializable {
private int pid;
private String pname;
private double market_price;
private double shop_price;
private String pimage;
private Date pdate;
private int is_hot;
private String pdesc;
private int pflag;
private int cid;
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public double getMarket_price() {
return market_price;
}
public void setMarket_price(double market_price) {
this.market_price = market_price;
}
public double getShop_price() {
return shop_price;
}
public void setShop_price(double shop_price) {
this.shop_price = shop_price;
}
public String getPimage() {
return pimage;
}
public void setPimage(String pimage) {
this.pimage = pimage;
}
public Date getPdate() {
return pdate;
}
public void setPdate(Date pdate) {
this.pdate = pdate;
}
public int getIs_hot() {
return is_hot;
}
public void setIs_hot(int is_hot) {
this.is_hot = is_hot;
}
public String getPdesc() {
return pdesc;
}
public void setPdesc(String pdesc) {
this.pdesc = pdesc;
}
public int getPflag() {
return pflag;
}
public void setPflag(int pflag) {
this.pflag = pflag;
}
public int getCid() {
return cid;
}
public void setCid(int cid) {
this.cid = cid;
}
@Override
public String toString() {
return "Product{" +
"pid=" + pid +
", pname='" + pname + '\'' +
", market_price=" + market_price +
", shop_price=" + shop_price +
", pimage='" + pimage + '\'' +
", pdate=" + pdate +
", is_hot=" + is_hot +
", pdesc='" + pdesc + '\'' +
", pflag=" + pflag +
", cid=" + cid +
'}';
}
}
7.在util创建druid的工具类DrulidUtils,在src下导入druid的配置文件
链接:https://pan.baidu.com/s/1xQYMcq1rtq8i358IwgqOUw
提取码:427w
package com.bianyiit.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
//Druid连接池的工具类
/*
* 1.获取连接池对象
* 2.获取连接对象
* 3.归还连接对象的方法
* 4.静态代码块(因为在创建连接池对象之前就需要加载好配置文件中的所有信息)
* */
public class DruidUtils {
private static DataSource ds;
//用来加载配置文件并创建好一个连接池对象
static {
Properties ps=new Properties();
try {
ps.load(DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties"));
ds = DruidDataSourceFactory.createDataSource(ps);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接对象的方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//有没有必要提供一个获取连接池对象的方法??---框架中可能只需要连接池对象,不需要连接对象
public static DataSource getDataSource(){
return ds;
}
//归还连接对象的方法
//有一种是有结果集的连接(查询),
public static void close(PreparedStatement psmt, Connection con, ResultSet rs){
try {
if(psmt!=null){
psmt.close();
psmt=null;
}
if(con!=null){
con.close();
con=null;
}
if(rs!=null){
rs.close();
rs=null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//有一种没有结果集的连接(增删改)
public static void close(PreparedStatement psmt, Connection con){
try {
if(psmt!=null){
psmt.close();
psmt=null;
}
if(con!=null){
con.close();
con=null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
三、商城后台管理系统之普通查询
1.在web目录下创建index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
<title>商城首页</title>
</head>
<body>
<div class="container">
<h1>编译商城后台管理系统</h1><br>
<a class="btn btn-default" href="${pageContext.request.contextPath}/findAll" role="button">查询所有商品</a>
<a class="btn btn-default" href="${pageContext.request.contextPath}/pageQuery?currentPage=1&pageSize=10" role="button">分页查询商品</a>
</div>
</body>
</html>
结果演示截图:
2.在web目录下创建FindAllServlet(注意这里不再是创建普通java类了,而是创建一个Servlet)
package com.bianyiit.web;
import com.bianyiit.domain.Product;
import com.bianyiit.service.ProductService;
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 java.io.IOException;
import java.util.List;
@WebServlet("/findAll")
public class FindAllServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ProductService productService = new ProductService();
List<Product> productList=productService.findAll();
request.setAttribute("productList",productList);
request.getRequestDispatcher("/productlist.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3.在service下创建一个ProductService,在这个service中只处理业务逻辑,控制业务流程,不操作数据库
package com.bianyiit.service;
import com.bianyiit.dao.ProductDao;
import com.bianyiit.domain.PageBean;
import com.bianyiit.domain.Product;
import java.util.List;
public class ProductService {
ProductDao productDao = new ProductDao();
public List<Product> findAll() {
List<Product> productList=productDao.findAll();
return productList;
}
}
4.在dao下新建一个Product类(不包含任何业务处理代码) 只封装对数据库的基本的增删改查代码
package com.bianyiit.dao;
import com.bianyiit.domain.Product;
import com.bianyiit.util.DruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
import java.util.List;
public class ProductDao {
private JdbcTemplate template=new JdbcTemplate(DruidUtils.getDataSource());
public List<Product> findAll() {
String sql="select * from product";
List<Product> query = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
return query;
}
}
5.上述代码完成之后,回到FindAllServet,我们已经拿到了数据库中所有的商品数据,那么下一步就是在web目录下创建productlist.jsp页面,在这个页面将数据展示出来
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h1>商品的列表页面</h1>
<table class="table table-bordered table table-hover">
<tr>
<td colspan="8">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">名称</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="请输入查询的商品">
</div>
<button class="btn btn-info" type="submit" class="btn btn-default">查询</button>
<button class="btn btn-success" type="submit" class="btn btn-default">添加</button>
<button class="btn btn-warning" type="submit" class="btn btn-default">删除</button>
</form>
</td>
</tr>
<tr>
<th>序号</th>
<th><input type="checkbox"></th>
<th>商品名称</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
<c:forEach var="product" items="${productList}" varStatus="status">
<tr>
<td>${status.count}</td>
<td></td>
<td>${product.pname}</td>
<td>${product.market_price}</td>
<td>${product.shop_price}</td>
<td>${product.is_hot==1?"是":"否"}</td>
<td>${product.pflag==1?"是":"否"}</td>
<td>修改</td>
</tr>
</c:forEach>
</table>
</div>
</body>
</html>
6.效果展示
三、商城后台管理系统之分页查询
SELECT * FROM product LIMIT 0,10;
SELECT * FROM product LIMIT 10,10;
SELECT * FROM product LIMIT 20,10; //List数据
SELECT COUNT(pid) FROM product //查询总记录数
Math.ceil((double)count/10); //总页数
起始位置=(当前页码-1)*每页条数;
第一页的起始位置=(页码1-1)*10=0
第二页的起始位置=(页码2-1)*10=10
浏览器只要传入当前页码/每页条数--->服务器就可以显示起始位置开始的10条数据
使用PageBean--封装总页数 当前页 每页的展示条数 总记录条数 List数据
1.同样在index.jsp页面中添加一行关于分页查询的html代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
<title>商城首页</title>
</head>
<body>
<div class="container">
<h1>编译商城后台管理系统</h1><br>
<a class="btn btn-default" href="${pageContext.request.contextPath}/findAll" role="button">查询所有商品</a>
<a class="btn btn-default" href="${pageContext.request.contextPath}/pageQuery?currentPage=1&pageSize=10" role="button">分页查询商品</a>
</div>
</body>
</html>
2.在web目录下创建PageQueryServlet(注意这里不再是创建普通java类了,而是创建一个Servlet)
package com.bianyiit.web;
import com.bianyiit.domain.PageBean;
import com.bianyiit.domain.Product;
import com.bianyiit.service.ProductService;
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 java.io.IOException;
@WebServlet("/pageQuery")
public class PageQueryServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String currentPage = request.getParameter("currentPage");
String pageSize = request.getParameter("pageSize");
/*调用service处理业务逻辑*/
ProductService service = new ProductService();
PageBean<Product> pageBean=service.findPage(currentPage,pageSize);
/*3.将数据保存到request域对象中转发到jsp页面*/
request.setAttribute("page",pageBean);
request.getRequestDispatcher("/pagelist.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3.在domain下创建PageBean实体类,封装了当前页,每页条数,总记录数,总页数,List集合
package com.bianyiit.domain;
import java.util.List;
public class PageBean<T> {
private int currentPage; //当前页
private int pageSize; //每页条数
private int totalCount;//总记录数
private int pageCount;//总页数
private List<T> 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 int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageCount() {
return pageCount;
}
public void setPageCount(int pageCount) {
this.pageCount = pageCount;
}
public List<T> getList() {
return list;
}
public void setList(List<T> list) {
this.list = list;
}
@Override
public String toString() {
return "PageBean{" +
"currentPage=" + currentPage +
", pageSize=" + pageSize +
", totalCount=" + totalCount +
", pageCount=" + pageCount +
", list=" + list +
'}';
}
}
4.继续在ProductService中处理业务逻辑,控制业务流程,不操作数据库
package com.bianyiit.service;
import com.bianyiit.dao.ProductDao;
import com.bianyiit.domain.PageBean;
import com.bianyiit.domain.Product;
import java.util.List;
public class ProductService {
ProductDao productDao = new ProductDao();
public List<Product> findAll() {
List<Product> productList=productDao.findAll();
return productList;
}
public PageBean<Product> findPage(String scurrentPage, String spageSize) {
/*校验数据是否正确*/
int pageSize=10;
try {
pageSize = Integer.parseInt(spageSize);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
int currentPage=1;
try {
currentPage = Integer.parseInt(scurrentPage);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
/*完成分类的业务逻辑*/
PageBean<Product> PageBean = new PageBean<>();
//设置每页条数
PageBean.setPageSize(pageSize);
//当前页数
PageBean.setCurrentPage(currentPage);
//总记录数
int totalCount = productDao.findCount();
PageBean.setTotalCount(totalCount);
//总页数
int pageCount=(int)Math.ceil((double)totalCount/pageSize);
PageBean.setPageCount(pageCount);
//list数据
int start=(currentPage-1)*pageSize;
List<Product> list=productDao.findPage(start,pageSize);
PageBean.setList(list);
return PageBean;
}
}
5.继续在dao下的Product类中完成ProductService中需要我们去操作数据库的方法
package com.bianyiit.dao;
import com.bianyiit.domain.Product;
import com.bianyiit.util.DruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
import java.util.List;
public class ProductDao {
private JdbcTemplate template=new JdbcTemplate(DruidUtils.getDataSource());
public List<Product> findAll() {
String sql="select * from product";
List<Product> query = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
return query;
}
public int findCount() {
String sql="SELECT count(pid) FROM product";
Integer count = template.queryForObject(sql, Integer.class);
return count;
}
public List<Product> findPage(int start, int pageSize) {
String sql="select * from product limit ?,?";
List<Product> productlist = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class), start, pageSize);
return productlist;
}
}
6.上述代码完成之后,回到FindAllServet,我们已经拿到了分页查询需要用到的PageBean对象了,那么下一步就是在web目录下创建pagelist.jsp页面,在这个页面将分页的数据展示出来
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
<script>
window.onload=function () {
document.getElementById("selectAll").onclick=function () {
var ischecked=document.getElementById("selectAll").checked;
var items = document.getElementsByName("select_item");
for (var i = 0; i < items.length ; i++) {
items[i].checked=ischecked;
}
}
/*document.getElementById("add").onclick=function () {
document.getElementById("addProduct_form").onsubmit();
}*/
document.getElementById("btn_deleteAll").onclick = function () {
document.getElementById("list_form").submit();
}
}
function deleteProduct(pid) {
var flag=confirm("是否确认删除?");
if(flag){
location.href="${pageContext.request.contextPath}/deleteProduct?pid="+pid;
}
}
</script>
</head>
<body>
<div class="container">
<h1>商品的列表页面</h1>
<table class="table table-bordered table table-hover">
<tr>
<td colspan="8">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">名称</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="请输入查询的商品">
</div>
<button class="btn btn-info" class="btn btn-default">查询</button>
<button class="btn btn-success" class="btn btn-default">添加</button>
<button class="btn btn-warning" id="btn_deleteAll">删除</button>
</form>
</td>
</tr>
<tr>
<th>序号</th>
<th><input type="checkbox" id="selectAll"></th>
<th>商品名称</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
<form id="list_form" action="${pageContext.request.contextPath}/deleteAll" method="post">
<c:forEach var="product" items="${page.list}" varStatus="status">
<tr>
<td>${status.count}</td>
<td><input type="checkbox" name="select_item" value="${product.pid}"></td>
<td>${product.pname}</td>
<td>${product.market_price}</td>
<td>${product.shop_price}</td>
<td>${product.is_hot==1?"是":"否"}</td>
<td>${product.pflag==1?"已下架":"未下架"}</td>
<td>
<a class="btn btn-default">修改</a>
<a href="#" class="btn btn-default" onclick="deleteProduct(${product.pid})">删除</a>
</td>
</tr>
</c:forEach>
</form>
<tr>
<td colspan="8">
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${page.currentPage > 1}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage-1}&pageSize=10"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach var="i" begin="1" end="${page.pageCount}">
<c:if test="${i == page.currentPage}">
<li class="active"><a href="#">${i}</a></li>
</c:if>
<c:if test="${i != page.currentPage}">
<li><a href="${pageContext.request.contextPath}/pageQuery?currentPage=${i}&pageSize=10">${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${page.currentPage < page.pageCount}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage+1}&pageSize=10"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li>
<span>
共 ${page.totalCount}条
共 ${page.pageCount}页
</span>
</li>
</ul>
</nav>
</td>
</tr>
</table>
</div>
</body>
</html>
6.效果展示
三、商城后台管理系统之单点删除
1.在pagelist.jsp页面中继续进行修改用以实现单点删除
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
<script>
window.onload=function () {
document.getElementById("selectAll").onclick=function () {
var ischecked=document.getElementById("selectAll").checked;
var items = document.getElementsByName("select_item");
for (var i = 0; i < items.length ; i++) {
items[i].checked=ischecked;
}
}
/*document.getElementById("add").onclick=function () {
document.getElementById("addProduct_form").onsubmit();
}*/
document.getElementById("btn_deleteAll").onclick = function () {
document.getElementById("list_form").submit();
}
}
function deleteProduct(pid) {
var flag=confirm("是否确认删除?");
if(flag){
location.href="${pageContext.request.contextPath}/deleteProduct?pid="+pid;
}
}
</script>
</head>
<body>
<div class="container">
<h1>商品的列表页面</h1>
<table class="table table-bordered table table-hover">
<tr>
<td colspan="8">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">名称</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="请输入查询的商品">
</div>
<button class="btn btn-info" class="btn btn-default">查询</button>
<button class="btn btn-success" class="btn btn-default">添加</button>
<button class="btn btn-warning" id="btn_deleteAll">删除</button>
</form>
</td>
</tr>
<tr>
<th>序号</th>
<th><input type="checkbox" id="selectAll"></th>
<th>商品名称</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
<form id="list_form" action="${pageContext.request.contextPath}/deleteAll" method="post">
<c:forEach var="product" items="${page.list}" varStatus="status">
<tr>
<td>${status.count}</td>
<td><input type="checkbox" name="select_item" value="${product.pid}"></td>
<td>${product.pname}</td>
<td>${product.market_price}</td>
<td>${product.shop_price}</td>
<td>${product.is_hot==1?"是":"否"}</td>
<td>${product.pflag==1?"已下架":"未下架"}</td>
<td>
<a class="btn btn-default">修改</a>
<a href="#" class="btn btn-default" onclick="deleteProduct(${product.pid})">删除</a>
</td>
</tr>
</c:forEach>
</form>
<tr>
<td colspan="8">
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${page.currentPage > 1}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage-1}&pageSize=10"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach var="i" begin="1" end="${page.pageCount}">
<c:if test="${i == page.currentPage}">
<li class="active"><a href="#">${i}</a></li>
</c:if>
<c:if test="${i != page.currentPage}">
<li><a href="${pageContext.request.contextPath}/pageQuery?currentPage=${i}&pageSize=10">${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${page.currentPage < page.pageCount}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage+1}&pageSize=10"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li>
<span>
共 ${page.totalCount}条
共 ${page.pageCount}页
</span>
</li>
</ul>
</nav>
</td>
</tr>
</table>
</div>
</body>
</html>
2.在web下新建一个DeleteProductServlet用来接收单点删除的请求
package com.bianyiit.web;
import com.bianyiit.service.ProductService;
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 java.io.IOException;
@WebServlet("/deleteProduct")
public class DeleteProductServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String pid = request.getParameter("pid");
ProductService service = new ProductService();
service.deleteByPid(pid);
response.sendRedirect(request.getContextPath()+"/pageQuery");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
3.继续在ProductService中处理业务逻辑,控制业务流程,不操作数据库
package com.bianyiit.service;
import com.bianyiit.dao.ProductDao;
import com.bianyiit.domain.PageBean;
import com.bianyiit.domain.Product;
import java.util.List;
public class ProductService {
ProductDao productDao = new ProductDao();
public List<Product> findAll() {
List<Product> productList=productDao.findAll();
return productList;
}
public PageBean<Product> findPage(String scurrentPage, String spageSize) {
/*校验数据是否正确*/
int pageSize=10;
try {
pageSize = Integer.parseInt(spageSize);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
int currentPage=1;
try {
currentPage = Integer.parseInt(scurrentPage);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
/*完成分类的业务逻辑*/
PageBean<Product> PageBean = new PageBean<>();
//设置每页条数
PageBean.setPageSize(pageSize);
//当前页数
PageBean.setCurrentPage(currentPage);
//总记录数
int totalCount = productDao.findCount();
PageBean.setTotalCount(totalCount);
//总页数
int pageCount=(int)Math.ceil((double)totalCount/pageSize);
PageBean.setPageCount(pageCount);
//list数据
int start=(currentPage-1)*pageSize;
List<Product> list=productDao.findPage(start,pageSize);
PageBean.setList(list);
return PageBean;
}
public void deleteByPid(String pid) {
productDao.deleteByPid(pid);
}
}
4.继续在dao下的Product类中完成ProductService中需要我们去操作数据库的方法
package com.bianyiit.dao;
import com.bianyiit.domain.Product;
import com.bianyiit.util.DruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
import java.util.List;
public class ProductDao {
private JdbcTemplate template=new JdbcTemplate(DruidUtils.getDataSource());
public List<Product> findAll() {
String sql="select * from product";
List<Product> query = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
return query;
}
public int findCount() {
String sql="SELECT count(pid) FROM product";
Integer count = template.queryForObject(sql, Integer.class);
return count;
}
public List<Product> findPage(int start, int pageSize) {
String sql="select * from product limit ?,?";
List<Product> productlist = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class), start, pageSize);
return productlist;
}
public void deleteByPid(String pid) {
String sql="delete from product where pid=?";
template.update(sql, pid);
}
}
5.在DeleteProductServlet中处理完删除操作之后的业务走向
6.同样在pagelist.jsp中展示删除商品之后重新请求的分页的页面,效果展示如下
四、商城后台管理系统之批量删除
1.在pagelist.jsp页面中继续进行修改用以实现单点删除
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
<script>
window.onload=function () {
document.getElementById("selectAll").onclick=function () {
var ischecked=document.getElementById("selectAll").checked;
var items = document.getElementsByName("select_item");
for (var i = 0; i < items.length ; i++) {
items[i].checked=ischecked;
}
}
/*document.getElementById("add").onclick=function () {
document.getElementById("addProduct_form").onsubmit();
}*/
document.getElementById("btn_deleteAll").onclick = function () {
document.getElementById("list_form").submit();
}
}
function deleteProduct(pid) {
var flag=confirm("是否确认删除?");
if(flag){
location.href="${pageContext.request.contextPath}/deleteProduct?pid="+pid;
}
}
</script>
</head>
<body>
<div class="container">
<h1>商品的列表页面</h1>
<table class="table table-bordered table table-hover">
<tr>
<td colspan="8">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">名称</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="请输入查询的商品">
</div>
<button class="btn btn-info" class="btn btn-default">查询</button>
<button class="btn btn-success" class="btn btn-default">添加</button>
<button class="btn btn-warning" id="btn_deleteAll">删除</button>
</form>
</td>
</tr>
<tr>
<th>序号</th>
<th><input type="checkbox" id="selectAll"></th>
<th>商品名称</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
<form id="list_form" action="${pageContext.request.contextPath}/deleteAll" method="post">
<c:forEach var="product" items="${page.list}" varStatus="status">
<tr>
<td>${status.count}</td>
<td><input type="checkbox" name="select_item" value="${product.pid}"></td>
<td>${product.pname}</td>
<td>${product.market_price}</td>
<td>${product.shop_price}</td>
<td>${product.is_hot==1?"是":"否"}</td>
<td>${product.pflag==1?"已下架":"未下架"}</td>
<td>
<a class="btn btn-default">修改</a>
<a href="#" class="btn btn-default" onclick="deleteProduct(${product.pid})">删除</a>
</td>
</tr>
</c:forEach>
</form>
<tr>
<td colspan="8">
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${page.currentPage > 1}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage-1}&pageSize=10"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach var="i" begin="1" end="${page.pageCount}">
<c:if test="${i == page.currentPage}">
<li class="active"><a href="#">${i}</a></li>
</c:if>
<c:if test="${i != page.currentPage}">
<li><a href="${pageContext.request.contextPath}/pageQuery?currentPage=${i}&pageSize=10">${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${page.currentPage < page.pageCount}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage+1}&pageSize=10"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li>
<span>
共 ${page.totalCount}条
共 ${page.pageCount}页
</span>
</li>
</ul>
</nav>
</td>
</tr>
</table>
</div>
</body>
</html>
2.全选和全不选的效果演示
3.如何对全选中的数据进行批量删除
4.在web下新建一个DeleteAllServlet用来接收批量删除的请求
package com.bianyiit.web;
import com.bianyiit.service.ProductService;
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 java.io.IOException;
import java.util.HashSet;
@WebServlet("/deleteAll")
public class DeleteAllServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] pids = request.getParameterValues("select_item");
ProductService service = new ProductService();
service.deleteBatch(pids);
response.sendRedirect(request.getContextPath()+"/pageQuery");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
5.继续在ProductService中处理业务逻辑,控制业务流程,不操作数据库
package com.bianyiit.service;
import com.bianyiit.dao.ProductDao;
import com.bianyiit.domain.PageBean;
import com.bianyiit.domain.Product;
import java.util.List;
public class ProductService {
ProductDao productDao = new ProductDao();
public List<Product> findAll() {
List<Product> productList=productDao.findAll();
return productList;
}
public PageBean<Product> findPage(String scurrentPage, String spageSize) {
/*校验数据是否正确*/
int pageSize=10;
try {
pageSize = Integer.parseInt(spageSize);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
int currentPage=1;
try {
currentPage = Integer.parseInt(scurrentPage);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
/*完成分类的业务逻辑*/
PageBean<Product> PageBean = new PageBean<>();
//设置每页条数
PageBean.setPageSize(pageSize);
//当前页数
PageBean.setCurrentPage(currentPage);
//总记录数
int totalCount = productDao.findCount();
PageBean.setTotalCount(totalCount);
//总页数
int pageCount=(int)Math.ceil((double)totalCount/pageSize);
PageBean.setPageCount(pageCount);
//list数据
int start=(currentPage-1)*pageSize;
List<Product> list=productDao.findPage(start,pageSize);
PageBean.setList(list);
return PageBean;
}
public void deleteByPid(String pid) {
productDao.deleteByPid(pid);
}
public void deleteBatch(String[] pids) {
if(pids!=null||pids.length>0){
for (int i = 0; i < pids.length ; i++) {
deleteByPid(pids[i]);
}
}
}
}
6.继续在dao下的Product类中完成ProductService中需要我们去操作数据库的方法
package com.bianyiit.dao;
import com.bianyiit.domain.Product;
import com.bianyiit.util.DruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
import java.util.List;
public class ProductDao {
private JdbcTemplate template=new JdbcTemplate(DruidUtils.getDataSource());
public List<Product> findAll() {
String sql="select * from product";
List<Product> query = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
return query;
}
public int findCount() {
String sql="SELECT count(pid) FROM product";
Integer count = template.queryForObject(sql, Integer.class);
return count;
}
public List<Product> findPage(int start, int pageSize) {
String sql="select * from product limit ?,?";
List<Product> productlist = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class), start, pageSize);
return productlist;
}
public void deleteByPid(String pid) {
String sql="delete from product where pid=?";
template.update(sql, pid);
}
}
5.在DeleteAllServlet中处理完删除操作之后的业务走向
6.同样在pagelist.jsp中展示删除全选的商品之后重新请求的分页的页面,效果展示如下
五、商城后台管理系统之添加商品
1.在pagelist.jsp页面中继续进行修改用以实现添加商品
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- jQuery (Bootstrap 的所有 JavaScript 插件都依赖 jQuery,所以必须放在前边) -->
<script src="js/jquery-3.2.1.min.js"></script>
<!-- 加载 Bootstrap 的所有 JavaScript 插件。你也可以根据需要只加载单个插件。 -->
<script src="js/bootstrap.min.js"></script>
<script>
window.onload=function () {
document.getElementById("selectAll").onclick=function () {
var ischecked=document.getElementById("selectAll").checked;
var items = document.getElementsByName("select_item");
for (var i = 0; i < items.length ; i++) {
items[i].checked=ischecked;
}
}
$('#addProduct').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget) // Button that triggered the modal
var recipient = button.data('whatever') // Extract info from data-* attributes
// If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
// Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
var modal = $(this)
modal.find('.modal-title').text('添加商品')
})
document.getElementById("add").onclick=function () {
document.getElementById("addProduct_form").submit();
}
document.getElementById("btn_deleteAll").onclick = function () {
document.getElementById("list_form").submit();
}
}
function deleteProduct(pid) {
var flag=window.confirm("是否确认删除?");
if(flag){
location.href="${pageContext.request.contextPath}/deleteProduct?pid="+pid;
}
}
</script>
</head>
<body>
<div class="container">
<h1>商品的列表页面</h1>
<table class="table table-bordered table table-hover">
<tr>
<td colspan="8">
<form class="form-inline">
<div class="form-group">
<label for="exampleInputName2">名称</label>
<input type="text" class="form-control" id="exampleInputName2" placeholder="请输入查询的商品">
</div>
<button class="btn btn-info" class="btn btn-default">查询</button>
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#addProduct">
添加
</button>
<button class="btn btn-warning" id="btn_deleteAll">删除</button>
</form>
</td>
</tr>
<tr>
<th>序号</th>
<th><input type="checkbox" id="selectAll"></th>
<th>商品名称</th>
<th>市场价格</th>
<th>商品价格</th>
<th>是否热门</th>
<th>是否下架</th>
<th>操作</th>
</tr>
<form id="list_form" action="${pageContext.request.contextPath}/deleteAll" method="post">
<c:forEach var="product" items="${page.list}" varStatus="status">
<tr>
<td>${status.count}</td>
<td><input type="checkbox" name="select_item" value="${product.pid}"></td>
<td>${product.pname}</td>
<td>${product.market_price}</td>
<td>${product.shop_price}</td>
<td>${product.is_hot==1?"是":"否"}</td>
<td>${product.pflag==1?"已下架":"未下架"}</td>
<td>
<a class="btn btn-default">修改</a>
<a href="#" class="btn btn-default" onclick="deleteProduct(${product.pid})">删除</a>
</td>
</tr>
</c:forEach>
</form>
<tr>
<td colspan="8">
<nav aria-label="Page navigation">
<ul class="pagination">
<c:if test="${page.currentPage > 1}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage-1}&pageSize=10"
aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
</c:if>
<c:forEach var="i" begin="1" end="${page.pageCount}">
<c:if test="${i == page.currentPage}">
<li class="active"><a href="#">${i}</a></li>
</c:if>
<c:if test="${i != page.currentPage}">
<li><a href="${pageContext.request.contextPath}/pageQuery?currentPage=${i}&pageSize=10">${i}</a></li>
</c:if>
</c:forEach>
<c:if test="${page.currentPage < page.pageCount}">
<li>
<a href="${pageContext.request.contextPath}/pageQuery?currentPage=${page.currentPage+1}&pageSize=10"
aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</c:if>
<li>
<span>
共 ${page.totalCount}条
共 ${page.pageCount}页
</span>
</li>
</ul>
</nav>
</td>
</tr>
</table>
<%--弹出添加商品的模态框--%>
<div class="modal fade" id="addProduct" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="exampleModalLabel">添加商品</h4>
</div>
<div class="modal-body">
<form id="addProduct_form" class="form-horizontal"
action="${pageContext.request.contextPath}/addProduct" method="post">
<div class="form-group">
<label for="pname" class="col-sm-2 control-label">商品名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="pname" name="pname" placeholder="请输入商品名称">
</div>
</div>
<div class="form-group">
<label for="market_price" class="col-sm-2 control-label">市场价格</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="market_price" name="market_price" placeholder="请输入商品价格">
</div>
</div>
<div class="form-group">
<label for="shop_price" class="col-sm-2 control-label">商城价格</label>
<div class="col-sm-10">
<input type="number" class="form-control" id="shop_price" name="shop_price" placeholder="请输入商品价格">
</div>
</div>
<div class="form-group">
<label for="is_hot" class="col-sm-2 control-label">是否热门</label>
<div class="col-sm-10">
<div class="radio" id="is_hot">
<label>
<input type="radio" value="1" name="is_hot" checked> 是
</label>
<label>
<input type="radio" value="0" name="is_hot"> 否
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="pflag" class="col-sm-2 control-label">是否下架</label>
<div class="col-sm-10">
<div class="radio" id="pflag">
<label>
<input type="radio" value="1" name="pflag" > 是
</label>
<label>
<input type="radio" value="0" name="pflag" checked> 否
</label>
</div>
</div>
</div>
<div class="form-group">
<label for="pdesc" class="col-sm-2 control-label">商城描述</label>
<div class="col-sm-10">
<textarea class="form-control" id="pdesc" name="pdesc" placeholder="请输入商品描述"></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary" id="add">添加</button>
</div>
</div>
</div>
</div>
</body>
</html>
2.效果演示
3.在web下新建一个AddProductServlet用来接收批量删除的请求
package com.bianyiit.web;
import com.bianyiit.domain.Product;
import com.bianyiit.service.ProductService;
import org.apache.commons.beanutils.BeanUtils;
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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/addProduct")
public class AddProductServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
Map<String, String[]> parameterMap = request.getParameterMap();
Product product = new Product();
try {
BeanUtils.populate(product,parameterMap);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(product);
ProductService service=new ProductService();
service.add(product);
response.sendRedirect(request.getContextPath()+"/pageQuery");
/*只能使用重定向,不能使用请求转发(永远是执行上一次的添加操作)*/
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
5.继续在ProductService中处理业务逻辑,控制业务流程,不操作数据库
package com.bianyiit.service;
import com.bianyiit.dao.ProductDao;
import com.bianyiit.domain.PageBean;
import com.bianyiit.domain.Product;
import java.util.List;
public class ProductService {
ProductDao productDao = new ProductDao();
public List<Product> findAll() {
List<Product> productList=productDao.findAll();
return productList;
}
public PageBean<Product> findPage(String scurrentPage, String spageSize) {
/*校验数据是否正确*/
int pageSize=10;
try {
pageSize = Integer.parseInt(spageSize);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
int currentPage=1;
try {
currentPage = Integer.parseInt(scurrentPage);
} catch (NumberFormatException e) {
//e.printStackTrace();
}
/*完成分类的业务逻辑*/
PageBean<Product> PageBean = new PageBean<>();
//设置每页条数
PageBean.setPageSize(pageSize);
//当前页数
PageBean.setCurrentPage(currentPage);
//总记录数
int totalCount = productDao.findCount();
PageBean.setTotalCount(totalCount);
//总页数
int pageCount=(int)Math.ceil((double)totalCount/pageSize);
PageBean.setPageCount(pageCount);
//list数据
int start=(currentPage-1)*pageSize;
List<Product> list=productDao.findPage(start,pageSize);
PageBean.setList(list);
return PageBean;
}
public void deleteByPid(String pid) {
productDao.deleteByPid(pid);
}
public void deleteBatch(String[] pids) {
if(pids!=null||pids.length>0){
for (int i = 0; i < pids.length ; i++) {
deleteByPid(pids[i]);
}
}
}
public void add(Product product) {
productDao.add(product);
}
}
6.继续在dao下的Product类中完成ProductService中需要我们去操作数据库的方法
package com.bianyiit.dao;
import com.bianyiit.domain.Product;
import com.bianyiit.util.DruidUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Date;
import java.util.List;
public class ProductDao {
private JdbcTemplate template=new JdbcTemplate(DruidUtils.getDataSource());
public List<Product> findAll() {
String sql="select * from product";
List<Product> query = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class));
return query;
}
public int findCount() {
String sql="SELECT count(pid) FROM product";
Integer count = template.queryForObject(sql, Integer.class);
return count;
}
public List<Product> findPage(int start, int pageSize) {
String sql="select * from product limit ?,?";
List<Product> productlist = template.query(sql, new BeanPropertyRowMapper<Product>(Product.class), start, pageSize);
return productlist;
}
public void deleteByPid(String pid) {
String sql="delete from product where pid=?";
template.update(sql, pid);
}
public void add(Product product) {
String sql = "insert into product values(null,?,?,?,?,?,?,?,?,?)";
template.update(sql,
product.getPname(),
product.getMarket_price(),
product.getShop_price(),
product.getPimage(),
new Date(),
product.getIs_hot(),
product.getPdesc(),
product.getPflag(),
product.getCid());
}
}
5.在AddProductServlet中处理完添加商品操作之后的业务走向
6.同样在pagelist.jsp中展示删除全选的商品之后重新请求的分页的页面,效果展示如下
注意1:之前创建的数据库表是包含外键的,打开数据库,找到product表,右击,找到关联/ 外键,点击删除
注意2:创建的Product实体类中的字段要和我们insert into进数据库中的保持一致,不然会报字段匹配的错误