servlet+jsp+druid+ajax+bootstrap+jqPaginator增删改查以及分页

druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/j220601?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai&useServerPrepStmts=true
username=root
password=130720
#初始化连接数量
initialSize=5
#最大连接数
maxActive=10
#最大等待时间
maxWait=3000

utils工具包

JdbcUtil--获取数据库连接对象

package com.hqyj.zyw.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @ClassName JdbcUtil
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:19
 * @Version 1.0
 **/
public class JdbcUtil {
    private static DataSource dataSource;
    static{
        try {
            //加载配置文件
            Properties pro = new Properties();
            //通过类加载器获取字节流
            InputStream in = JdbcUtil.class.getClassLoader().getResourceAsStream("druid.properties");
            //从字节流中读取属性列表
            pro.load(in);
            //初始化连接池对象
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //获取连接池对象
    public static DataSource getDataSource(){
        return dataSource;
    }
    //获取连接Connection对象
    public static Connection getConnection() {
        try {
            Connection conn=dataSource.getConnection();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }

    }
    public static void free(Connection conn,PreparedStatement ps,ResultSet rs){
        try {
            if (rs!=null){
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (ps!=null){
                ps.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            if (conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

PageUtil--分页工具

package com.hqyj.zyw.utils;

import java.util.List;

/**
 * @ClassName PageUtil
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/9 11:02
 * @Version 1.0
 **/
public class PageUtil<T> {
    //总页数
    private int totalPages;
    //每页展示的条数
    private int pageSize;
    //当前页码
    private int pageNum;
    //总条数
    private int totalCounts;
    //存放查询出的数据
    private List<T> pageInfo;

    public int getTotalPages() {
        return totalPages;
    }

    public void setTotalPages(int totalPages) {
        this.totalPages = totalPages;
    }

    public int getPageSize() {
        return pageSize;
    }

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

    public int getPageNum() {
        return pageNum;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public int getTotalCounts() {
        return totalCounts;
    }

    public void setTotalCounts(int totalCounts) {
        this.totalCounts = totalCounts;
    }

    public List<T> getPageInfo() {
        return pageInfo;
    }

    public void setPageInfo(List<T> pageInfo) {
        this.pageInfo = pageInfo;
    }
}

entity包

User

package com.hqyj.zyw.entity;

import java.util.Objects;

/**
 * @ClassName User
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:29
 * @Version 1.0
 **/
public class User {
    private Integer id;
    private String userName;
    private Integer userAge;
    private String userSex;
    private String userTel;
    private String userPwd;

    public User() {
    }

    public User(Integer id, String userName, Integer userAge, String userSex, String userTel, String userPwd) {
        this.id = id;
        this.userName = userName;
        this.userAge = userAge;
        this.userSex = userSex;
        this.userTel = userTel;
        this.userPwd = userPwd;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Integer getUserAge() {
        return userAge;
    }

    public void setUserAge(Integer userAge) {
        this.userAge = userAge;
    }

    public String getUserSex() {
        return userSex;
    }

    public void setUserSex(String userSex) {
        this.userSex = userSex;
    }

    public String getUserTel() {
        return userTel;
    }

    public void setUserTel(String userTel) {
        this.userTel = userTel;
    }

    public String getUserPwd() {
        return userPwd;
    }

    public void setUserPwd(String userPwd) {
        this.userPwd = userPwd;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return Objects.equals(id, user.id) &&
                Objects.equals(userName, user.userName) &&
                Objects.equals(userAge, user.userAge) &&
                Objects.equals(userSex, user.userSex) &&
                Objects.equals(userTel, user.userTel) &&
                Objects.equals(userPwd, user.userPwd);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, userName, userAge, userSex, userTel, userPwd);
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", userAge=" + userAge +
                ", userSex='" + userSex + '\'' +
                ", userTel='" + userTel + '\'' +
                ", userPwd='" + userPwd + '\'' +
                '}';
    }
}

filter包--拦截器

CharsetFilter--将所有的请求与响应的字符集改为UTF-8

package com.hqyj.zyw.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @ClassName CharsetFilter
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:39
 * @Version 1.0
 **/
public class CharsetFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

dao包

UserDao

package com.hqyj.zyw.dao;

import com.hqyj.zyw.entity.User;

import java.util.List;

public interface UserDao {
    public List<User> queryUser(int pageNum,int pageSize);
    public int deleteUser(int id);
    public User queryUserById(int id);
    public int updateUser(User user);
    public int addUser(User user);
    public List<User> condQueryUser(String userName,String userTel);
    public int selectCountAll();
}

UserDaoImpl

package com.hqyj.zyw.dao.impl;

import com.hqyj.zyw.dao.UserDao;
import com.hqyj.zyw.entity.User;
import com.hqyj.zyw.utils.JdbcUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName UserDaoImpl
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:29
 * @Version 1.0
 **/
public class UserDaoImpl implements UserDao {
    private Connection conn=null;
    private PreparedStatement ps=null;
    private ResultSet rs=null;
    @Override
    public List<User> queryUser(int pageNum, int pageSize) {
        conn = JdbcUtil.getConnection();
        String sql="select * from user limit ?,?";
        try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1, (pageNum-1)*pageSize);
            ps.setInt(2, pageSize);
            rs=ps.executeQuery();
            List<User> users=new ArrayList<>();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("user_name"));
                user.setUserAge(rs.getInt("user_age"));
                user.setUserSex(rs.getString("user_sex"));
                user.setUserTel(rs.getString("user_tel"));
                user.setUserPwd(rs.getString("user_pwd"));
                users.add(user);
            }
            return users;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUtil.free(conn,ps,rs);
        }
        return null;
    }

    @Override
    public int deleteUser(int id) {
        conn = JdbcUtil.getConnection();
        String sql="delete from user where id=?";
        try {
            ps=conn.prepareStatement(sql);
            ps.setInt(1, id);
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtil.free(conn,ps,rs);
        }
        return 0;
    }

    @Override
    public User queryUserById(int id) {
        conn= JdbcUtil.getConnection();
        String sql="select * from user where id=?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setInt(1, id);
            rs = ps.executeQuery();
            User user = new User();
            if (rs.next()) {
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("user_name"));
                user.setUserAge(rs.getInt("user_age"));
                user.setUserSex(rs.getString("user_sex"));
                user.setUserTel(rs.getString("user_tel"));
                user.setUserPwd(rs.getString("user_pwd"));
            }
            return user;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.free(conn,ps,rs);
        }
        return null;
    }

    @Override
    public int updateUser(User user) {
        conn= JdbcUtil.getConnection();
        String sql="update user set user_name=?, user_age=?, user_sex=?, user_tel=? where id=?";
        try {
            ps=conn.prepareStatement(sql);
            ps.setString(1,user.getUserName());
            ps.setInt(2,user.getUserAge());
            ps.setString(3,user.getUserSex());
            ps.setString(4,user.getUserTel());
            ps.setInt(5,user.getId());
            int num=ps.executeUpdate();
            return num;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.free(conn,ps,null);
        }
        return 0;
    }

    @Override
    public int addUser(User user) {
        conn=JdbcUtil.getConnection();
        String sql="insert into user(user_name, user_age, user_sex, user_tel) values (?, ?, ?,?)";
        try {
            ps = conn.prepareStatement(sql);
            ps.setString(1,user.getUserName());
            ps.setInt(2,user.getUserAge());
            ps.setString(3,user.getUserSex());
            ps.setString(4,user.getUserTel());
            int num = ps.executeUpdate();
            return num;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.free(conn,ps,null);
        }
        return 0;
    }

    @Override
    public List<User> condQueryUser(String userName, String userTel) {
        conn= JdbcUtil.getConnection();
        String sql="select * from user where 1=1 ";
        List<Object> params = new ArrayList<>();
        if(!userName.equals("")) {
            sql+="and user_name = ? ";
            params.add(userName);
        }
        if (!userTel.equals("")) {
            sql+="and user_tel = ? ";
            params.add(userTel);
        }
        try {
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < params.size(); i++) {
                ps.setObject(i + 1, params.get(i));
            }
            rs = ps.executeQuery();
            List<User> users = new ArrayList<>();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUserName(rs.getString("user_name"));
                user.setUserAge(rs.getInt("user_age"));
                user.setUserSex(rs.getString("user_sex"));
                user.setUserTel(rs.getString("user_tel"));
                user.setUserPwd(rs.getString("user_pwd"));
                users.add(user);
            }
            return users;
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.free(conn,ps,null);
        }
        return null;
    }

    @Override
    public int selectCountAll() {
        conn= JdbcUtil.getConnection();
        String sql="select count(*) num from user";
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery();
            if (rs.next()) {
                int totalCounts = rs.getInt("num");
                return totalCounts;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            JdbcUtil.free(conn,ps,null);
        }
        return 0;
    }
}

service包

UserService

package com.hqyj.zyw.service;

import com.hqyj.zyw.entity.User;
import com.hqyj.zyw.utils.PageUtil;

import java.util.List;

/**
 * @ClassName UserService
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:26
 * @Version 1.0
 **/
public interface UserService {
    public PageUtil<User> queryUser(String pageNum, String pageSize);
    public String deleteUser(int id);
    public User queryUserById(int id);
    public String updateUser(User user);
    public String addUser(User user);
    public List<User> condQueryUser(String userName, String userTel);
}

UserServiceImpl

package com.hqyj.zyw.service.impl;

import com.hqyj.zyw.dao.UserDao;
import com.hqyj.zyw.dao.impl.UserDaoImpl;
import com.hqyj.zyw.entity.User;
import com.hqyj.zyw.service.UserService;
import com.hqyj.zyw.utils.PageUtil;

import java.util.Collections;
import java.util.List;
import java.util.Optional;

/**
 * @ClassName UserServiceImpl
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:27
 * @Version 1.0
 **/
public class UserServiceImpl implements UserService {
    private final UserDao userDao=new UserDaoImpl();

    @Override
    public PageUtil<User> queryUser(String pageNum, String pageSize) {
        int pageNumber = Integer.parseInt(pageNum);
        if (pageNumber==-1) {
            pageNumber=1;
        }
        PageUtil<User> pageUser = new PageUtil<>();
        int totalCounts = userDao.selectCountAll();
        pageUser.setTotalCounts(totalCounts);
        pageUser.setPageSize(Integer.parseInt(pageSize));
        pageUser.setPageNum(pageNumber);
        pageUser.setPageInfo(Optional.ofNullable(userDao.queryUser(pageNumber, Integer.parseInt(pageSize))).orElse(Collections.emptyList()));
        return pageUser;
    }

    @Override
    public String deleteUser(int id) {
        int num = userDao.deleteUser(id);
        if (num>0){
            return "success";
        }else {
            return "fail";
        }
    }

    @Override
    public User queryUserById(int id) {
        return userDao.queryUserById(id);
    }

    @Override
    public String updateUser(User user) {
        int num = userDao.updateUser(user);
        if (num > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    @Override
    public String addUser(User user) {
        int num = userDao.addUser(user);
        if (num > 0) {
            return "success";
        } else {
            return "fail";
        }
    }

    @Override
    public List<User> condQueryUser(String userName, String userTel) {
        return Optional.ofNullable(userDao.condQueryUser(userName, userTel)).orElse(Collections.emptyList());
    }
}

controller包

UserController

package com.hqyj.zyw.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hqyj.zyw.entity.User;
import com.hqyj.zyw.service.UserService;
import com.hqyj.zyw.service.impl.UserServiceImpl;
import com.hqyj.zyw.utils.PageUtil;

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;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author ZhuYouWan
 * @Date 2022/8/8 11:26
 * @Version 1.0
 **/
@WebServlet("/user")
public class UserController extends HttpServlet {
    private final UserService userService=new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=req.getParameter("_method");
        if (method.equals("queryUser")) {
            queryUser(req,resp);
        }else if (method.equals("deleteUser")){
            deleteUser(req,resp);
        }else if (method.equals("queryUserById")){
            queryUserById(req,resp);
        }else if (method.equals("updateUser")){
            updateUser(req,resp);
        }else if (method.equals("addUser")){
            addUser(req,resp);
        }else if (method.equals("condQueryUser")){
            condQueryUser(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    public void queryUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String pageNum = req.getParameter("pageNum");
        String pageSize = req.getParameter("pageSize");
        PageUtil<User> userPage = userService.queryUser(pageNum, pageSize);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(userPage);
        resp.getWriter().write(json);
    }
    public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int userId=Integer.parseInt(id);
        String msg = userService.deleteUser(userId);
        resp.getWriter().write(msg);
    }
    public void queryUserById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int userId=Integer.parseInt(id);
        User user = userService.queryUserById(userId);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(user);
        resp.getWriter().write(json);
    }
    public void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        int userId=Integer.parseInt(id);
        String userName = req.getParameter("userName");
        String userAge = req.getParameter("userAge");
        int age = Integer.parseInt(userAge);
        String userSex = req.getParameter("userSex");
        String userTel = req.getParameter("userTel");
        User user = new User();
        user.setId(userId);
        user.setUserName(userName);
        user.setUserAge(age);
        user.setUserSex(userSex);
        user.setUserTel(userTel);
        String msg = userService.updateUser(user);
        resp.getWriter().write(msg);
    }
    public void addUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userName = req.getParameter("userName");
        String userAge = req.getParameter("userAge");
        int age = Integer.parseInt(userAge);
        String userSex = req.getParameter("userSex");
        String userTel = req.getParameter("userTel");
        User user = new User();
        user.setUserName(userName);
        user.setUserAge(age);
        user.setUserSex(userSex);
        user.setUserTel(userTel);
        String msg = userService.addUser(user);
        resp.getWriter().write(msg);
    }
    public void condQueryUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String userName = req.getParameter("userName");
        String userTel = req.getParameter("userTel");
        List<User> users = userService.condQueryUser(userName, userTel);
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(users);
        resp.getWriter().write(json);
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <filter>
        <filter-name>CharsetFilter</filter-name>
        <filter-class>com.hqyj.zyw.filter.CharsetFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

user.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户列表</title>
    <link rel="stylesheet" type="text/css" href="static/css/bootstrap.min.css">
    <script src="static/js/jquery-3.6.0.min.js"></script>
    <script src="static/js/bootstrap.min.js"></script>
    <script src="static/js/jqPaginator.js"></script>
</head>
<body>
<!-- 添加搜索 -->
<div class="container" style="margin-top: 10px">
    <div class="row">
        <div class="col-md-6">
            <button type="button" class="btn btn-info" data-toggle="modal" data-target="#myModal1">添加</button>
        </div>
        <div class="col-md-6" style="text-align: right">
            <form class="form-inline">
                <div class="form-group">
                    <label for="sUserName">用户名</label>
                    <input type="text" class="form-control" id="sUserName" placeholder="用户名">
               </div>
                <div class="form-group">
                    <label for="sUserTel">手机号</label>
                    <input type="text" class="form-control" id="sUserTel" placeholder="手机号">
                </div>
                <button type="button" class="btn btn-success" onclick="condQueryUser();">搜索</button>
            </form>
        </div>
    </div>
</div>
<!-- 表格内容 -->
<div class="container">
    <div class="row">
        <div class="col-sm-12">
            <table class="table table-striped table-bordered table-hover table-condensed" style="text-align: center;">
                <thead>
                <tr>
                    <td>姓名</td>
                    <td>年龄</td>
                    <td>性别</td>
                    <td>电话</td>
                    <td>操作</td>
                </tr>
                </thead>
                <tbody id="res"></tbody>
                <tfoot>
                <tr>
                    <td colspan="5">
                        <ul class="pagination" id="pagination1"></ul>
                    </td>
                </tr>
                </tfoot>
            </table>
        </div>
    </div>
</div>
<!-- Modal 修改-->
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel">用户修改</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal">
                                <input type="hidden" id="userId">
                                <div class="form-group">
                                    <label for="userName" class="col-md-2 control-label">用户名</label>
                                    <div class="col-md-10">
                                        <input class="form-control" type="text" name="userName" placeholder="用户名" id="userName">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="userAge" class="col-md-2 control-label">年龄</label>
                                    <div class="col-md-10">
                                        <input type="text" name="userAge" id="userAge" class="form-control" placeholder="年龄">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-md-2 control-label">性别</label>
                                    <div class="col-md-10">
                                        <div class="radio-inline">
                                            <input type="radio" name="sex" id="male" value="男">男
                                        </div>
                                        <div class="radio-inline">
                                            <input type="radio" name="sex" id="female" value="女">女
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="userTel" class="col-md-2 control-label">电话</label>
                                    <div class="col-md-10">
                                        <input type="text" name="userTel" id="userTel" class="form-control" placeholder="电话号码">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="updateUser();">修改</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- Modal 添加-->
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="modal fade" id="myModal1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog" role="document">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                            <h4 class="modal-title" id="myModalLabel1">添加用户</h4>
                        </div>
                        <div class="modal-body">
                            <form class="form-horizontal">
                                <div class="form-group">
                                    <label for="name" class="col-md-2 control-label">用户名</label>
                                    <div class="col-md-10">
                                        <input class="form-control" type="text" name="userName" placeholder="用户名" id="name">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="age" class="col-md-2 control-label">年龄</label>
                                    <div class="col-md-10">
                                        <input type="text" name="userAge" id="age" class="form-control" placeholder="年龄">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-md-2 control-label">性别</label>
                                    <div class="col-md-10">
                                        <div class="radio-inline">
                                            <input type="radio" name="gender" id="boy" value="男">男
                                        </div>
                                        <div class="radio-inline">
                                            <input type="radio" name="gender" id="girl" value="女">女
                                        </div>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label for="tel" class="col-md-2 control-label">电话</label>
                                    <div class="col-md-10">
                                        <input type="text" name="userTel" id="tel" class="form-control" placeholder="电话号码">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                            <button type="button" class="btn btn-primary" onclick="addUser();">添加</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    let total=0;//总条数
    let visiblePages = 3;//显示的分页按钮数
    let current_Page = 0;//当前页码
    let pageSize = 3;//每页展示的条数
    //页面加载完成执行
    $(function(){
        showUser(-1);
        pageInit();
    });
    //查询全部用户
    function showUser(pageNum) {
        $.ajax({
            url: "user",
            type: "POST",
            async: false,
            data: {"_method":"queryUser","pageNum":pageNum,"pageSize":pageSize},
            dataType: "json",
            success: function(data){
                if(pageNum==-1) {
                    total = data.totalCounts;
                    current_Page = data.pageNum;
                }
                let res = "";
                for (let i = 0; i < data.pageInfo.length; i++) {
                    res+="<tr><td>"+data.pageInfo[i].userName + "</td><td>"+data.pageInfo[i].userAge + "</td><td>"+data.pageInfo[i].userSex + "</td><td>"+data.pageInfo[i].userTel+"</td>"+
                        "<td><button type='button' class='btn btn-danger' onclick='deleteUser("+data.pageInfo[i].id+")'>删除</button>"+
                        "&nbsp;&nbsp;&nbsp;&nbsp;<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#myModal' onclick='queryUserById("+data.pageInfo[i].id+")'>修改</button></td><tr>";
                }
                $("#res").html(res);
            }
        });
    }
    //分页
    function pageInit() {
        $('#pagination1').jqPaginator({
            pageSize: pageSize,//每页显示的条数
            visiblePages: visiblePages,//显示分页的按钮数
            currentPage: current_Page,//当前页码
            totalCounts: total,//总条数
            first: '<li class="first"><a href="javascript:void(0);">第一页</a></li>',
            prev: '<li class="prev"><a href="javascript:void(0);">前一页</a></li>',
            next: '<li class="next"><a href="javascript:void(0);">下一页</a></li>',
            last: '<li class="last"><a href="javascript:void(0);">最后一页</a></li>',
            page: '<li class="page"><a href="javascript:void(0);">{{page}}</a></li>',
            onPageChange: function (num) {
                /* num代表改变过后的页码 */
                showUser(num);
            }
        });
    }
    //删除用户
    function deleteUser(id) {
        let isDel=confirm("是否确定删除?");
        if(isDel){
            $.ajax({
                url:"user",
                type:"GET",
                data: {"_method":"deleteUser","id":id},
                dataType: "text",
                success: function(data){
                    if(data=="success"){
                        showUser();
                    }
                }
            });
        }
    }
    //根据ID查询用户
    function queryUserById(id) {
        $.ajax({
            url:"user",
            type:"GET",
            data: {"_method":"queryUserById","id":id},
            dataType: "json",
            success: function(data){
                $("#userId").val(data.id);
                $("#userName").val(data.userName);
                $("#userAge").val(data.userAge);
                $("#userTel").val(data.userTel);
                if (data.userSex=="男"){
                    $("#male").prop("checked", true);
                }else {
                    $("#female").prop("checked", true);
                }
            }
        });
    }
    //更新用户
    function updateUser() {
        let id=$("#userId").val();
        let userName=$("#userName").val();
        let userAge=$("#userAge").val();
        let userSex=$("input[name='sex']:checked").val();
        let userTel=$("#userTel").val();
        $.ajax({
            url:"user",
            type:"POST",
            data:{
                "_method":"updateUser",
                "id":id,
                "userName":userName,
                "userAge":userAge,
                "userSex":userSex,
                "userTel":userTel
            },
            dataType: "text",
            success: function(data){
                if(data=="success"){
                    $('#myModal').modal('hide')
                    showUser();
                    alert("修改成功");
                }
            }
        });
    }
    //添加用户
    function addUser() {
        let userName=$("#name").val();
        let userAge=$("#age").val();
        let userSex=$("input[name='gender']:checked").val();
        let userTel=$("#tel").val();
        $.ajax({
            url:"user",
            type:"POST",
            data: {
                "_method": "addUser",
                "userName":userName,
                "userAge":userAge,
                "userSex":userSex,
                "userTel":userTel
            },
            dataType: "text",
            success: function(data){
                if(data=="success") {
                    $('#myModal1').modal('hide')
                    showUser();
                    alert("添加成功");
                }
            }
        });
    }
    //搜索用户
    function condQueryUser() {
        let userName=$("#sUserName").val();
        let userTel=$("#sUserTel").val();
        $.ajax({
            url:"user",
            type:"POST",
            data: {
                "_method": "condQueryUser",
                "userName": userName,
                "userTel":userTel
            },
            dataType: "json",
            success:function (data) {
                console.log(data);
                $("#res").html("");
                let res = "";
                for (let i = 0; i < data.length; i++) {
                    res+="<tr><td>"+data[i].userName + "</td><td>"+data[i].userAge + "</td><td>"+data[i].userSex + "</td><td>"+data[i].userTel+"</td>"+
                        "<td><button type='button' class='btn btn-danger' onclick='deleteUser("+data[i].id+")'>删除</button>"+
                        "&nbsp;&nbsp;&nbsp;&nbsp;<button type='button' class='btn btn-primary' data-toggle='modal' data-target='#myModal' onclick='queryUserById("+data[i].id+")'>修改</button></td><tr>";
                }
                $("#res").html(res);
            }
        });
    }
</script>
</body>
</html>

效果图

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值