项目源码,欢迎下载查看:https://github.com/qingzibbb/Java/tree/master/userManager%20%E5%89%AF%E6%9C%AC
建立一张用户信息表,插入初始数据
drop database if exists usermanger;
create DATABASE if not exists usermanger character set utf8;
use usermanger;
drop table if exists usermessage;
create table `usermessage` (
`id` INT PRIMARY KEY auto_increment,
`name` varchar (60),
`username` varchar (60) default 'bit',
`password` varchar (60) default '123456',
`gender` varchar (4),
`age` int,
`address` varchar (90),
`qq` varchar (20),
`email` varchar (30)
);
INSERT INTO usermessage VALUES(1,'小晴','xiaoqing','520','女',21,'陕西','18022223333','[email protected]');
INSERT INTO usermessage VALUES(2,'小权','xiaoquan','520','男',21,'西安','13822223333','[email protected]');
INSERT INTO usermessage VALUES(3,'小楠','xiaonan','1235','女',21,'上海','1262913817','[email protected]');
INSERT INTO usermessage VALUES(4,'小韩','xiaohan','1237','女',21,'陕西','1262913819','[email protected]');
INSERT INTO usermessage VALUES(5,'小月','xiaoyue','1238','男',22,'上海','1262913814','[email protected]');
INSERT INTO usermessage VALUES(6,'权栋','quandong','1239','男',23,'陕西','1262913813','[email protected]');
创建User类,包含id、name、username、password、gender、age、address、qq、email属性,并实现其get()、set()方法
创建分页对象PageBean,包含totalCount、totalPage、list、currentPage、rows属性,并实现其get()、set()、toString()方法
public class PageBean<T> {
private int totalCount; //总记录数
private int totalPage; //总页码
private List<T> list; //每页中的数据
private int currentPage; //当前页码
private int rows; //每页的记录数
//实现get set toString方法
}
创建一个Person类来演示:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Main {
public static void main(String[] args) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person(1, "tom", "123");
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("JsonString: " + jsonString);
}
}
输出JsonString: {“id”:1,“name”:“tom”,“password”:“123”}
请求: POST /loginServlet
响应: {msg: true}
请求: POST /addServlet
响应: {msg: true}
请求: GET /deleteServlet?id=1
请求: POST /deleteSelectedServlet
响应: {msg: true}
请求: POST /findByPageServlet
data:{currentPage,rows,name,address,email}
响应: 响应体内容为,每一页的用户信息
请求: POST /findByPageServlet
data:{currentPage,rows,name,address,email}
响应: 响应体内容为,每一页的用户信息
1.更新用户信息之前,先请求得到要修改的用户的信息
请求: POST /returnServlet
响应: 当前需要更新的用户的信息
2.更新完成后,提交更新信息
请求: POST /updateServlet
响应: {msg: true}
获取数据库连接,通过username及password登录数据库
实现login、add、delete、find、update、findByPage(分页查询)、findAllRecord(查询共有多少条记录)方法
核心代码:实现模糊查找
public List<User> findByPage(int start, int rows,Map<String, String[]> map) {
String sql="select * from usermessage where 1=1";
StringBuilder s=new StringBuilder(sql);
Set<String> set = map.keySet();
List<Object> list =new ArrayList<>();
for(String key : set){
String value=map.get(key)[0];
if(value!=null && !"".equals(value)){
//有值
s.append(" and ").append(key).append(" like ? ");
list.add("%"+value+"%");
}
}
s.append(" limit ?,? ");
list.add(start);
list.add(rows);
//............省略
}
核心代码
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//。。。。省略,像前端请求拿到username和password
UserService userService=new UserService(); //创建service层的对象
Map<String ,Object> return_map = new HashMap<>(); //创建一个map集合,存放返回到客户端的数据
UserService userService = new UserService();
User user = userService.login(loginUser);
Map<String,Object> returnMap = new HashMap<>();
if(user!= null){
System.out.println("登陆成功"+username);
//把当前登录成功的用户写到session中
req.getSession().setAttribute("user",user);
returnMap.put("msg",true);
}else {
System.out.println("登陆失败"+username);
returnMap.put("msg",false);
}
//把登陆成功的map返回给前端 json :便于前端进行处理
ObjectMapper objectMapper = new ObjectMapper();
//将returnMap转换为json字符串
objectMapper.writeValue(resp.getWriter(),returnMap);
}
}
用户进行登录后,需要先进行查询,将查询结果显示到页面上。
进行查询
4.1 删除单个用户
获取前端参数id
4.2 删除选中用户
获取前端选中的id数组。
@WebServlet("/deleteSelectedServlet")
public class DeleteSelectedServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//。。。。。。。省略
String[] values = req.getParameterValues("id[]");
UserService userService = new UserService();
int sum = 0;
for (int i = 0; i < values.length; i++) {
//勾选了多个 只有全部删除成功才算成功
int j = Integer.parseInt(values[i]);
int delete = userService.delete(j);
//成功一次加1
sum+=delete;
}
Map<String,Object> returnMap = new HashMap<>();
if(sum == values.length){
returnMap.put("msg",true);
}else{
returnMap.put("msg",false);
}
//。。。。。。。省略 json转换
}
}
前端采用HTML+CSS+JS设计
前后端服务器数据交互,以登录为例:
<script>
//登录请求
$(function () {
$("#submit").click(function () {
var username=$("#user").val();
var password=$("#password").val();
$.ajax({
url:"/loginServlet",//发送请求的地址
data:{"username":username,"password":password},//发送给服务器的数据
type:"POST",//请求方式 ("POST" 或 "GET"), 默认为 "GET"
dataType:"json",//预期服务器返回的数据类型
success:function (data) {//请求成功后的回调函数
console.log(data);
if(data.msg===true){
window.location.href="list.html";
}else{
/*window.location.reload();*/
$("#message").text("账号或密码错误,请重试!");
$("#user").val("");
$("#password").val("");
$("#verifycode").val("");
}
}
});
});
});
</script>