当前位置: 代码迷 >> 综合 >> day41 JavaWeb阶段——综合案例:用户信息列表展示(Servlet+JSP+MySQL+JDBCTempleat+Duird+BeanUtilS+tomcat完成用户信息列表展示)
  详细解决方案

day41 JavaWeb阶段——综合案例:用户信息列表展示(Servlet+JSP+MySQL+JDBCTempleat+Duird+BeanUtilS+tomcat完成用户信息列表展示)

热度:67   发布时间:2023-12-18 23:30:22.0

今日内容

  • 用户信息列表展示
  1. 简单功能
    1. 列表查询
    2. 登录
    3. 添加
    4. 删除
    5. 修改
  2. 复杂功能
    1. 删除选中
    2. 分页查询
    • 好处:
      1. 减轻服务器内存的开销
      2. 提升用户体验
    1. 复杂条件查询
  • 涉及相关技术:Servlet+JSP+MySQL+JDBCTempleat+Duird+BeanUtilS+tomcat

今日源码:
链接:https://pan.baidu.com/s/1TrgVXlXn6cYG3Jz1-Y_bFQ
提取码:e9de

案例:用户信息列表展示

1. 需求:用户信息的增删改查操作

目标:完成下图中的所有功能

在这里插入图片描述

2. 设计:

1. 技术选型:

Servlet+JSP+MySQL+JDBCTempleat+Duird+BeanUtilS+tomcat

2. 数据库设计:

create database day17; -- 创建数据库
use day17; 			   -- 使用数据库
create table user(   -- 创建表id int primary key auto_increment,name varchar(20) not null,gender varchar(5),age int,address varchar(32),qq	varchar(20),email varchar(50)
);

3. 开发:

1. 环境搭建

  1. 创建数据库环境
  2. 创建项目,导入需要的jar包
    在这里插入图片描述

2. 编码

2.1登录功能

效果:
在这里插入图片描述
测试:输入错误验证码效果
在这里插入图片描述
输入错误账户密码:

在这里插入图片描述
代码:

登录界面代码: login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>管理员登录</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><script type="text/javascript"></script><script>window.onload = function(){
     document.getElementById("vcode").onclick = function(){
     this.src="${pageContext.request.contextPath}/checkCodeServlet?time="+new Date().getTime();}}</script>
</head>
<body>
<div class="container" style="width: 400px;"><h3 style="text-align: center;">管理员登录</h3><form action="${pageContext.request.contextPath}/loginServlet" method="post"><div class="form-group"><label for="user">用户名:</label><input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/></div><div class="form-group"><label for="password">密码:</label><input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/></div><div class="form-inline"><label for="vcode">验证码:</label><input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/><a href="javascript:refreshCode();"><img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/></a></div><hr/><div class="form-group" style="text-align: center;"><input class="btn btn btn-primary" type="submit" value="登录"></div></form><!-- 出错显示的信息框 --><div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" ><span>&times;</span></button><strong>${login_msg}</strong></div>
</div>
</body>
</html>

验证码校验Servlet: CheckCodeServlet.java

package cn.wbslz.web.servlet;import javax.imageio.ImageIO;
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.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;/*** 验证码*/
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    //服务器通知浏览器不要缓存response.setHeader("pragma","no-cache");response.setHeader("cache-control","no-cache");response.setHeader("expires","0");//在内存中创建一个长80,宽30的图片,默认黑色背景//参数一:长//参数二:宽//参数三:颜色int width = 80;int height = 30;BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//获取画笔Graphics g = image.getGraphics();//设置画笔颜色为灰色g.setColor(Color.GRAY);//填充图片g.fillRect(0,0, width,height);//产生4个随机验证码,12EyString checkCode = getCheckCode();//将验证码放入HttpSession中request.getSession().setAttribute("CHECKCODE_SERVER",checkCode);//设置画笔颜色为黄色g.setColor(Color.YELLOW);//设置字体的小大g.setFont(new Font("黑体",Font.BOLD,24));//向图片上写入验证码g.drawString(checkCode,15,25);//将内存中的图片输出到浏览器//参数一:图片对象//参数二:图片的格式,如PNG,JPG,GIF//参数三:图片输出到哪里去ImageIO.write(image,"PNG",response.getOutputStream());}/*** 产生4位随机字符串 */private String getCheckCode() {
    String base = "0123456789ABCDEFGabcdefg";int size = base.length();Random r = new Random();StringBuffer sb = new StringBuffer();for(int i=1;i<=4;i++){
    //产生0到size-1的随机值int index = r.nextInt(size);//在base字符串中获取下标为index的字符char c = base.charAt(index);//将c放入到StringBuffer中去sb.append(c);}return sb.toString();}public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doGet(request,response);}
}
2.2 欢迎界面

在这里插入图片描述
代码
index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>首页</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><script type="text/javascript"></script>
</head>
<body><div>${user.name},欢迎您!</div><div align="center"><ahref="${pageContext.request.contextPath}/findUserByPageServlet" style="text-decoration:none;font-size:33px">查询所有用户信息</a>
</div>
</body>
</html>
2.3查询结果界面

效果:
在这里插入图片描述

2.4 添加用户功能
  • 分析
    在这里插入图片描述

编码:

  1. add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- HTML5文档-->
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head><!-- 指定字符集 --><meta charset="utf-8"><!-- 使用Edge最新的浏览器的渲染方式 --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。width: 默认宽度与设备的宽度相同initial-scale: 初始的缩放比,为1:1 --><meta name="viewport" content="width=device-width, initial-scale=1"><!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --><title>添加用户</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container"><center><h3>添加联系人页面</h3></center><form action="${pageContext.request.contextPath}/addUserServlet" method="post"><div class="form-group"><label for="name">姓名:</label><input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名"></div><div class="form-group"><label>性别:</label><input type="radio" name="gender" value="" checked="checked"/><input type="radio" name="gender" value=""/></div><div class="form-group"><label for="age">年龄:</label><input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄"></div><div class="form-group"><label for="address">籍贯:</label><select name="address" class="form-control" id="address"><option value="广东">广东</option><option value="广西">广西</option><option value="湖南">湖南</option></select></div><div class="form-group"><label for="qq">QQ:</label><input type="text" class="form-control" id="qq" name="qq" placeholder="请输入QQ号码"/></div><div class="form-group"><label for="email">Email:</label><input type="text" class="form-control" id="email" name="email" placeholder="请输入邮箱地址"/></div><div class="form-group" style="text-align: center"><input class="btn btn-primary" type="submit" value="提交" /><input class="btn btn-default" type="reset" value="重置" /><input class="btn btn-default" type="button" value="返回" /></div></form>
</div>
</body>
  1. AddUserServlet
package cn.wbslz.web.servlet;import cn.wbslz.domain.User;
import cn.wbslz.service.UserService;
import cn.wbslz.service.impl.UserServiceImpl;
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("/addUserServlet")
public class AddUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1设置编码request.setCharacterEncoding("utf-8");//2.获取参数Map<String, String[]> map = request.getParameterMap();//3.封装对象User user = new User();try {
    BeanUtils.populate(user,map);} catch (IllegalAccessException e) {
    e.printStackTrace();} catch (InvocationTargetException e) {
    e.printStackTrace();}//4.调用service保存UserService service = new UserServiceImpl();service.addUser(user);//5.跳转到userListServletresponse.sendRedirect(request.getContextPath()+"/findUserByPageServlet");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);}
}
  1. UserService接口
 /*** 保存对象* @param user*/void addUser(User user);
  1. UserServiceImpl实现类
private UserDao dao = new UserDaoImpl();
@Overridepublic void addUser(User user) {
    dao.add(user);}
  1. UserDao接口
    /*** 添加用户* @param user*/void add(User user);
  1. UserDaoImpl实现类
    @Overridepublic void add(User user) {
    //1 定义sqlString sql = "insert into user values(null,?,?,?,?,?,?,null,null)";//2执行sqltemplate.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail());}

界面效果:
在这里插入图片描述

2.5 删除功能
  • 分析:
    在这里插入图片描述

  • 编码:

  1. delUserServlet
package cn.wbslz.web.servlet;import cn.wbslz.service.UserService;
import cn.wbslz.service.impl.UserServiceImpl;
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("/delUserServlet")
public class DelUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1 获取idString id = request.getParameter("id");//2 调用service删除UserService service = new UserServiceImpl();service.deleteUser(id);//3 跳转到查询所有页面response.sendRedirect(request.getContextPath()+"/findUserByPageServlet");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);}
}
  1. UserService接口
 /*** 根据id删除user* @param id*/void deleteUser(String id);
  1. UserServiceImpl实现类
@Overridepublic void deleteUser(String id) {
    dao.delete(Integer.parseInt(id));}
  1. UserDao接口
/*** 删除用户* @param id*/
void delete(int id);
  1. UserDaoImpl实现类
 @Overridepublic void delete(int id) {
    //1 定义sqlString sql = "delete from user where id = ?";//2.执行template.update(sql,id);}

演示效果:
在这里插入图片描述

2.6 修改功能
  • 分析
    在这里插入图片描述
  • 编码:
  1. FindUserServlet
package cn.wbslz.web.servlet;import cn.wbslz.domain.User;
import cn.wbslz.service.UserService;
import cn.wbslz.service.impl.UserServiceImpl;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("/findUserServlet")
public class FindUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1.获取idString id = request.getParameter("id");//2.调用serviceUserService service = new UserServiceImpl();User user = service.findUserById(id);//3.将user存入requestrequest.setAttribute("user",user);//4.转发到update.jsp
request.getRequestDispatcher("/update.jsp").forward(request,response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);}
}
  1. Update.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head><!-- 指定字符集 --><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>修改用户</title><link href="css/bootstrap.min.css" rel="stylesheet"><script src="js/jquery-2.1.0.min.js"></script><script src="js/bootstrap.min.js"></script></head>
<body>
<div class="container" style="width: 400px;"><h3 style="text-align: center;">修改联系人</h3><form action="${pageContext.request.contextPath}/updateUserServlet" method="post"><input type="hidden" name="id" value="${user.id}"><%--隐藏域,传id--%><div class="form-group"><label for="name">姓名:</label><input type="text" class="form-control" id="name" name="name" value="${user.name}" readonly="readonly" placeholder="请输入姓名" /></div><div class="form-group"><label>性别:</label><c:if test="${user.gender == '' }"><input type="radio" name="gender" value="" checked /><input type="radio" name="gender" value="" /></c:if><c:if test="${user.gender == '' }"><input type="radio" name="gender" value="" /><input type="radio" name="gender" value="" checked /></c:if></div><div class="form-group"><label for="age">年龄:</label><input type="text" class="form-control" id="age" name="age" value="${user.age}" placeholder="请输入年龄" /></div><div class="form-group"><label for="address">籍贯:</label><select name="address" id="address" class="form-control" ><c:if test="${user.address == '北京' }"><option value="北京" selected>北京</option><option value="上海">上海</option><option value="广州">广州</option></c:if><c:if test="${user.address == '上海' }"><option value="北京" >北京</option><option value="上海" selected>上海</option><option value="广州">广州</option></c:if><c:if test="${user.address == '广州' }"><option value="北京" >北京</option><option value="上海">上海</option><option value="广州" selected>广州</option></c:if></select></div><div class="form-group"><label for="qq">QQ:</label><input type="text" class="form-control" id="qq" name="qq" value="${user.qq}" placeholder="请输入QQ号码"/></div><div class="form-group"><label for="email">Email:</label><input type="text" class="form-control" id="email" name="email" value="${user.email}" placeholder="请输入邮箱地址"/></div><div class="form-group" style="text-align: center"><input class="btn btn-primary" type="submit" value="提交" /><input class="btn btn-default" type="reset" value="重置" /><input class="btn btn-default" type="button" value="返回"/></div></form>
</div>
</body>
</html>
  1. UpdateUserServlet
package cn.wbslz.web.servlet;import cn.wbslz.domain.User;
import cn.wbslz.service.UserService;
import cn.wbslz.service.impl.UserServiceImpl;
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("/updateUserServlet")
public class UpdateUserServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //1,设置编码request.setCharacterEncoding("utf-8");//2.获取mapMap<String, String[]> map = request.getParameterMap();//3.封装对象User user = new User();try {
    BeanUtils.populate(user,map);} catch (IllegalAccessException e) {
    e.printStackTrace();} catch (InvocationTargetException e) {
    e.printStackTrace();}//4.调用service修改UserService service = new UserServiceImpl();service.updateUser(user);//5.跳转到查询所有Servletresponse.sendRedirect(request.getContextPath()+"/findUserByPageServlet");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);}
}
  1. UserService接口
 /***根据id查询* @param id* @return*/User findUserById(String id);/*** 修改用户信息* @param user*/void updateUser(User user);
  1. UserServiceImpl实现类
@Override
public User findUserById(String id) {
    return dao.findById(Integer.parseInt(id));
}@Override
public void updateUser(User user) {
    dao.update(user);
}
  1. UserDao接口
    /*** 根据id查询用户* @param id* @return*/User findById(int id);/*** 修改用户* @param user*/void update(User user);
  1. UserDaoImpl实现类
@Override
public User findById(int id) {
    //1定义sqlString sql = "select * from user where id = ?";//2.执行return template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),id);
}@Override
public void update(User user) {
    //1定义sqlString sql = "update user set name = ?,gender = ?,age = ?, address = ?,qq = ?,email = ? where id = ?";//2.执行template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());
}
  • 效果演示
    在这里插入图片描述
2.7 删除选中功能
  • 分析
    在这里插入图片描述
  • 编码:
  1. delSelectedServlet
package cn.wbslz.web.servlet;import cn.wbslz.domain.User;
import cn.wbslz.service.UserService;
import cn.wbslz.service.impl.UserServiceImpl;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("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //获取所有idString[] ids = request.getParameterValues("uid");//2.调用service删除UserService service = new UserServiceImpl();service.delSelectedUser(ids);//3.跳转到查询所有Servletresponse.sendRedirect(request.getContextPath()+"/findUserByPageServlet");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);}
}
  1. UserService接口
/*** 批量删除用户* @param ids* @return*/
void delSelectedUser(String[] ids);
  1. UserServiceImpl实现类: 这里循环复用删除单个用户方法
@Override
public void delSelectedUser(String[] ids) {
    if(ids != null && ids.length>0){
    //1.遍历数组for(String id: ids){
    //2.调用dao删除dao.delete(Integer.parseInt(id));}}
}
  1. UserDao接口
/*** 删除用户* @param id*/
void delete(int id);
  1. UserDaoImpl实现类
   @Overridepublic void delete(int id) {
    //1 定义sqlString sql = "delete from user where id = ?";//2.执行template.update(sql,id);}
  • 效果演示
    在这里插入图片描述
2.8 分页查询功能(重点)
  • 分析
    在这里插入图片描述
    在这里插入图片描述

  • 编码:

  1. FindUserByPageServlet
package cn.wbslz.web.servlet;import cn.wbslz.domain.PageBean;
import cn.wbslz.domain.User;
import cn.wbslz.service.UserService;
import cn.wbslz.service.impl.UserServiceImpl;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.Map;@WebServlet("/findUserByPageServlet")
public class FindUserByPageServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");//1.获取参数String currentPage = request.getParameter("currentPage");//当前页码String rows = request.getParameter("rows");//每页显示条数if(currentPage == null || "".equals(currentPage)){
    currentPage = "1";}if(rows == null || "".equals(rows)){
    rows = "5";}//获取条件查询的参数Map<String, String[]> condition = request.getParameterMap();//2.调用service查询UserService service = new UserServiceImpl();PageBean<User> pb = service.findUserByPage(currentPage,rows,condition);System.out.println(pb);//测试用//3.将PageBean出入requestrequest.setAttribute("pb",pb);request.setAttribute("condition",condition);//将查询条件也存入//4.转发到list.jsprequest.getRequestDispatcher("/list.jsp").forward(request,response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    this.doPost(request, response);}
}
  1. UserService接口
 /*** 分页条件查询* @param currentPage* @param rows* @param condition* @return*/PageBean<User> findUserByPage(String currentPage, String rows, Map<String, String[]> condition);
}
  1. UserServiceImpl实现类
@Overridepublic PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
    int currentPage = Integer.parseInt(_currentPage);int rows = Integer.parseInt(_rows);if(currentPage <= 0){
    //当前页小于0,则设置为1currentPage = 1;}//1.创建空的PageBean对象PageBean<User> pb = new PageBean<User>();//2.调用dao查询总记录数int totalCount = dao.findTotalCount(condition);pb.setTotalCount(totalCount);//3.设置参数pb.setCurrentPage(currentPage);pb.setRows(rows);//4.计算总页码int totalPage = (totalCount % rows) == 0 ? (totalCount/rows) : (totalCount/rows) +1;pb.setTotalPage(totalPage);if(currentPage >= totalPage){
    //当前页大于最大页,则设置为totalCountcurrentPage = totalPage;}//5.调用dao查询List集合//计算开始的记录int start = (currentPage - 1) * rows;List<User> list = dao.findByPage(start,rows,condition);pb.setList(list);return pb;}
  1. UserDao接口
/*** 查询总记录数* @return* @param condition*/
int findTotalCount(Map<String, String[]> condition);/*** 分页查询每页记录* @param start* @param rows* @param condition* @return*/
List<User> findByPage(int start, int rows, Map<String, String[]> condition);
  1. UserDaoImpl实现类
@Overridepublic int findTotalCount(Map<String, String[]> condition) {
    //1.定义模板初始化sql,String sql = "select count(*) from user where 1=1 ";StringBuilder sb = new StringBuilder(sql);//2.遍历mapSet<String> keySet = condition.keySet();//定义参数集合List<Object> params = new ArrayList<Object>();for(String key : keySet){
    //排除分页条件参数if("currentPage".equals(key) || "rows".equals(key)){
    continue;}//获取valueString value = condition.get(key)[0];//判断value是否有值if(value != null && !"".equals(value)){
    //有值sb.append(" and "+key+" like ? ");params.add("%"+value+"%");//?条件的值}}System.out.println(sb.toString());//测试System.out.println(params);//测试return template.queryForObject(sb.toString(),Integer.class,params.toArray());}@Overridepublic List<User> findByPage(int start, int rows, Map<String, String[]> condition) {
    String sql = "select * from user where 1 = 1";StringBuilder sb = new StringBuilder(sql);//2.遍历mapSet<String> keySet = condition.keySet();//定义参数集合List<Object> params = new ArrayList<Object>();for(String key : keySet){
    //排除分页条件参数if("currentPage".equals(key) || "rows".equals(key)){
    continue;}//获取valueString value = condition.get(key)[0];//判断value是否有值if(value != null && !"".equals(value)){
    //有值sb.append(" and "+key+" like ? ");params.add("%"+value+"%");//?条件的值}}//添加分页查询sb.append(" limit ?,? ");//添加分页查询参数params.add(start);params.add(rows);sql = sb.toString();System.out.println(sql);System.out.println(params);return template.query(sql,new BeanPropertyRowMapper<User>(User.class),params.toArray());}
  • 效果:
    在这里插入图片描述
2.9 复杂条件分页查询功能(重点)
  • 分析:
    在这里插入图片描述
  • 编码:
    • 包含在2.9分页查询里
  • 效果
    在这里插入图片描述
    可以在控制台查看到,查询sql是动态变化的
    在这里插入图片描述

4. 测试

5. 部署运维

使用tomcat服务器项目

6. 总结

该项目是融合了从前40天所学内容的整合项目,是对之前所学知识的实践性检验,对训练基础知识很有帮助。

([点开我的主页系统的学习java])

  相关解决方案