演示效果
https://www.bilibili.com/video/BV1fa411x7om?spm_id_from=333.999.0.0
步骤1:创建一个Maven项目
步骤2:规划实验项目的基本结构
步骤3:创建持久化类
在src/main/java/com/itheima目录下,创建domain包,在包中创建持久化类User;
package com.itheima.domain;
public class User {
private int id;
private String name;
private String password;
private String creation_time;
public User(){}
public User(int id, String name, String password, String creation_time) {
this.id = id;
this.name = name;
this.password = password;
this.creation_time = creation_time;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCreation_time() {
return creation_time;
}
public void setCreation_time(String creation_time) {
this.creation_time = creation_time;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", creation_time='" + creation_time + '\'' +
'}';
}
}
步骤4:实现DAO层
在src/main/java/com.itheima目录下,创建dao包,在包中创建用户接口UserMapper,并在接口中定义getUserList()、getUserName()、getUserID()、delUserInfo()、updateUserInfo()、insertUserInfo方法;在映射文件中实现、、和4个元素
UserMapper代码
// 用户接口文件
import com.itheima.domain.User;
import java.util.List;
public interface UserMapper {
// 获取用户信息
// @Select("select * from users")
List<User> getUserList();
// 根据姓名搜索
List<User> getUserName(String name);
// 根据id搜索
List<User> getUserID(int id);
// 根据id 删除用户信息
int delUserInfo(String ids);
// 修改用户信息
int updateUserInfo(User user);
// 添加用户信息
int insertUserInfo(User user);
}
UserMapper.xml代码
<?xml version="1.0" encoding="UTF8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.itheima.dao.UserMapper">
<select id="getUserList" resultType="com.itheima.domain.User">
select * from users
</select>
<select id="getUserName" resultType="com.itheima.domain.User">
select * from users where name like #{name}
</select>
<!-- 返回查询结果条数-->
<select id="getUserID" resultType="com.itheima.domain.User">
select * from users where id = #{id}
</select>
<delete id="delUserInfo" parameterType="com.itheima.domain.User">
delete from users where id = #{ids}
</delete>
<update id="updateUserInfo" parameterType="com.itheima.domain.User">
update users set id=#{id},name=#{name},password=#{password},creation_time=#{creation_time} where id=#{id}
</update>
<insert id="insertUserInfo" parameterType="com.itheima.domain.User">
insert into users(id,name,password,creation_time) values(#{id},#{name},#{password},#{creation_time})
</insert>
</mapper>
步骤5:实现Servlet
在src/main/java/com.itheima目录下,创建servlet包,在包中创建userlistAddServlet,
userlistDelServlet、userlistServlet、userlistUpdateServlet方法。
userlistAddServlet代码
package com.itheima.servlet;
import com.alibaba.fastjson.JSON;
import com.itheima.dao.UserMapper;
import com.itheima.domain.User;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/userlistAddServlet")
public class userlistAddServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*设置响应的文本类型为HTML,字符编码为utf-8*/
request.setCharacterEncoding("utf-8");
/*转换字符类型*/
response.setContentType("text/html;charset=utf-8");
// 获取前端传过来的 data
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
String creation_time = request.getParameter("creation_time");
System.out.println("id="+id);
List<User> user = null; // 初始值
PrintWriter out = response.getWriter();
int result=0;
try {
SqlSession sqlSession = MybatisUtils.getSqlSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 在用户添加之前,先判断ID是否被占用
user= userMapper.getUserID(id);
// 如果user.size()>0 说明改ID被占用,出现提示信息
if(user.size()>0){
result=-1;
}else {
// 该ID没有被占用,添加用户
int num =userMapper.insertUserInfo(new User(id,name,password,creation_time));
if(num>0) {
System.out.println("插入成功");
result=1;
}
}
}catch (Exception e){
e.printStackTrace();
}
// 向ajax 返回结果
out.println(result);
}
}
userlistDelServlet代码
package com.itheima.servlet;
import com.alibaba.fastjson.JSON;
import com.itheima.dao.UserMapper;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/userlistDelServlet")
public class userlistDelServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*设置响应的文本类型为HTML,字符编码为utf-8*/
request.setCharacterEncoding("utf-8");
/*转换字符类型*/
response.setContentType("text/html;charset=utf-8");
// 获取 待删除的那行的id
String ids = request.getParameter("ids");
// ids=JSON.toJSONString(ids); // 转换为字符串
ids=ids.replace("["," ").replace("]"," "); // 把[] 变成()
// System.out.println(ids);
int result = 0;//设置默认返回值
try{
SqlSession sqlSession = MybatisUtils.getSqlSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.delUserInfo(ids);
if (num>0){
System.out.println("删除成功!");
result=1;
}
sqlSession.commit();
sqlSession.close();
}catch (Exception e){
e.printStackTrace();
}
// 向ajax放回结果
response.getWriter().println(result);
}
}
userlistServlet代码
package com.itheima.servlet;
import com.alibaba.fastjson.JSON;
import com.itheima.dao.UserMapper;
import com.itheima.domain.User;
import com.itheima.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@WebServlet("/userlistServlet")
public class userlistServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*设置响应的文本类型为HTML,字符编码为utf-8*/
request.setCharacterEncoding("utf-8");
/*转换字符类型*/
response.setContentType("text/html;charset=utf-8");
/**
* 将从数据库查询到的数据转换成json字符串
*/
// name 获取搜索框输入的内容
String name="";
name = request.getParameter("name");
String data="";
PrintWriter out = response.getWriter();
List<User> userList=null;
try {
SqlSession sqlSession = MybatisUtils.getSqlSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
if(name==""){
userList = userMapper.getUserList(); // 显示所有用户信息
}else {
userList = userMapper.getUserName(name); // 根据用户姓名去搜索并且显示相关信息
}
data = JSON.toJSONString(userList);//将集合转换成json字符串
int count=userList.size();//获取学生信息条数
data="{\"total\":"+count+",\"rows\":"+data+"}"; // 转换为bootstrap固定格式 {total:总数,rows:[list集合]}
sqlSession.close(); // 关闭
}catch (Exception e){
e.printStackTrace();
}
out.println(data);
/*System.out.println(data);*/
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
}
userlistUpdateServlet代码
package com.itheima.servlet;
import com.itheima.dao.UserMapper;
import com.itheima.domain.User;
import com.itheima.utils.MybatisUtils;
import com.sun.org.apache.xpath.internal.operations.Number;
import org.apache.ibatis.session.SqlSession;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
@WebServlet("/userlistUpdateServlet")
public class userlistUpdateServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
/*设置响应的文本类型为HTML,字符编码为utf-8*/
request.setCharacterEncoding("utf-8");
/*转换字符类型*/
response.setContentType("text/html;charset=utf-8");
// 获取前端传过来的 data
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
String password = request.getParameter("password");
String creation_time = request.getParameter("creation_time");
// System.out.println("id="+id+name+password+creation_time);
int result=0;
try {
SqlSession sqlSession = MybatisUtils.getSqlSession(true);
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
int num = userMapper.updateUserInfo(new User(id,name,password,creation_time));
if(num>0){
System.out.println("修改成功");
result=1;
}
}catch (Exception e){
e.printStackTrace();
}
// 向ajax放回结果
response.getWriter().println(result);
}
}
步骤6:实现前端界面的功能
<%--
Created by IntelliJ IDEA.
User: Admin
Date: 2022/3/24
Time: 15:31
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户管理</title>
<link rel="stylesheet" href="./css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.css">
<style>
.container{
padding: 20px;
}
.form{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="form-inline">
<button type="button" class="btn btn-info" id="addBtn">添加</button>
<div class="form-group">
<label class="sr-only" for="username">请输入待搜索的姓名</label>
<input type="text" class="form-control" name="username" id="username" placeholder="请输入姓名">
</div>
<button type="submit" class="btn btn-default" id="btnSearch">搜索</button>
</div>
<table class="table table-striped" id="table"></table>
<%--删除按钮模态框--%>
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="delModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="delModalLabel">操作提示:</h4>
</div>
<div class="modal-body">
<input type="hidden" id="del_ids" name="ids" value="">
<h5 id="delBody">确定要删除选中的数据?</h5>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="deleteIds">确定删除</button>
<button type="button" class="btn btn-default" data-dismiss="modal">取消
</button>
</div>
</div>
</div>
</div>
<%--编辑按钮模态框--%>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="ediModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="ediModalLabel">编辑用户信息</h4>
</div>
<div class="modal-body">
<form action="" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label">ID</label>
<div class="col-sm-9">
<input type="text" class="form-control" disabled="disabled" id="modal_id">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-9">
<input type="text" class="form-control"id="modal_name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">密码</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="modal_password">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">注册时间</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="modal_creation_time">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
<button type="button" class="btn btn-primary" id="sava-edit-btn">保存</button>
</div>
</div>
</div>
</div>
<%-- 添加按钮模态框--%>
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="addModalLabel">添加用户信息</h4>
</div>
<div class="modal-body">
<form action="" class="form-horizontal" id="addForm">
<div class="form-group">
<label class="col-sm-2 control-label">ID</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="addmodal_id">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">姓名</label>
<div class="col-sm-9">
<input type="text" class="form-control"id="addmodal_name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">密码</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="addmodal_password">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">注册时间</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="addmodal_creation_time">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="add-close-btn">关闭</button>
<button type="button" class="btn btn-primary" id="add-btn">添加</button>
</div>
</div>
</div>
</div>
<script src="./js/jquery.min.js"></script>
<script src="./js/bootstrap.min.js"></script>
<script src="https://unpkg.com/bootstrap-table@1.15.3/dist/bootstrap-table.min.js"></script>
<script>
// 重新加载列表
$(function() {
load();
});
function load() {
$('#table').bootstrapTable({
method:'get',
url:'http://localhost:8080/china/userlistServlet',
dataType:"json",
striped: true, //是否显示行间隔色
pagination: true, //是否显示分页(*)
paginationLoop: false, //是否开启分页条无限循环,最后一页时点击下一页是否转到第一页
sortable: true, //是否启用排序
sortOrder: "asc", //排序方式
sidePagination: "client", //分页方式:client客户端分页,server服务端分页(*)
pageSize: 5, //每页的记录行数(*)
pageList: [5, 10, 25, 50, 100], //可供选择的每页的行数(*)
showColumns: true, //是否显示所有的列(选择显示的列)
showRefresh: true, //是否显示刷新按钮
clickToSelect: true, //是否启用点击选中行
uniqueId: "ID", //每一行的唯一标识,
showToggle: true, //是否显示详细视图和列表视图的切换按钮
queryParams: function(params) { // 查询数据
var temp = {
rows:params.limit, // 页面大小
page:(params.offset / params.limit) +1, //页码
sort:params.sort, // 排序列名
sortOrder: params.order,//排位命令(desc,asc)
name:$("#username").val(), // 获取搜索框的值
};
return temp;
},
columns:[ // title指表头信息,field是返回的json数据对应的名称
{checkbox:true,visible:true}, //是否显示复选框
{title:'ID',field:'id'},
{title:'姓名',field:'name'},
{title:'密码',field:'password'},
{title:'注册时间',field:'creation_time'},
{title: '操作',//表格中增加按钮
field: 'operation',
width:200,
align:'center',
formatter:function (value,row,index) {
//通过formatter可以自定义列显示的内容
//value:当前field的值,即id
//row:当前行的数据
// index参数是行在当前页面的索引,从0开始
var btn=""
btn+= ' <button type="button" class="btn btn-info" onclick="EditViewById('+ index+')">编辑</button>';
btn+=' <button type="button" class="btn btn-warning" onclick="DeleteByIds(' + row.id + ')">删除</button>';
return btn;
},
}
],
});
}
//定义表格操作 删除"
function DeleteByIds(id){
var ids = [];
ids.push(id);
//alert(JSON.stringify(ids));
//把ids的值给到隐藏输入框
$('#del_ids').val(JSON.stringify(ids));
//调出删除模态框
$("#delModal").modal();
}
// 点 "确定" 按钮发delete请求
$("#deleteIds").click(function() {
var del_ids = $('#del_ids').val();
$.ajax({
cache: false,
url: "http://localhost:8080/china/userlistDelServlet", //url
type: "get", //方法类型
data: {ids: del_ids},
success: function (result) {
//隐藏模态框
$("#delModal").modal('hide');
if (result == 1){
// 此处可以显示一个toastr消息
alert('删除成功!')
// 重新加载
$('#table').bootstrapTable('destroy');
load();
}
else {
alert("删除失败")
}
},
error: function () {
$("#delModal").modal('hide');
// 此处可以显示一个toastr消息
alert("删除失败,服务器异常")
}
});
})
//定义表格操作编辑按钮 title="编辑"
function EditViewById(index){
// alert(index);
// 调出modal 框#}
var row = JSON.stringify($('#table').bootstrapTable('getData')[index]); //获取那行信息
// row=JSON.stringify(row);
row=JSON.parse(row);
// console.log(row)
$("#modal_id").val(row.id);
$("#modal_name").val(row.name);
$("#modal_password").val(row.password);
$("#modal_creation_time").val(row.creation_time);
$("#myModal").modal('show');
}
// 点击 保存 按钮发送请求
$("#sava-edit-btn").click(function () {
$.ajax({
url:"http://localhost:8080/china/userlistUpdateServlet",
type: "post",
dataType: "json",
data:{
id: $("#modal_id").val(),
name: $("#modal_name").val(),
password:$("#modal_password").val(),
creation_time:$("#modal_creation_time").val(),
},
success: function (result) {
//隐藏模态框
$("#myModal").modal('hide');
if (result==1){
// 此处可以显示一个toastr消息
alert('保存成功!')
// 重新加载
$('#table').bootstrapTable('destroy');
load();
}
else {
alert("保存失败")
}
},
error: function () {
$("#myModal").modal('hide');
// 此处可以显示一个toastr消息
alert("删除失败,服务器异常")
}
})
})
// 点击 添加按钮 发送请求
$("#addBtn").click(function () {
$("#addModal").modal('show'); // 显示添加模拟框
})
// 点击添加按钮事件
$("#add-btn").click(function () {
$.ajax({
url:"http://localhost:8080/china/userlistAddServlet",
type: "get",
data:{
id: $("#addmodal_id").val(),
name: $("#addmodal_name").val(),
password:$("#addmodal_password").val(),
creation_time:$("#addmodal_creation_time").val(),
},
success: function (result) {
if (result ==1){
//隐藏模态框
$("#addModal").modal('hide');
// 出现提示信息
alert('添加成功!')
//当模态框完全关闭时的初始化
$('#addModal').on('hidden.bs.modal', function (e) {
//清除模态框中的内容
document.getElementById("addForm").reset();
}).modal('hide');
// 重新加载
$('#table').bootstrapTable('destroy');
load();
}else if(result == -1){
alert('该ID已经被占用,请重新输入');
} else {
//隐藏模态框
$("#addModal").modal('hide');
alert("添加失败")
}
},
error: function () {
$("#addModal").modal('hide');
// 此处可以显示一个toastr消息
alert("删除失败,服务器异常")
}
})
})
// 点击关闭按钮事件,对模态框进行初始化
$("#add-close-btn").click(function () {
//当模态框完全关闭时的初始化
$('#addModal').on('hidden.bs.modal', function (e) {
//清除模态框中的内容
document.getElementById("addForm").reset();
}).modal('hide');
})
// 搜索查询按钮触发事件
$('#btnSearch').click(function () {
$('#table').bootstrapTable('refresh'); // 刷新url
$("#username").val();
})
</script>
</body>
</html>
步骤7:启动项目,测试功能
将项目部署在Tomcat服务器并启动项目,访问用户管理页面,在该页面测试用户增删改查的功能。