条件查询-分页查询-条件分页查询

导读:本篇文章讲解 条件查询-分页查询-条件分页查询,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

条件查询(参考)

设计图:

在这里插入图片描述

参考代码:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
创建数据表:

#创建班级表
create table classInfo
(
    classId int primary key auto_increment,
    className varchar(20)
)

    insert into classInfo
(className)
select 'AAA01' UNION
select 'AAA02' UNION
select 'AAA03'

    insert into classInfo
(className)
select 'AAA04' UNION
select 'AAA05' UNION
select 'AAA06' UNION
select 'AAA07'

select * from classInfo

drop table studentInfo

    #创建学生信息表
create table studentInfo
(
    studentId int primary key auto_increment,
    name varchar(20),
    sex char(1),
    birthday date,
    tall decimal(3,2),
    classId int
)

    insert into studentInfo
(name,sex,birthday,tall,classId)
select '张三','男','2001-01-01',1.7,1 union
select '李四','女','2002-01-01',1.7,2

select * from studentInfo

BaseDAO:

package com.util;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.*;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://192.168.0.115:3306/0801_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";



	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

ClassInfo:

package com.entity;

/**
 * @author: hy
 * @create: 2022-08-01 10:52:43
 */
public class ClassInfo {
    private Integer classId;
    private String className;

    public ClassInfo() {
    }

    public ClassInfo(Integer classId, String className) {
        this.classId = classId;
        this.className = className;
    }

    public ClassInfo(String className) {
        this.className = className;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "ClassInfo{" +
                "classId=" + classId +
                ", className='" + className + '\'' +
                '}';
    }
}

IClassInfoDAO:

package com.dao;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassInfoDAO {
    /**
     * 查询所有
     * @return
     */
    List<Map<String,Object>> listAll();
    //带条件查询
    List<Map<String,Object>> listByCon(String searchClassName);

    ClassInfo getByClassId(Integer classId);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassInfoDAOImpl:

package com.dao.impl;

import com.dao.IClassInfoDAO;
import com.entity.ClassInfo;
import com.mysql.cj.util.StringUtils;
import com.util.BaseDAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:54:26
 */
public class ClassInfoDAOImpl implements IClassInfoDAO {
    @Override
    public List<Map<String, Object>> listAll() {
        String sql ="select classId,className from classInfo ";
        return BaseDAO.executeQuery(sql,null);
    }

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        //where sql语句
        StringBuilder whereSql = new StringBuilder();
        //sql中的参数
        List<Object> params = new ArrayList<>();

        //如果条件不为空,则拼接where ,同时添加参数
        if(!StringUtils.isNullOrEmpty(searchClassName)){
            whereSql.append(" where className like ? ");
            params.add("%"+searchClassName+"%");
        }

        String sql ="select classId,className " +
                "    from classInfo " + whereSql;

        return BaseDAO.executeQuery(sql,params.toArray());
    }

    /**
     * 根据编号查询数据对象
     * @param classId
     * @return
     */
    @Override
    public ClassInfo getByClassId(Integer classId) {
        String sql ="select classId,className from classInfo " +
                "    where classId = ? ";
        Object[] params = {classId};
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
        if(rows.size()>0){
            Map<String,Object> map = rows.get(0);
            ClassInfo c = new ClassInfo(
                    (Integer)map.get("classId"),
                    (String)map.get("className")
            );
            System.out.println(c);
            return c;
        }
        return null;
    }

    @Override
    public int insert(ClassInfo classInfo) {
        String sql = "insert into classInfo" +
                "     (className)" +
                "     values" +
                "     (?)";
        Object[] params = {classInfo.getClassName()};
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int update(ClassInfo classInfo) {
        String sql = "update classInfo " +
                "     set className = ? " +
                "     where classId = ? ";
        Object[] params = {
                classInfo.getClassName(),
                classInfo.getClassId()
        };
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int delete(Integer classId) {
        String sql = "delete from classInfo where classId = ? ";
        Object[] params = {classId};
        return BaseDAO.executeUpdate(sql,params);
    }
}

IClassInfoService:

package com.service;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassInfoService {
    //查询所有班级数据
    List<Map<String,Object>> listAll();
    //带条件查询
    List<Map<String,Object>> listByCon(String searchClassName);
    //根据编号查询班级对象
    ClassInfo getByClassId(Integer classId);
    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassInfoServiceImpl:

package com.service.impl;

import com.dao.IClassInfoDAO;
import com.dao.impl.ClassInfoDAOImpl;
import com.entity.ClassInfo;
import com.service.IClassInfoService;

import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:55:41
 */
public class ClassInfoServiceImpl implements IClassInfoService {
    //数据访问层对象
    private IClassInfoDAO classInfoDAO = new ClassInfoDAOImpl();
    @Override
    public List<Map<String, Object>> listAll() {
        return classInfoDAO.listAll();
    }

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        return classInfoDAO.listByCon(searchClassName);
    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        return classInfoDAO.getByClassId(classId);
    }

    @Override
    public int insert(ClassInfo classInfo) {
        return classInfoDAO.insert(classInfo);
    }

    @Override
    public int update(ClassInfo classInfo) {
        return classInfoDAO.update(classInfo);
    }

    @Override
    public int delete(Integer classId) {
        return classInfoDAO.delete(classId);
    }
}

ClassInfoServlet:

package com.servlet;

import com.entity.ClassInfo;
import com.service.IClassInfoService;
import com.service.impl.ClassInfoServiceImpl;

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;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:57:07
 */
@WebServlet(urlPatterns = "/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
    //定义业务层对象
    IClassInfoService classInfoService = new ClassInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应对象的编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取请求路径,截取请求处理的字符串
        //  uri: /lesson0801_crud/ClassInfoServlet/query
        String uri = req.getRequestURI();
        // process: query
        String process = uri.substring(uri.lastIndexOf("/")+1);

        //针对增删改查的请求做处理
        switch (process){
            case "query":
                this.query(req,resp); //查询处理
                break;
            case "toAdd":
                this.toAdd(req,resp); //跳转到添加
                break;
            case "add":
                this.add(req,resp); //添加处理
                break;
            case "toUpdate":
                this.toUpdate(req,resp);//跳转到修改
                break;
            case "update":
                this.update(req,resp);//修改处理
                break;
            case "delete":
                this.delete(req,resp); //删除处理
                break;
        }


    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取班级编号
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        int count = classInfoService.delete(classId);
        if(count==1){
            //删除成功,重新显示
            this.query(req,resp);
        }else{
            //失败,跳转到失败页面
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取提交的表单数据
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        String className = req.getParameter("className");
        ClassInfo classInfo = new ClassInfo(classId,className);
        //调用修改
        int count = classInfoService.update(classInfo);
        if(count==1){
            //修改成功,则重新显示
            this.query(req,resp);
        }else{
            //跳转到失败
        }

    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要修改的编号:如果此时没有获取到编号,会爆出数字格式异常
        System.out.println("classId:"+req.getParameter("classId"));
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        //根据编号,查询要修改的班级对象
        ClassInfo classInfo =  classInfoService.getByClassId(classId);
        //将要修改的班级对象,存储到request中,带到页面上,呈现出来
        req.setAttribute("classInfo",classInfo);
        //跳转到修改页面
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);
    }

    /**
     * 添加班级数据
     * @param req
     * @param resp
     */
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取添加页面提交的数据
        String className = req.getParameter("className");
        ClassInfo ci = new ClassInfo(className);
        //构建班级对象
        int count = classInfoService.insert(ci);

        if(count==1){
            //添加成功,跳转到查询页面
            //resp.sendRedirect(req.getContextPath()+"/ClassInfoServlet/query");
            //直接调用查询逻辑
            this.query(req,resp);
        }else{
            //跳转到失败页面
            System.out.println("添加记录不等于1,失败了......");
        }
    }

    /**
     * 跳转到添加页面
     * @param req
     * @param resp
     */
    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/classAdd.jsp").forward(req,resp);
    }

    /**
     * 查询处理
     * @param req
     * @param resp
     */
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取查询条件
        String searchClassName = req.getParameter("searchClassName");
        //List<Map<String,Object>> classInfoList = classInfoService.listAll();
        //条件查询
        List<Map<String, Object>> classInfoList = classInfoService.listByCon(searchClassName);
        req.setAttribute("classInfoList",classInfoList);
        //设置查询条件,存储到req,返回到页面
        //req.setAttribute("searchClassName",searchClassName);

        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 9:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="${pageContext.request.contextPath}/StudentInfoServlet">学生信息</a>
    <a href="${pageContext.request.contextPath}/ClassInfoServlet/query">班级信息</a>
  </body>
</html>

classList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 10:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    班级数据:${classInfoList}
    <hr/>
    <table border="1" align="center" width="50%">
        <tr>
            <td colspan="3">
                <a href="${pageContext.request.contextPath}/ClassInfoServlet/toAdd">添加</a>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <form id="searchFrm" action="" method="get">
                    班级:
                    <!--param: el 隐式对象,能够存储页面提交到服务器端的参数数据-->
                    <input type="text" id="searchCls" name="searchClassName" value="${param.searchClassName}"/>
                    <input type="submit" value="搜索"/>
                </form>
            </td>
        </tr>
        <tr>
            <th>班级编号</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        <!--items:数据集合
            注意:items关联的一定是个对象集合(el表达式),不是纯粹的字符串
            var:用于定义变量名字,临时存储遍历集合中的某个对象
        -->
        <c:forEach items="${classInfoList}" var="c">
            <tr>
                <td>${c.classId}</td>
                <td>${c.className}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/toUpdate?classId=${c.classId}">修改</a>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/delete?classId=${c.classId}"
                       onclick="return confirm('确定要删除么?')">
                        删除
                    </a>
                </td>
            </tr>
        </c:forEach>
    </table>

</body>
</html>

classAdd.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/add">
        <table border="1" align="center">
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="添加"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

classUpdate.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    ${classInfo}
    <hr/>
    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/update">
        <table border="1" align="center">
            <!--type=hidden : 隐藏文本框-->
            <input type="hidden" name="classId" value="${classInfo.classId}"/>
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className" value="${classInfo.className}"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="修改"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';

分页查询(参考)

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

参考代码:

BaseDAO:

package com.util;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.*;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://192.168.0.115:3306/0801_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";



	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}

	//获取总记录数的查询:select count(*) from ..
	public static int getTotal(String sql,Object[] params){
		int total = 0;

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{

			con = getConnection();
			pst = con.prepareStatement(sql);
			setParams(pst,params);
			rs = pst.executeQuery();
			//判断是否查询除了一个记录
			if(rs.next()){
				total = rs.getInt(1);
			}

		}catch (Exception ex){
			ex.printStackTrace();
		}finally {
			closeAll(con,pst,rs);
		}

		return total;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

ClassInfo:

package com.entity;

/**
 * @author: hy
 * @create: 2022-08-01 10:52:43
 */
public class ClassInfo {
    private Integer classId;
    private String className;

    public ClassInfo() {
    }

    public ClassInfo(Integer classId, String className) {
        this.classId = classId;
        this.className = className;
    }

    public ClassInfo(String className) {
        this.className = className;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "ClassInfo{" +
                "classId=" + classId +
                ", className='" + className + '\'' +
                '}';
    }
}

PageData:

package com.entity;

import java.util.List;

/**
 * 用于封装分页数据的实体类
 * @author: hy
 * @create: 2022-08-02 11:05:21
 */
public class PageData {
    //1.当前页码
    private Integer pageNo;
    //2.每页条数
    private Integer pageSize;
    //3.总记录数
    private Integer totalCount;
    //4.总页数
    private Integer totalPage;
    //5.当前页的记录
    private Object data;

    public PageData() {
    }

    public PageData(Integer pageNo, Integer pageSize, Integer totalCount, Integer totalPage, Object data) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
        this.totalPage = totalPage;
        this.data = data;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "PageData{" +
                "pageNo=" + pageNo +
                ", pageSize=" + pageSize +
                ", totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", data=" + data +
                '}';
    }
}

IClassInfoDAO:

package com.dao;

import com.entity.ClassInfo;
import com.entity.PageData;

import java.util.List;
import java.util.Map;

public interface IClassInfoDAO {
    /**
     * 查询所有
     * @return
     */
    List<Map<String,Object>> listAll();
    //带条件查询
    List<Map<String,Object>> listByCon(String searchClassName);
    //分页查询:pageNo 当前页码 pagesize 每页几条
    PageData listByPage(Integer pageNo,Integer pageSize);

    ClassInfo getByClassId(Integer classId);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassInfoDAOImpl:

package com.dao.impl;

import com.dao.IClassInfoDAO;
import com.entity.ClassInfo;
import com.entity.PageData;
import com.mysql.cj.util.StringUtils;
import com.util.BaseDAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:54:26
 */
public class ClassInfoDAOImpl implements IClassInfoDAO {
    @Override
    public List<Map<String, Object>> listAll() {
        String sql ="select classId,className from classInfo ";
        return BaseDAO.executeQuery(sql,null);
    }

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        //where sql语句
        StringBuilder whereSql = new StringBuilder();
        //sql中的参数
        List<Object> params = new ArrayList<>();

        //如果条件不为空,则拼接where ,同时添加参数
        if(!StringUtils.isNullOrEmpty(searchClassName)){
            whereSql.append(" where className like ? ");
            params.add("%"+searchClassName+"%");
        }

        String sql ="select classId,className " +
                "    from classInfo " + whereSql;

        return BaseDAO.executeQuery(sql,params.toArray());
    }

    /**
     * 分页查询数据
     * @param pageNo
     * @param pageSize
     * @return
     */
    @Override
    public PageData listByPage(Integer pageNo, Integer pageSize) {
        //查询总记录数
        String totalSql = "select count(*) from classInfo ";
        Integer totalCount = BaseDAO.getTotal(totalSql,null);

        //获取总页数: 10  2  3
        Integer totalPage = totalCount%pageSize==0?totalCount/pageSize
                                                  :totalCount/pageSize+1;


        // limit ?,?:从哪一条之后,取若干条
        String sql ="select classId,className " +
                "    from classInfo " +
                "    order by classId " +
                "    limit ?,? ";
        //计算分页开始位置
        int start = (pageNo-1)*pageSize;
        //构建分页参数
        Object[] params = {
                start,pageSize
        };

        //分页查询:查询当前页若干条的记录数
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);

        //将5项数据封装到PageData中
        PageData pd = new PageData();
        pd.setPageNo(pageNo); //当前页码
        pd.setPageSize(pageSize); //每页记录数
        pd.setTotalCount(totalCount); //总记录数
        pd.setTotalPage(totalPage); //总页数
        pd.setData(rows); //当前页记录

        return pd;
    }

    /**
     * 根据编号查询数据对象
     * @param classId
     * @return
     */
    @Override
    public ClassInfo getByClassId(Integer classId) {
        String sql ="select classId,className from classInfo " +
                "    where classId = ? ";
        Object[] params = {classId};
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
        if(rows.size()>0){
            Map<String,Object> map = rows.get(0);
            ClassInfo c = new ClassInfo(
                    (Integer)map.get("classId"),
                    (String)map.get("className")
            );
            System.out.println(c);
            return c;
        }
        return null;
    }

    @Override
    public int insert(ClassInfo classInfo) {
        String sql = "insert into classInfo" +
                "     (className)" +
                "     values" +
                "     (?)";
        Object[] params = {classInfo.getClassName()};
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int update(ClassInfo classInfo) {
        String sql = "update classInfo " +
                "     set className = ? " +
                "     where classId = ? ";
        Object[] params = {
                classInfo.getClassName(),
                classInfo.getClassId()
        };
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int delete(Integer classId) {
        String sql = "delete from classInfo where classId = ? ";
        Object[] params = {classId};
        return BaseDAO.executeUpdate(sql,params);
    }
}

IClassInfoService:

package com.service;

import com.entity.ClassInfo;
import com.entity.PageData;

import java.util.List;
import java.util.Map;

public interface IClassInfoService {
    //查询所有班级数据
    List<Map<String,Object>> listAll();
    //带条件查询
    List<Map<String,Object>> listByCon(String searchClassName);
    //分页查询:pageNo 当前页码 pagesize 每页几条
    PageData listByPage(Integer pageNo, Integer pageSize);
    //根据编号查询班级对象
    ClassInfo getByClassId(Integer classId);
    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassInfoServiceImpl:

package com.service.impl;

import com.dao.IClassInfoDAO;
import com.dao.impl.ClassInfoDAOImpl;
import com.entity.ClassInfo;
import com.entity.PageData;
import com.service.IClassInfoService;

import java.util.List;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:55:41
 */
public class ClassInfoServiceImpl implements IClassInfoService {
    //数据访问层对象
    private IClassInfoDAO classInfoDAO = new ClassInfoDAOImpl();
    @Override
    public List<Map<String, Object>> listAll() {
        return classInfoDAO.listAll();
    }

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        return classInfoDAO.listByCon(searchClassName);
    }

    @Override
    public PageData listByPage(Integer pageNo, Integer pageSize) {
        return classInfoDAO.listByPage(pageNo,pageSize);
    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        return classInfoDAO.getByClassId(classId);
    }

    @Override
    public int insert(ClassInfo classInfo) {
        return classInfoDAO.insert(classInfo);
    }

    @Override
    public int update(ClassInfo classInfo) {
        return classInfoDAO.update(classInfo);
    }

    @Override
    public int delete(Integer classId) {
        return classInfoDAO.delete(classId);
    }
}

ClassInfoServlet :

package com.servlet;

import com.entity.ClassInfo;
import com.entity.PageData;
import com.service.IClassInfoService;
import com.service.impl.ClassInfoServiceImpl;

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;
import java.util.Map;

/**
 * @author: hy
 * @create: 2022-08-01 10:57:07
 */
@WebServlet(urlPatterns = "/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
    //定义业务层对象
    IClassInfoService classInfoService = new ClassInfoServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求和响应对象的编码
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //获取请求路径,截取请求处理的字符串
        //  uri: /lesson0801_crud/ClassInfoServlet/query
        String uri = req.getRequestURI();
        // process: query
        String process = uri.substring(uri.lastIndexOf("/")+1);

        //针对增删改查的请求做处理
        switch (process){
            case "query":
                this.query(req,resp); //查询处理
                break;
            case "queryByPage":
                this.queryByPage(req,resp);
                break;
            case "toAdd":
                this.toAdd(req,resp); //跳转到添加
                break;
            case "add":
                this.add(req,resp); //添加处理
                break;
            case "toUpdate":
                this.toUpdate(req,resp);//跳转到修改
                break;
            case "update":
                this.update(req,resp);//修改处理
                break;
            case "delete":
                this.delete(req,resp); //删除处理
                break;
        }


    }

    //分页查询
    private void queryByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取当前页页码
        Integer pageNo =  1;
        Integer pageSize = 3;
        if(req.getParameter("pageNo")!=null){
            pageNo = Integer.parseInt(req.getParameter("pageNo"));
        }
        if(req.getParameter("pageSize")!=null){
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }

        //获取查询条件
        String searchClassName = req.getParameter("searchClassName");
        System.out.println("searchClassName:"+searchClassName);
        System.out.println("pageNo:"+pageNo);
        System.out.println("pageSize:"+pageSize);

        //调用分页查询
        PageData pageData = classInfoService.listByPage(pageNo, pageSize);
        System.out.println("pagedata:"+pageData);
        //存储到req,跳转到页面
        req.setAttribute("pd",pageData);
        req.getRequestDispatcher("/classList.jsp").forward(req,resp);

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取班级编号
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        int count = classInfoService.delete(classId);
        if(count==1){
            //删除成功,重新显示
            this.query(req,resp);
        }else{
            //失败,跳转到失败页面
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取提交的表单数据
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        String className = req.getParameter("className");
        ClassInfo classInfo = new ClassInfo(classId,className);
        //调用修改
        int count = classInfoService.update(classInfo);
        if(count==1){
            //修改成功,则重新显示
            this.query(req,resp);
        }else{
            //跳转到失败
        }

    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要修改的编号:如果此时没有获取到编号,会爆出数字格式异常
        System.out.println("classId:"+req.getParameter("classId"));
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        //根据编号,查询要修改的班级对象
        ClassInfo classInfo =  classInfoService.getByClassId(classId);
        //将要修改的班级对象,存储到request中,带到页面上,呈现出来
        req.setAttribute("classInfo",classInfo);
        //跳转到修改页面
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);
    }

    /**
     * 添加班级数据
     * @param req
     * @param resp
     */
    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取添加页面提交的数据
        String className = req.getParameter("className");
        ClassInfo ci = new ClassInfo(className);
        //构建班级对象
        int count = classInfoService.insert(ci);

        if(count==1){
            //添加成功,跳转到查询页面
            //resp.sendRedirect(req.getContextPath()+"/ClassInfoServlet/query");
            //直接调用查询逻辑
            this.query(req,resp);
        }else{
            //跳转到失败页面
            System.out.println("添加记录不等于1,失败了......");
        }
    }

    /**
     * 跳转到添加页面
     * @param req
     * @param resp
     */
    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/classAdd.jsp").forward(req,resp);
    }

    /**
     * 查询处理
     * @param req
     * @param resp
     */
    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取查询条件
        String searchClassName = req.getParameter("searchClassName");
        //List<Map<String,Object>> classInfoList = classInfoService.listAll();
        //条件查询
        List<Map<String, Object>> classInfoList = classInfoService.listByCon(searchClassName);
        req.setAttribute("classInfoList",classInfoList);
        //设置查询条件,存储到req,返回到页面
        //req.setAttribute("searchClassName",searchClassName);

        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 9:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <a href="${pageContext.request.contextPath}/StudentInfoServlet">学生信息</a>
    <a href="${pageContext.request.contextPath}/ClassInfoServlet/query">班级信息</a>
    <a href="${pageContext.request.contextPath}/ClassInfoServlet/queryByPage">班级分页</a>
  </body>
</html>

classList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 10:58
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    班级数据:${classInfoList}
    <hr/>
    <table border="1" align="center" width="50%">
        <tr>
            <td colspan="3">
                <a href="${pageContext.request.contextPath}/ClassInfoServlet/toAdd">添加</a>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <form id="searchFrm" action="${pageContext.request.contextPath}/ClassInfoServlet/queryByPage" method="get">
                    班级:
                    <!--param: el 隐式对象,能够存储页面提交到服务器端的参数数据-->
                    <input type="text" id="searchCls" name="searchClassName" value="${param.searchClassName}"/>
                    <input type="submit" value="搜索"/>
                    <!--不管是条件查询,还是分页处理,需要将两种情况的数据放在一起条件-->
                    <input type="hidden" name="pageNo" id="pageNo"/>
                    <input type="hidden" name="pageSize" id="pageSize"/>
                </form>
            </td>
        </tr>
        <tr>
            <th>班级编号</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        <!--items:数据集合
            注意:items关联的一定是个对象集合(el表达式),不是纯粹的字符串
            var:用于定义变量名字,临时存储遍历集合中的某个对象
        -->
        <c:forEach items="${pd.data}" var="c">
            <tr>
                <td>${c.classId}</td>
                <td>${c.className}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/toUpdate?classId=${c.classId}">修改</a>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/delete?classId=${c.classId}"
                       onclick="return confirm('确定要删除么?')">
                        删除
                    </a>
                </td>
            </tr>
        </c:forEach>
        <!--生成分页信息-->
        <tr>
            <td colspan="3">
                当前第${pd.pageNo}页/共${pd.totalPage}页 |
                总记录数:${pd.totalCount} |
                <c:forEach begin="1" end="${pd.totalPage}" var="i">
                    <c:if test="${pd.pageNo==i}">
                        <span>${i}</span>
                    </c:if>
                    <c:if test="${pd.pageNo!=i}">
                        <a href="javascript:jumpPage(${i})">${i}</a>
                    </c:if>
                    &nbsp;&nbsp;
                </c:forEach>  |
                每页
                <select name="pageSize" id="ps" onchange="changePageSize(this.value)">
                    <option value="2"  ${pd.pageSize==2?'selected':''}>2</option>
                    <option value="3"  ${pd.pageSize==3?'selected':''}>3</option>
                    <option value="5"  ${pd.pageSize==5?'selected':''}>5</option>
                </select>
                条
            </td>
        </tr>
    </table>

    <script type="text/javascript">
        //切换每页记录数
        function  changePageSize(size){
            window.location.href="${pageContext.request.contextPath}/ClassInfoServlet/queryByPage?pageSize="+size;
        }

        //跳转分页
        function jumpPage(no){
            //设置查询表单中的分页页码
            document.getElementById("pageNo").value=no;
            //设置查询表单中的每页记录数
            document.getElementById("pageSize").value=ps.value;
            //提交表单
            searchFrm.submit();
        }
    </script>
</body>
</html>

classAdd.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/add">
        <table border="1" align="center">
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="添加"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

classUpdate.jsp:

<%--
  Created by IntelliJ IDEA.
  User: henry
  Date: 2022/8/1
  Time: 11:20
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    ${classInfo}
    <hr/>
    <form method="post" action="${pageContext.request.contextPath}/ClassInfoServlet/update">
        <table border="1" align="center">
            <!--type=hidden : 隐藏文本框-->
            <input type="hidden" name="classId" value="${classInfo.classId}"/>
            <tr>
                <td>班级名称</td>
                <td>
                    <input type="text" name="className" value="${classInfo.className}"/>
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="submit" value="修改"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

1.条件查询(标准)

设计图:

在这里插入图片描述

实现效果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码整体布局:(class部分)

在这里插入图片描述
在这里插入图片描述

代码:

创建数据库/表格:

#创建数据库
create database 70730_db
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则 
#创建班级表
create table class
(
	classId int primary key auto_increment,
	className varchar(20)
);

insert into class
(className)
values 
('菜鸟1班'),
('菜鸟2班'),
('菜鸟3班'),
('菜鸟4班'),
('菜鸡1班'),
('菜鸡2班'),
('菜鸡3班'),
('菜鸡4班');

select * from class;

BaseDAO:

package com.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://localhost:3306/70730_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";

	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}


	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

ClassInfo:

package com.entity;

public class ClassInfo {
    private Integer classId;
    private String className;

    public ClassInfo() {
    }

    public ClassInfo(String className) {
        this.className = className;
    }

    public ClassInfo(Integer classId, String className) {
        this.classId = classId;
        this.className = className;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "Class{" +
                "classId=" + classId +
                ", className='" + className + '\'' +
                '}';
    }
}

IClassDAO:

package com.dao;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassDAO {
    List<Map<String,Object>> listAll();

    ClassInfo getByClassId(Integer classId);

    List<Map<String,Object>> listByCon(String searchClassName);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassDAOImpl:

package com.dao.impl;

import com.dao.IClassDAO;
import com.entity.ClassInfo;
import com.mysql.cj.util.StringUtils;
import com.util.BaseDAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClassDAOImpl implements IClassDAO {
    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        StringBuilder whereSql=new StringBuilder();

        List<Object> sparams=new ArrayList<>();

        if(!StringUtils.isNullOrEmpty(searchClassName)){
            whereSql.append(" where className like ? ");
            sparams.add("%"+searchClassName+"%");
        }

        String sql="select classId,className " +
                "  from class "+whereSql;
        System.out.println("sql:"+sql);
        System.out.println(sparams);
        System.out.println("sparams.toArray():"+sparams.toArray());

        return BaseDAO.executeQuery(sql,sparams.toArray());

    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        String sql="select classId,className from class"+
                "   where classId=?";
        Object[] params={classId};
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
        if(rows.size()>0){
            Map<String,Object> map= rows.get(0);

            ClassInfo classInfo=new ClassInfo(
                    (Integer) map.get("classId"), //注意强转化 get得到的是Object类型(鼠标放在get上看)
                    (String) map.get("className")
            );
            System.out.println(classInfo);
            return classInfo;
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> listAll() {
        String sql="select * from class";
        return BaseDAO.executeQuery(sql,null);
    }

    @Override
    public int insert(ClassInfo classInfo) {
        String sql="insert into class"+
                "   (className)"+
                "   values"+
                "   (?)";
        Object[] params={classInfo.getClassName()};
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int update(ClassInfo classInfo) {
        String sql="update class"+
                "   set className=?"+
                "   where classId=?";
        Object[] params={
                classInfo.getClassName(),
                classInfo.getClassId()
        };
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int delete(Integer classId) {
        String sql="delete from class"+  //注意delete写法
                "   where classId=?";
        Object[] params={classId};
        return BaseDAO.executeUpdate(sql,params);
    }
}

IClassService:

package com.service;

import com.entity.ClassInfo;

import java.util.List;
import java.util.Map;

public interface IClassService {
    List<Map<String,Object>> listAll();

    ClassInfo getByClassId(Integer classId);

    List<Map<String,Object>> listByCon(String searchClassName);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassServiceImpl:

package com.service.impl;

import com.dao.IClassDAO;
import com.dao.impl.ClassDAOImpl;
import com.entity.ClassInfo;
import com.service.IClassService;

import java.util.List;
import java.util.Map;

public class ClassServiceImpl implements IClassService {


    IClassDAO classDAO=new ClassDAOImpl();

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        return classDAO.listByCon(searchClassName);
    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        return classDAO.getByClassId(classId);
    }

    @Override
    public List<Map<String, Object>> listAll() {
        return classDAO.listAll();
    }

    @Override
    public int insert(ClassInfo classInfo) {
        return classDAO.insert(classInfo);
    }

    @Override
    public int update(ClassInfo classInfo) {
        return classDAO.update(classInfo);
    }

    @Override
    public int delete(Integer classId) {
        return classDAO.delete(classId);
    }
}

ClassInfoServlet :

package com.servlet;

import com.entity.ClassInfo;
import com.service.IClassService;
import com.service.impl.ClassServiceImpl;

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;
import java.util.Map;

@WebServlet(urlPatterns = "/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
    IClassService classService=new ClassServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);
        System.out.println("截取字段:"+process);

        switch (process){
            case "query":
                this.query(req,resp);
                break;
            case "toAdd":
                this.toAdd(req,resp);
                break;
            case "add":
                this.add(req,resp);
                break;
            case "toUpdate":
                this.toUpdate(req,resp);
                break;
            case "update":
                this.update(req,resp);
                break;
            case "delete":
                this.delete(req,resp);
                break;
        }
    }

//    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        List<Map<String,Object>> classList=classService.listAll();
//
//        req.setAttribute("classList",classList);
//        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
//    }


    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String searchClassName=req.getParameter("searchClassName");
        List<Map<String,Object>> classList=classService.listByCon(searchClassName);
        //用的特别巧妙,如果searchClassName为空,将查询所有;如果不为空,将模糊查询得相关的数据
        System.out.println(classList);

        req.setAttribute("classList",classList);
        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/classAdd.jsp").forward(req,resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String className=req.getParameter("className"); //注意 设置值关键字 从输入框获取值的关键字
        ClassInfo ci=new ClassInfo(className);

        int count=classService.insert(ci);

        if(count==1){
            System.out.println("插入成功!");
            this.query(req,resp);
        }else{
            System.out.println("插入失败!");
        }
    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        //根据编号,查询要修改的班级对象
        ClassInfo classInfo =  classService.getByClassId(classId);
        //将要修改的班级对象,存储到request中,带到页面上,呈现出来
        req.setAttribute("classInfo",classInfo);
        //跳转到修改页面
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);

        req.setAttribute("classInfo",classInfo);
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        String className = req.getParameter("className");
        ClassInfo classInfo = new ClassInfo(classId,className);
        //调用修改
        int count = classService.update(classInfo);
        if(count==1){
            //修改成功,则重新显示
            this.query(req,resp);
        }else{
            //跳转到失败
        }

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId= Integer.parseInt(req.getParameter("classId"));
        int count =classService.delete(classId);
        if(count==1){
            System.out.println("删除成功!");
            this.query(req,resp);
        }else{
            System.out.println("删除失败!");
        }
    }



}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/1
  Time: 20:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  <a href="${pageContext.request.contextPath}/StudentInfoServlet ">学生信息</a>
  <a href="${pageContext.request.contextPath}/ClassInfoServlet/query">班级信息</a>
 
  </body>
</html>

classList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/2
  Time: 1:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
    <%=request.getAttribute("classList")%>
</head>
<body>
    班级数据:${classList}
    <hr/>
    <table border="1" align="center" width="50%">
        <tr>
            <td colspan="3">
                <a href="${pageContext.request.contextPath}/ClassInfoServlet/toAdd">添加</a>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <form id="searchFrm" action="${pageContext.request.contextPath}/ClassInfoServlet/query" method="get">
                    班级:<input type="text" id="searchCls" name="searchClassName" value="${param.searchClassName}"/>
                    <input type="submit" value="搜索" />
                </form>
            </td>
        </tr>
        <tr>
            <th>班级编号</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${classList}" var="clas">
            <tr>
                <td>${clas.classId}</td>
                <td>${clas.className}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/toUpdate?classId=${clas.classId}">修改</a>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/delete?classId=${clas.classId}"
                    onclick="return confirm('你确定要删除吗?')">
                        删除
                    </a>
                </td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

2.分页查询:(这时的分页查询完好,条件查询异常)

实现效果:

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码整体布局:

在这里插入图片描述
在这里插入图片描述

代码:

创建数据库/表:

#创建班级表
create table class
(
	classId int primary key auto_increment,
	className varchar(20)
);

insert into class
(className)
values 
('菜鸟1班'),
('菜鸟2班'),
('菜鸟3班'),
('菜鸟4班'),
('菜鸡1班'),
('菜鸡2班'),
('菜鸡3班'),
('菜鸡4班');

select * from class;

select count(*) from class;

BaseDAO:

package com.util;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class BaseDAO {

	//四大金刚
	//驱动类
	private static final String DRIVER="com.mysql.cj.jdbc.Driver";
	//连接地址
	private static final String URL="jdbc:mysql://localhost:3306/70730_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
	//用户名
	private static final String USER="root";
	//密码
	private static final String PASSWORD="123456";

	//获取连接
	public static Connection getConnection(){

		Connection con = null;

		try{
			//加载驱动类
			Class.forName(DRIVER);
			//获取连接
			con = DriverManager.getConnection(URL,USER,PASSWORD);
			
		}catch(Exception ex){
			ex.printStackTrace();
		}

		return con;
	}

	//关闭数据库对象
	public static void closeAll(Connection con,Statement st,ResultSet rs){
		
		if(rs!=null){
			try{
				rs.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(st!=null){

			try{
				st.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

		if(con!=null){
			try{
				con.close();
			}catch(Exception ex){
				ex.printStackTrace();
			}
			
		}

	}


	//通用设置参数方法
	public static void setParams(PreparedStatement pst,Object[] params){

		if(params==null){
			return;
		}

		for(int i=0;i<params.length;i++){
			try{
				pst.setObject(i+1,params[i]);
			}catch(Exception ex){
				ex.printStackTrace();
			}
		}
	}

	//获取总记录数的查询 :select count(*) from ..
	public static int getTotal(String sql,Object[] params){
		int total=0;

		Connection con=null;
		PreparedStatement pst=null;
		ResultSet rs=null;


		try {                                  //手动添加try-catch: ctrl+alt+t
			con=getConnection();
			pst=con.prepareStatement(sql);

			setParams(pst,params);
			rs=pst.executeQuery();

			if(rs.next()){
				total=rs.getInt(1); //获取第一列的值(具体解释请看详细图解)
			}
		} catch (SQLException throwables) {
			throwables.printStackTrace();
		} finally {
			closeAll(con,pst,rs);
		}


		return total;
	}

	//通用增删改
	public static int executeUpdate(String sql,Object[] params){

		Connection con = null;
		PreparedStatement pst = null;
		
		int res = -1;
		
		try{

			//获取连接
			con = getConnection();
			//创建预编译命令执行对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行
			res = pst.executeUpdate();

		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,null);
		}
		
		return res;
	}


	//通用查询
	public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {

		List<Map<String,Object>> rows = new ArrayList<>();

		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;

		try{
			//获取连接	
			con = getConnection();			
			//获取命令对象
			pst = con.prepareStatement(sql);
			//设置参数
			setParams(pst,params);
			//执行查询
			rs = pst.executeQuery();

			//通过rs获取结果集的结构信息
			ResultSetMetaData rsmd =  rs.getMetaData();
			//获取结果集的列数
			int colCount = rsmd.getColumnCount();

			//遍历查询结果,并封装到List<Map>中
			while(rs.next()){
				//用Map存储当前行的各个列数据
				Map<String,Object> map = new HashMap<>();
				//循环获取每一列的信息
				for(int i=1;i<=colCount;i++){
					//获取列名(使用rsmd)
					String colName = rsmd.getColumnLabel(i);
					//获取列值(使用rs)
					Object colVal = rs.getObject(i);
					//将当前列存储到map中
					map.put(colName,colVal);								
				}
				
				//将遍历的当前行的数据存储到List中
				rows.add(map);
							
			}


		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			closeAll(con,pst,rs);
		}
		
		return rows;

	}

}

ClassInfo:

package com.entity;

public class ClassInfo {
    private Integer classId;
    private String className;

    public ClassInfo() {
    }

    public ClassInfo(String className) {
        this.className = className;
    }

    public ClassInfo(Integer classId, String className) {
        this.classId = classId;
        this.className = className;
    }

    public Integer getClassId() {
        return classId;
    }

    public void setClassId(Integer classId) {
        this.classId = classId;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    @Override
    public String toString() {
        return "Class{" +
                "classId=" + classId +
                ", className='" + className + '\'' +
                '}';
    }
}

PageDate :

package com.entity;

public class PageDate {
    //当前页码
    private Integer pageNo;
    //每页条数
    private Integer pageSize;
    //总记录数
    private Integer totalCount;
    //总页数
    private Integer totalPage;
    //当前页的记录
    private Object data;

    public PageDate() {
    }

    public PageDate(Integer pageSize, Integer totalCount, Integer totalPage, Object data) {
        this.pageSize = pageSize;
        this.totalCount = totalCount;
        this.totalPage = totalPage;
        this.data = data;
    }

    public PageDate(Integer pageNo, Integer pageSize, Integer totalCount, Integer totalPage, Object data) {
        this.pageNo = pageNo;
        this.pageSize = pageSize;
        this.totalCount = totalCount;
        this.totalPage = totalPage;
        this.data = data;
    }

    public Integer getPageNo() {
        return pageNo;
    }

    public void setPageNo(Integer pageNo) {
        this.pageNo = pageNo;
    }

    public Integer getPageSize() {
        return pageSize;
    }

    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    public Integer getTotalCount() {
        return totalCount;
    }

    public void setTotalCount(Integer totalCount) {
        this.totalCount = totalCount;
    }

    public Integer getTotalPage() {
        return totalPage;
    }

    public void setTotalPage(Integer totalPage) {
        this.totalPage = totalPage;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "PageDate{" +
                "pageNo=" + pageNo +
                ", pageSize=" + pageSize +
                ", totalCount=" + totalCount +
                ", totalPage=" + totalPage +
                ", data=" + data +
                '}';
    }
}

IClassDAO:

package com.dao;

import com.entity.ClassInfo;
import com.entity.PageDate;

import java.util.List;
import java.util.Map;

public interface IClassDAO {
    List<Map<String,Object>> listAll();

    ClassInfo getByClassId(Integer classId);

    List<Map<String,Object>> listByCon(String searchClassName);

    PageDate listByPage(Integer pageNo,Integer pageSize);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassDAOImpl:

package com.dao.impl;

import com.dao.IClassDAO;
import com.entity.ClassInfo;
import com.entity.PageDate;
import com.mysql.cj.util.StringUtils;
import com.util.BaseDAO;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ClassDAOImpl implements IClassDAO {
    @Override
    public PageDate listByPage(Integer pageNo, Integer pageSize) {
        //查询总记录数
        String totalSql="select count(*) from class";
        Integer totalCount=BaseDAO.getTotal(totalSql,null);

        //获取总页数
        Integer totalPage=totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;

        //limit ?,?; 从哪一条开始,取若干条
        String sql="select * from class "+
                "  order by classId "+
                "  limit ?,? ";
        //计算分页开始的位置
        int start=(pageNo-1)*pageSize;
        //构建分页参数
        Object[] params={
                start,
                pageSize
        };

        //分页查询:查询当前页若干条的记录数
        List<Map<String,Object>> rows=BaseDAO.executeQuery(sql,params);

        //将5项数据封装到PageData中
        PageDate pd=new PageDate();
        pd.setPageNo(pageNo);
        pd.setPageSize(pageSize);
        pd.setTotalCount(totalCount);
        pd.setTotalPage(totalPage);
        pd.setData(rows);

        return pd;
    }

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        StringBuilder whereSql=new StringBuilder();

        List<Object> sparams=new ArrayList<>();

        if(!StringUtils.isNullOrEmpty(searchClassName)){
            whereSql.append(" where className like ? ");
            sparams.add("%"+searchClassName+"%");
        }

        String sql="select classId,className " +
                "  from class "+whereSql;
        System.out.println("sql:"+sql);
        System.out.println(sparams);
        System.out.println("sparams.toArray():"+sparams.toArray());

        return BaseDAO.executeQuery(sql,sparams.toArray());

    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        String sql="select classId,className from class"+
                "   where classId=?";
        Object[] params={classId};
        List<Map<String,Object>> rows = BaseDAO.executeQuery(sql,params);
        if(rows.size()>0){
            Map<String,Object> map= rows.get(0);

            ClassInfo classInfo=new ClassInfo(
                    (Integer) map.get("classId"), //注意强转化 get得到的是Object类型(鼠标放在get上看)
                    (String) map.get("className")
            );
            System.out.println(classInfo);
            return classInfo;
        }
        return null;
    }

    @Override
    public List<Map<String, Object>> listAll() {
        String sql="select * from class";
        return BaseDAO.executeQuery(sql,null);
    }

    @Override
    public int insert(ClassInfo classInfo) {
        String sql="insert into class"+
                "   (className)"+
                "   values"+
                "   (?)";
        Object[] params={classInfo.getClassName()};
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int update(ClassInfo classInfo) {
        String sql="update class"+
                "   set className=?"+
                "   where classId=?";
        Object[] params={
                classInfo.getClassName(),
                classInfo.getClassId()
        };
        return BaseDAO.executeUpdate(sql,params);
    }

    @Override
    public int delete(Integer classId) {
        String sql="delete from class"+  //注意delete写法
                "   where classId=?";
        Object[] params={classId};
        return BaseDAO.executeUpdate(sql,params);
    }
}

IClassService:

package com.service;

import com.entity.ClassInfo;
import com.entity.PageDate;

import java.util.List;
import java.util.Map;

public interface IClassService {
    List<Map<String,Object>> listAll();

    ClassInfo getByClassId(Integer classId);

    List<Map<String,Object>> listByCon(String searchClassName);

    PageDate listByPage(Integer pageNo,Integer pageSize);

    int insert(ClassInfo classInfo);
    int update(ClassInfo classInfo);
    int delete(Integer classId);
}

ClassServiceImpl:

package com.service.impl;

import com.dao.IClassDAO;
import com.dao.impl.ClassDAOImpl;
import com.entity.ClassInfo;
import com.entity.PageDate;
import com.service.IClassService;

import java.util.List;
import java.util.Map;

public class ClassServiceImpl implements IClassService {

    IClassDAO classDAO=new ClassDAOImpl();

    @Override
    public PageDate listByPage(Integer pageNo, Integer pageSize) {
        return classDAO.listByPage(pageNo,pageSize);
    }

    @Override
    public List<Map<String, Object>> listByCon(String searchClassName) {
        return classDAO.listByCon(searchClassName);
    }

    @Override
    public ClassInfo getByClassId(Integer classId) {
        return classDAO.getByClassId(classId);
    }

    @Override
    public List<Map<String, Object>> listAll() {
        return classDAO.listAll();
    }

    @Override
    public int insert(ClassInfo classInfo) {
        return classDAO.insert(classInfo);
    }

    @Override
    public int update(ClassInfo classInfo) {
        return classDAO.update(classInfo);
    }

    @Override
    public int delete(Integer classId) {
        return classDAO.delete(classId);
    }
}

ClassInfoServlet:

package com.servlet;

import com.entity.ClassInfo;
import com.entity.PageDate;
import com.mysql.cj.util.StringUtils;
import com.service.IClassService;
import com.service.impl.ClassServiceImpl;

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;
import java.util.Map;

@WebServlet(urlPatterns = "/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
    IClassService classService=new ClassServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");

        String uri=req.getRequestURI();
        String process=uri.substring(uri.lastIndexOf("/")+1);
        System.out.println("截取字段:"+process);

        switch (process){
            case "query":
                this.query(req,resp);
                break;
            case "queryByPage":
                this.queryByPage(req,resp);
                break;
            case "toAdd":
                this.toAdd(req,resp);
                break;
            case "add":
                this.add(req,resp);
                break;
            case "toUpdate":
                this.toUpdate(req,resp);
                break;
            case "update":
                this.update(req,resp);
                break;
            case "delete":
                this.delete(req,resp);
                break;
        }
    }

    private void queryByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer pageNo=1;
        Integer pageSize=3;

        if(req.getParameter("pageNo")!=null){
            pageNo=Integer.parseInt(req.getParameter("pageNo"));
        }
        if(req.getParameter("pageSize")!=null){
            pageSize= Integer.parseInt(req.getParameter("pageSize"));  //Integet.valueOf()和Integet.parseInt()
        }

        //获取查询条件
        String searchClassName=req.getParameter("searchClassName");
        System.out.println("searchClassName:"+searchClassName);
        System.out.println("pageNo:"+pageNo);
        System.out.println("pageSize:"+pageSize);

        //调用分页查询
        PageDate pageDate=classService.listByPage(pageNo,pageSize);
        System.out.println("pageDate"+pageDate);

        //存储到req,跳转到页面
        req.setAttribute("pd",pageDate);
        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }

//    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        List<Map<String,Object>> classList=classService.listAll();
//
//        req.setAttribute("classList",classList);
//        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
//    }


    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String searchClassName=req.getParameter("searchClassName");
        List<Map<String,Object>> classList=classService.listByCon(searchClassName);
        //用的特别巧妙,如果searchClassName为空,将查询所有;如果不为空,将模糊查询得相关的数据
        System.out.println(classList);

        req.setAttribute("classList",classList);
        req.getRequestDispatcher("/classList.jsp").forward(req,resp);
    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("/classAdd.jsp").forward(req,resp);
    }

    private void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String className=req.getParameter("className"); //注意 设置值关键字 从输入框获取值的关键字
        ClassInfo ci=new ClassInfo(className);

        int count=classService.insert(ci);

        if(count==1){
            System.out.println("插入成功!");
            this.query(req,resp);
        }else{
            System.out.println("插入失败!");
        }
    }

    private void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        //根据编号,查询要修改的班级对象
        ClassInfo classInfo =  classService.getByClassId(classId);
        //将要修改的班级对象,存储到request中,带到页面上,呈现出来
        req.setAttribute("classInfo",classInfo);
        //跳转到修改页面
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);

        req.setAttribute("classInfo",classInfo);
        req.getRequestDispatcher("/classUpdate.jsp").forward(req,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId = Integer.parseInt(req.getParameter("classId"));
        String className = req.getParameter("className");
        ClassInfo classInfo = new ClassInfo(classId,className);
        //调用修改
        int count = classService.update(classInfo);
        if(count==1){
            //修改成功,则重新显示
            this.query(req,resp);
        }else{
            //跳转到失败
        }

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Integer classId= Integer.parseInt(req.getParameter("classId"));
        int count =classService.delete(classId);
        if(count==1){
            System.out.println("删除成功!");
            this.query(req,resp);
        }else{
            System.out.println("删除失败!");
        }
    }
}

index.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/1
  Time: 20:26
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  <a href="${pageContext.request.contextPath}/StudentInfoServlet ">学生信息</a>
  <a href="${pageContext.request.contextPath}/ClassInfoServlet/query">班级信息</a>
  <a href="${pageContext.request.contextPath}/ClassInfoServlet/queryByPage">分页信息</a>
 
  </body>
</html>

classList.jsp:

<%--
  Created by IntelliJ IDEA.
  User: 33154
  Date: 2022/8/2
  Time: 1:18
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
<%--    <%=request.getAttribute("classList")%>--%>
</head>
<body>
    班级数据:${classList}
    <table border="1" align="center" width="50%">
        <tr>
            <td colspan="3">
                <a href="${pageContext.request.contextPath}/ClassInfoServlet/toAdd">添加</a>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <form id="searchFrm" action="${pageContext.request.contextPath}/ClassInfoServlet/queryByPage" method="get">
                    班级:<input type="text" id="searchCls" name="searchClassName" value="${param.searchClassName}"/> <%--value--%>
                    <input type="submit" value="搜索" />
                    <input type="hidden" name="pageNo" id="pageNo" />
                    <input type="hidden" name="pageSize" id="pageSize" />
                </form>
            </td>
        </tr>
        <tr>
            <th>班级编号</th>
            <th>班级名称</th>
            <th>操作</th>
        </tr>
        <c:forEach items="${pd.data}" var="pdd">
            <tr>
                <td>${pdd.classId}</td>
                <td>${pdd.className}</td>
                <td>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/toUpdate?classId=${pdd.classId}">修改</a>
                    <a href="${pageContext.request.contextPath}/ClassInfoServlet/delete?classId=${pdd.classId}"
                    onclick="return confirm('你确定要删除吗?')">
                        删除
                    </a>
                </td>
            </tr>
        </c:forEach>
        <%--生成分页信息--%>
        <tr>
            <td colspan="3">
                当前页${pd.pageNo}/共${pd.totalPage}页 |
                总记录数:${pd.totalCount} |
                <c:forEach begin="1" end="${pd.totalPage}" var="i">
                    <c:if test="${pd.pageNo==i}">
                        <span>${i}</span>
                    </c:if>
                    <c:if test="${pd.pageNo!=i}">
                        <a href="javascript:jumpPage(${i})">${i}</a>
                    </c:if>
                    &nbsp;&nbsp;
                </c:forEach>
                每页
                    <select name="pageSize" id="ps" onchange="changePageSize(this.value)"> <%--onchange--%>
                        <option value="2" ${pd.pageSize==2?'selected':''}>2</option>  <%--option value="2"和2哪个在起作用?--%>
                        <option value="3" ${pd.pageSize==3?'selected':''}>3</option>    <%--注意:代码运行到这里出错了--%>
                        <option value="5" ${pd.pageSize==5?'selected':''}>5</option>
                    </select>
                条
            </td>
        </tr>
    </table>
    <script type="text/javascript">
        //切换每页记录数
        function changePageSize(size){
            window.location.href="${pageContext.request.contextPath}/ClassInfoServlet/queryByPage?pageSize="+size;
        }

        //跳转分页
        function jumpPage(no){
            document.getElementById("pageNo").value=no;
            document.getElementById("pageSize").value=ps.value;  //ps在 (每页。。条) 下一行的位置
            searchFrm.submit();
        }
    </script>
</body>
</html>

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';

KQC 0803 条件查询(待补充)

图书条件查询:创建图书表,编号,书名,作者,价格,出版日期。
要求可以按照书名和作者进行模糊查询。

// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118078.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!