基于jsp完成的分页查询的增删查改

基于jsp完成的分页查询的增删查改

jsp页面

第一页代码:
userpage:
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据表格</title>
<link rel="shortcut icon" href="favicon.ico">
<link href="/pms/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
<link href="/pms/css/font-awesome.css?v=4.4.0" rel="stylesheet">
<link href="/pms/css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="/pms/css/animate.css" rel="stylesheet">
<link href="/pms/css/style.css?v=4.1.0" rel="stylesheet">
</head>
<body class="gray-bg">
	<div class="wrapper wrapper-content animated fadeInRight">
		<div class="row">
			<div class="col-sm-12">
				<div class="ibox float-e-margins">
					<div class="ibox-content">
						<div id="DataTables_Table_0_wrapper"
							class="dataTables_wrapper form-inline" role="grid">
							<div class="row">
								<div class="col-sm-6">
									<div class="dataTables_length" id="DataTables_Table_0_length">
										<label>每页 <select name="DataTables_Table_0_length"
											aria-controls="DataTables_Table_0"
											class="form-control input-sm"><option value="10">10</option>
												<option value="25">25</option>
												<option value="50">50</option>
												<option value="100">100</option></select> 条记录
										</label>
									</div>
								</div>
								<div class="col-sm-6">
									<div id="DataTables_Table_0_filter" class="dataTables_filter">
										<label>查找:<input type="search"
											class="form-control input-sm"
											aria-controls="DataTables_Table_0"></label>
									</div>
								</div>
							</div>

							<table
								class="table table-striped table-bordered table-hover dataTables-example dataTable"
								id="DataTables_Table_0"
								aria-describedby="DataTables_Table_0_info">
								<tr role="row">

									<th rowspan="1" colspan="1" style="width: 50px;">id</th>
									<th rowspan="1" colspan="1" style="width: 100px;">用户名</th>
									<th rowspan="1" colspan="1" style="width: 100px;">真实姓名</th>
									<th rowspan="1" colspan="1" style="width: 200px;">邮箱</th>
									<th rowspan="1" colspan="1" style="width: 150px;">QQ</th>
									<th rowspan="1" colspan="1" style="width: 150px;">电话</th>
									<th rowspan="1" colspan="1" style="width: 150px;">注册时间</th>
									<th rowspan="1" colspan="1" style="width: 150px;">操作</th>
								</tr>
								<c:forEach var="user" items="${page.pageData}">
									<tr>
										<td>${user.id }</td>
										<td>${user.username }</td>
										<td>${user.realname }</td>
										<td>${user.email }</td>
										<td>${user.qq }</td>
										<td>${user.phone }</td>
										<td><fmt:formatDate value="${user.regtime }"
												pattern="yyyy:MM:dd:HH:mm:ss" /></td>
										<td>
										
										<%--    <a href="/pms/user?action=findUserById&uid=${user.id}">  --%> 
										    <a href="/pms/user?action=findUserById&uid=${user.id}" >  
										<span class="glyphicon glyphicon-edit" aria-hidden="true"></span>修改</a>&nbsp;&nbsp;&nbsp;
										<a href="/pms/user?action=deleteUser&uid=${user.id}">
										<span class="glyphicon glyphicon-trash" aria-hidden="true"></span>删除</a>
										</td>
									</tr>
									
								</c:forEach>

							</table>

							<div class="row">
								<div class="col-sm-6">
									<div class="dataTables_info" id="DataTables_Table_0_info"
										role="alert" aria-live="polite" aria-relevant="all">显示
										${page.startIndex+1 } 到 ${page.startIndex + page.pageSize }
										项,共 ${page.totalCount}条数据</div>
								</div>
								<div class="col-sm-6">
									<div class="dataTables_paginate paging_simple_numbers"
										id="DataTables_Table_0_paginate">
										<ul class="pagination">
										<!-- 设置当前页是第一页,不可以点击 -->
										<c:if test="${page.currentPage ==1 }">
										
										<li class="paginate_button previous disabled" tabindex="0">
										<a href="#">上一页</a></li>
										</c:if>
										<!-- 当前页不是是第一页,可以点击 -->
										<c:if test="${page.currentPage != 1 }">
										<li class="paginate_button previous " tabindex="0"><a
												href="/pms/user?action=findPageUsers&currentPage=${page.currentPage-1 }&pageSize=10">上一页</a></li>
										</c:if>
										
										<!-- 循环页面 -->
										<c:forEach var="index" begin="${page.startNav }" end="${page.endNav }">
										
										<c:if test="${index == page.currentPage }">
										<!-- 显示当前的页数 active 高亮(活动) -->
										<li class="paginate_button active"><a href="#">${index}</a></li>
										</c:if>
										
										<c:if test="${index!=page.currentPage }">
										<!-- 显示当前的页数 active 高亮(活动) -->
										<li class="paginate_button ">
										<a href="/pms/user?action=findPageUsers&currentPage=${index}&pageSize=10">${index}</a></li>
										</c:if>
										
										</c:forEach>
											
											<!-- 设置当前页是最后一页,不可以点击下一页 -->
										<c:if test="${page.currentPage == page.totalPage}">
										
										<li class="paginate_button previous disabled" tabindex="0"><a href="#">上一页</a></li>
										</c:if>
										<!-- 当前页不是是最后一页,可以点击下一页 -->
										<c:if test="${page.currentPage !=page.totalPage }">
										<li class="paginate_button previous " tabindex="0"> 
										<a href="/pms/user?action=findPageUsers&currentPage=${page.currentPage+1 }&pageSize=10">下一页</a></li>
										</c:if>
										</ul>
									</div>
								</div>
							</div>
						</div>

					</div>
				</div>
			</div>
		</div>
	</div>
	<!-- 全局js -->
	<script src="/pms/js/jquery.min.js?v=2.1.4"></script>
	<script src="/pms/js/bootstrap.min.js?v=3.3.6"></script>

	<script src="/pms/js/plugins/jeditable/jquery.jeditable.js"></script>

	<!-- Data Tables -->
	<script src="/pms/js/plugins/dataTables/jquery.dataTables.js"></script>
	<script src="/pms/js/plugins/dataTables/dataTables.bootstrap.js"></script>

	<!-- 自定义js -->
	<script src="/pms/js/content.js?v=1.0.0"></script>

</body>

</html>

userServlet代码块



package cn.szsxt.controller;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;
import java.util.Map;
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 org.apache.commons.beanutils.BeanUtils;
import com.alibaba.fastjson.JSON;
import cn.szsxt.bean.PageBean;
import cn.szsxt.bean.ResultMsg;
import cn.szsxt.bean.User;
import cn.szsxt.service.UserService;

/**
 * @ClassName:
 * @author: YDJ
 * @Date: 2019年8月26日 下午5:00:01
 * @description:
 */
@WebServlet("/user") // 使用注解servlet配置 就不用到xml 中配置
public class UserServlet extends HttpServlet {

	// 创建userService 服务层代码

	private UserService userService = new UserService();

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		// 设置编码

		req.setCharacterEncoding("utf-8");

		resp.setContentType("text/html;charset=utf-8");

		// 获取action判断
		String action = req.getParameter("action");

		System.out.println("action---->" + action);

		if (action.equals("checkName")) {// 检查用户名

			checkName(req, resp);
		}
		if (action.equals("adduser")) {// 检查用户名

			try {
				adduser(req, resp);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if (action.equals("findUsers")) {// 用户查找
			findUsers(req, resp);
		}

		if (action.equals("findPageUsers")) {// 分页查询
			findPageUsers(req, resp);
		}
		
		if (action.equals("findUserById")) {// 通过id查询用户
			findUserById(req, resp);
		}
		
		if (action.equals("updateuser")) {// 修改用户
			updateUser(req, resp);
		}
		
		if (action.equals("deleteUser")) {
			deleteUser(req,resp);
		}

	}
	
	/**
	 * 	删除用户 通过id
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		String uid = req.getParameter("uid");
		System.out.println("uid--------->"+uid);
		
		boolean	flag= userService.deleteUserById(Integer.valueOf(uid));
		if (flag) {
			//刷新
			resp.sendRedirect("/pms/user?action=findPageUsers&currentPage=1&pageSize=10");
		}
		
	}

	/**
	 * 修改用户
	 * @param req
	 * @param resp
	 * @throws IOException 
	 */
	private void updateUser(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		//创建map集合
		Map<String, String[]> map = req.getParameterMap();
		
		//创建对象
		User u = new User();
		
		try {
			BeanUtils.populate(u, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		//打印
		
		System.out.println("u------>"+u);
		
		//更新
		
		boolean updateFlag = userService.updateUser(u);
		
		if (updateFlag) {//修改成功
			
			//刷新
			resp.sendRedirect("/pms/user?action=findPageUsers&currentPage=1&pageSize=10");
		}else {
			//修改失败
			ResultMsg msg = new ResultMsg(2,"更新失败");
			String json = JSON.toJSONString(msg);
			resp.getWriter().write(json);
		}
		
	}
	
	

	/**
	 * 通过id查询 user
	 * @param req
	 * @param resp
	 * @throws IOException 
	 * @throws ServletException 
	 */
	private void findUserById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String uid = req.getParameter("uid");
		
		System.out.println(uid);
		User u = userService.findUserById(Integer.valueOf(uid));
		
		System.out.println(u);
		if (u != null) { // 把 u 发送到修改界面
			
			req.setAttribute("user", u);
			req.getRequestDispatcher("/page/user/useredit.jsp").forward(req, resp);
	
		}
	}
	 

	/**
	 * 分页查询
	 * 
	 * @param req
	 * @param resp
	 */

	private void findPageUsers(HttpServletRequest req,
			HttpServletResponse resp) {
		
		String currentPageStr = req.getParameter("currentPage");
		String pageSizeStr = req.getParameter("pageSize");
		
		System.out.println("currentPageStr"+currentPageStr);
		System.out.println("pageSizeStr"+pageSizeStr);
		
		int currentPage = 0;
		try {
			currentPage =Integer.parseInt(currentPageStr);//为了防止非法输入异常捕获
		} catch (NumberFormatException e) {
			
			currentPage = 1;
		}
		int pageSize = 0;
		try {
			pageSize = Integer.parseInt(pageSizeStr);//为了防止非法输入异常捕获
		} catch (NumberFormatException e) {
			
			pageSize = 10;
		}
		
		int totalCount = userService.findUserCount();
		//创建PageBean 对象
		PageBean page = new PageBean(currentPage, pageSize, totalCount, 10);
		
		//创建对象
		
		//获取data对象
		List<User> pageData = userService.findPageUsers(page.getStartIndex(),page.getPageSize());
		//page对象设置数据
		page.setPageData(pageData);
		
		System.out.println(page);
		//page对象  传到 分页的页面
		req.setAttribute("page", page);
		
		try {
			req.getRequestDispatcher("/page/user/userpage.jsp").forward(req, resp);
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		};
		
	}

	/**
	 * 查询所有的用户
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	private void findUsers(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		List<User> list = userService.findUsers();

		// 判断

		if (list != null) {
			req.setAttribute("list", list);
			// 路径
			req.getRequestDispatcher("/page/user/userlist.jsp").forward(req,
					resp);

		}

	}
	/**
	 * 获取传递过来的参数
	 * 
	 * @param req
	 * @param resp
	 * @throws InvocationTargetException
	 * @throws IllegalAccessException
	 * @throws IOException
	 */
	private void adduser(HttpServletRequest req, HttpServletResponse resp)
			throws IllegalAccessException, InvocationTargetException,
			IOException {

		// 获取所有的请求参数
		Map<String, String[]> map = req.getParameterMap();
		User u = new User();
		BeanUtils.populate(u, map);

		// 把user的img补全 regtime 注册时间
		u.setImg("a.jpg");
		u.setRegtime(new Date());
		boolean flag = userService.addUser(u);

		if (flag) {
			ResultMsg msg = new ResultMsg(1, "添加成功");

			String json = JSON.toJSONString(msg);
			resp.getWriter().write(json);
		} else {
			ResultMsg msg = new ResultMsg(2, "添加失败");

			String json = JSON.toJSONString(msg);
			resp.getWriter().write(json);
		}

	}

	/**
	 * 检查用户名是否存在
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	private void checkName(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String username = req.getParameter("username");

		// 打印前端传递过来的数据

		System.out.println("name--->" + username);

		// 检查用户名是否存在
		boolean flag = userService.checkName(username);

		if (flag) {// 用户名存在

			ResultMsg msg = new ResultMsg(1, "用户名已存在");

			String json = JSON.toJSONString(msg);
			resp.getWriter().write(json);
		} else {
			ResultMsg msg = new ResultMsg(2, "用户名符合");

			String json = JSON.toJSONString(msg);
			resp.getWriter().write(json);
		}

	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		this.doGet(req, resp);

	}

}

userService代码块



package cn.szsxt.service;
import java.util.List;
import cn.szsxt.bean.User;
import cn.szsxt.dao.UserDao;
import cn.szsxt.daoimpl.UserDaoImpl;

/**
 * @ClassName:
 * @author: YDJ
 * @Date: 2019年8月24日 下午7:51:58
 * @description: userService层的实现
 */

public class UserService {

	private UserDao userDao = new UserDaoImpl();

	/**
	 * 登录操作
	 * 
	 * @param name
	 * @param pwd
	 * @return
	 */
	public User login(String name, String pwd) {

		return userDao.login(name, pwd);

	}
	/**
	 * 检查用户名是否存在
	 * 
	 * @param username
	 * @return
	 */
	public boolean checkName(String username) {
		// TODO Auto-generated method stub
		return userDao.checkName(username);
	}

	/**
	 * 添加用户
	 * 
	 * @param u
	 * @return
	 */
	public boolean addUser(User u) {
		// TODO Auto-generated method stub
		return userDao.addUser(u);
	}
	/**
	 * 查询用户
	 * 
	 * @return
	 */
	public List<User> findUsers() {
		return userDao.findUsers();
	}
	
	/**
	 * 	查询用户的总数量
	 * @return
	 */
	public int findUserCount() {
		
		return userDao.findUserCount();
	}
	/**
	 * 分页查询的服务层
	 * @param startIndex
	 * @param pageSize
	 */
	public List<User> findPageUsers(int startIndex, int pageSize) {
		
		return userDao.findPageUsers(startIndex, pageSize);
	}
	
	/**
	 * 	通过id来查询user
	 * @param id
	 * @return
	 */
	public User findUserById(Integer id) {
		
		return userDao.findUserById(id);
	}
	
	/**
	 * 修改用户
	 * @param u
	 * @return
	 */
	
	public boolean updateUser(User u) {
		
		return userDao.updateUser(u);
	}
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	public boolean deleteUserById(Integer id) {
		
		
		return userDao.deleteUserById(id);
	}

}

userDao代码块

package cn.szsxt.dao;
import java.util.List;
import cn.szsxt.bean.User;

/** 
 * @ClassName: 
 * @author: YDJ
 * @Date: 2019年8月24日 下午7:05:09
 * @description: UserDao层的实现
 */
public interface UserDao {
	/**
	 * 	登录操作
	 * @param name
	 * @param pwd
	 * @return
	 */
	public User login(String name,String pwd);
	/**
	 * 判断用户名是否存在
	 * @param username
	 * @return
	 */
	public boolean checkName(String username);
	/**
	 * 添加用户
	 * @param u
	 * @return
	 */
	public boolean addUser(User u);
	
	/**
	 * 查询所有的用户
	 */
	
	public List<User> findUsers();
	
	/**
	 * 	分页查询
	 */
	public List<User> findPageUsers(int startIndex,int pageSize);
	
	/**
	 * 	查询 用户的总数量   
	 * @return
	 */
	public int findUserCount();
	
	/**
	 * 	通过id查询user
	 * @param id
	 * @return
	 */
	public User findUserById(Integer id);
	/**
	 * 修改用户
	 * @param u
	 * @return
	 */

	public boolean updateUser(User u);

	/**
	 * 	删除
	 * @param id
	 * @return
	 */
	public boolean deleteUserById(Integer id);
}


userDaoImpl代码块


package cn.szsxt.daoimpl;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import cn.szsxt.bean.User;
import cn.szsxt.dao.UserDao;
import cn.szsxt.utils.JdbcUtils;
/**
 * @ClassName:
 * @author: YDJ
 * @Date: 2019年8月24日 下午7:21:16
 * @description:
 */
public class UserDaoImpl implements UserDao {
	/**
	 * 登录
	 */
	@Override
	public User login(String name, String pwd) {

		// 1获取conn
		Connection conn = JdbcUtils.getConn();

		// 2准备sql
		String sql = "select * from t_sysuser where username=? and password=?";

		// 3拿到ps
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);

			// 4设置参数
			ps.setString(1, name);
			ps.setString(2, pwd);

			// 5执行sql
			rs = ps.executeQuery();
			User u = null;
			// 6拿到结果
			if (rs.next()) {
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				String realname = rs.getString("realname");
				String email = rs.getString("email");
				String qq = rs.getString("qq");
				String phone = rs.getString("phone");
				String img = rs.getString("img");
				Date date = rs.getDate("regtime");

				java.util.Date regtime = new java.util.Date(date.getTime());
				u = new User(id, username, password, realname, email, qq, phone,
						img, regtime);
			}
			return u;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 7释放资源
			JdbcUtils.CloseAll(rs, ps, conn);
		}
		return null;
	}

	/**
	 * 判断用户名是否存在
	 */
	@Override
	public boolean checkName(String username) {
		// 1获取conn
		Connection conn = JdbcUtils.getConn();

		// 2准备sql
		String sql = "select * from t_sysuser where username=?";

		// 3拿到ps
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);

			// 4设置参数
			ps.setString(1, username);

			// 5执行sql
			rs = ps.executeQuery();
			// 6拿到结果
			if (rs.next()) {

				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 7释放资源
			JdbcUtils.CloseAll(rs, ps, conn);
		}
		return false;
	}
	/**
	 * 添加用户
	 */
	@Override
	public boolean addUser(User u) {
		// 1获取conn
		Connection conn = JdbcUtils.getConn();

		// 2准备sql
		String sql = "insert into t_sysuser(username,password,realname,email,qq,phone,img,regtime) value(?,?,?,?,?,?,?,?)";

		// 3拿到ps
		PreparedStatement ps = null;
		int update = 0;
		try {
			ps = conn.prepareStatement(sql);

			// 4设置参数
			ps.setString(1, u.getUsername());
			ps.setString(2, u.getPassword());
			ps.setString(3, u.getRealname());
			ps.setString(4, u.getEmail());
			ps.setString(5, u.getQq());
			ps.setString(6, u.getPhone());
			ps.setString(7, u.getImg());

			// setData (sql 类型的data)
			// u 是utils.Data
			java.util.Date date = u.getRegtime();

			// Date regTime = new Date(date.getTime());
			Timestamp time = new Timestamp(date.getTime());

			ps.setTimestamp(8, time);
			// 5执行sql
			update = ps.executeUpdate();
			// 6拿到结果
			if (update > 0) {

				return true;
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 7释放资源
			JdbcUtils.CloseAll(ps, conn);
		}
		return false;
	}
	/**
	 * 查询
	 */
	@Override
	public List<User> findUsers() {

		List<User> list = new ArrayList<User>();
		// 1获取conn
		Connection conn = JdbcUtils.getConn();

		// 2准备sql
		String sql = "select * from t_sysuser";

		// 3拿到ps
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			// 设置参数
			// 执行sql
			rs = ps.executeQuery();
			// 拿到结果
			while (rs.next()) {
				User u = null;
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				String realname = rs.getString("realname");
				String email = rs.getString("email");
				String phone = rs.getString("phone");
				String qq = rs.getString("qq");
				String img = rs.getString("img");
				Date date = rs.getDate("regtime");

				java.util.Date regtime = new java.util.Date(date.getTime());
				u = new User(id, username, password, realname, email, qq, phone,
						img, regtime);
				list.add(u);
			}

			return list;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 释放资源
			JdbcUtils.CloseAll(rs, ps, conn);
		}

		return null;
	}

	/**
	 * 分页查询
	 */
	@Override
	public List<User> findPageUsers(int startIndex, int pageSize) {
		List<User> list = new ArrayList<User>();
		// 1获取conn
		Connection conn = JdbcUtils.getConn();

		// 2准备sql
		String sql = "select * from t_sysuser limit ?,?";

		// 3拿到ps
		PreparedStatement ps = null;
		ResultSet rs = null;

		try {
			ps = conn.prepareStatement(sql);
			// 设置参数
			ps.setInt(1, startIndex);// 第一的参数开始的位置
			ps.setInt(2, pageSize);// 查询多少天
			// 执行sql
			rs = ps.executeQuery();
			// 拿到结果
			while (rs.next()) {
				User u = null;
				int id = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				String realname = rs.getString("realname");
				String email = rs.getString("email");
				String phone = rs.getString("phone");
				String qq = rs.getString("qq");
				String img = rs.getString("img");
				Date date = rs.getDate("regtime");

				java.util.Date regtime = new java.util.Date(date.getTime());
				u = new User(id, username, password, realname, email, qq, phone,
						img, regtime);
				list.add(u);
			}

			return list;

		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			// 释放资源
			JdbcUtils.CloseAll(rs, ps, conn);
		}

		return null;
	}
	/**
	 * 	查询用户的数量
	 */
	@Override
	public int findUserCount() {
		// 1获取conn
				Connection conn = JdbcUtils.getConn();

				// 2准备sql
				String sql = "select count(1) from t_sysuser";

				// 3拿到ps
				PreparedStatement ps = null;
				ResultSet rs = null;
				//统计数据
				int count = 0;
				try {
					ps = conn.prepareStatement(sql);
					// 设置参数
					
					// 执行sql
					rs = ps.executeQuery();
					// 拿到结果
					while (rs.next()) {
						
						count = rs.getInt(1);
					}	
					}catch (Exception e) {
						e.printStackTrace();
					}finally {
						JdbcUtils.close(rs,ps,conn);
					}
					return count;
	}
	/**
	 * 通过id查询用户
	 */
	/*@Override
	public User findUserById(Integer id) {
		User u = new User();
		// 1获取conn
				Connection conn = JdbcUtils.getConn();
				// 2准备sql
				//String sql = "select * from t_sysuser where id=?";
				String sql = "UPDATE t_sysuser SET username=?,realname=?,email=?,qq=?,phone=?, img=?,pwd=?,img=?,regtime=? WHERE id=?";
				
				// 3拿到ps
				PreparedStatement ps = null;
				int update = 0;
				try {
					ps = conn.prepareStatement(sql);

					// 4设置参数
					ps.setString(1, u.getUsername());
					ps.setString(2, u.getPassword());
					ps.setString(3, u.getRealname());
					ps.setString(4, u.getEmail());
					ps.setString(5, u.getQq());
					ps.setString(6, u.getPhone());
					ps.setString(7, u.getImg());

					java.util.Date date = u.getRegtime();
					Timestamp time = new Timestamp(date.getTime());

					ps.setTimestamp(8, time);
					ps.setInt(9, u.getId());
					// 5执行sql
					update = ps.executeUpdate();
					// 6拿到结果
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally {
					// 7释放资源
					JdbcUtils.CloseAll(ps, conn);
				}
				return null;
	}*/
	
	@Override
	public User findUserById(Integer id) {

		// 获取conn
		Connection conn = JdbcUtils.getConn();
		// 准备sql
		String sql = "select * from t_sysuser where id = ?";
//		String sql = "UPDATE t_sysuser SET username=?,realname=?,email=?,qq=?,phone=?, img=?,pwd=?,img=?,regtime=? WHERE id=?";
		// 拿到ps
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			ps = conn.prepareStatement(sql);
			// 设置参数
			ps.setInt(1, id);
			// 执行sql
			rs = ps.executeQuery();
			// 拿到结果
			User u = null;
			if (rs.next()) {
				int uid = rs.getInt("id");
				String username = rs.getString("username");
				String password = rs.getString("password");
				String realname = rs.getString("realname");
				String email = rs.getString("email");
				String phone = rs.getString("phone");
				String qq = rs.getString("qq");
				String img = rs.getString("img");
				Date date = rs.getDate("regtime");

				java.util.Date regtime = new java.util.Date(date.getTime());
				u = new User(uid, username, password, realname, email, qq, phone, img, regtime);
			}
			return u;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			JdbcUtils.CloseAll(rs, ps, conn);
		}
		// 释放资源

		return null;
	}

	@Override
	public boolean updateUser(User u) {
		
		// 1获取conn
		Connection conn = JdbcUtils.getConn();
		// 2准备sql
		//String sql = "select * from t_sysuser where id=?";
		String sql = "UPDATE t_sysuser SET username=?,realname=?,email=?,qq=?,phone=? "
				+ " WHERE id=?";
		PreparedStatement ps = null;
		int update = 0;
		try {
			ps = conn.prepareStatement(sql);
			
			// 设置参数
			ps.setString(1, u.getUsername());
			ps.setString(2, u.getRealname());
			ps.setString(3, u.getEmail());
			ps.setString(4, u.getQq());
			ps.setString(5, u.getPhone());
			ps.setInt(6, u.getId());
			//执行sql
			update = ps.executeUpdate();
			
			// 拿到结果
				if (update > 0) {

				return true;
				}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			JdbcUtils.CloseAll(ps,conn);
		}
		
		return false;
	}

	@Override
	public boolean deleteUserById(Integer id) {
		
		// 获取conn
		Connection conn = JdbcUtils.getConn();
		// 准备sql
		String sql = "delete from t_sysuser where id=?";
		
		//拿到ps
		PreparedStatement ps =null;
		 int update =0;
		try {
			 ps = conn.prepareStatement(sql);
			//设置参数
			 
			 ps.setInt(1, id);
			 
			 //执行sql
			 update = ps.executeUpdate();
			 //拿到结果
			 if (update>0) {
				return true;
			}
			 
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally {
			//关闭资源
			JdbcUtils.close(ps,conn);
		}
		
		return false;
	}
}

userEdit.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>

<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<link rel="shortcut icon" href="favicon.ico">
<link href="/pms/css/bootstrap.min.css?v=3.3.6" rel="stylesheet">
<link href="/pms/css/font-awesome.css?v=4.4.0" rel="stylesheet">
<link href="/pms/css/plugins/iCheck/custom.css" rel="stylesheet">
<link href="/pms/css/animate.css" rel="stylesheet">
<link href="/pms/css/style.css?v=4.1.0" rel="stylesheet">
</head>

<body class="gray-bg">
	<div class="wrapper wrapper-content animated fadeInRight">

		<div class="row">
			<div class="col-sm-12">
				<div class="ibox float-e-margins">

					<div class="ibox-content">
						<form method="get" class="form-horizontal">
							<div class="form-group">
							<input type="hidden" id="uid" 
										value="${user.id}" class="form-control">
								<label class="col-sm-2 control-label">用户名:</label>

								<div class="col-sm-10">
									<input type="text" id="usernameId" name="username" value="${user.username }"
										class="form-control"> <span id="nameSpan"></span>
								</div>

							</div>

						
							<div class="hr-line-dashed"></div>
							<div class="form-group">
								<label class="col-sm-2 control-label">真实姓名:</label>

								<div class="col-sm-10">
									<input type="text" class="form-control" id="realnameId" value="${user.realname }">
									<span id="realSpan"></span>
								</div>
							</div>

							<div class="hr-line-dashed"></div>
							<div class="form-group">
								<label class="col-sm-2 control-label">手机号码:</label>

								<div class="col-sm-10">
									<input type="text" class="form-control" id="phoneId" value="${user.phone }"> <span
										id="phoneSpan"></span>
								</div>
							</div>

							<div class="hr-line-dashed"></div>
							<div class="form-group">
								<label class="col-sm-2 control-label">邮箱:</label>

								<div class="col-sm-10">
									<input type="email" class="form-control" id="emailId" value="${user.email }"> <span 
										id="emailSpan"></span>
								</div>
							</div>

							<div class="hr-line-dashed"></div>
							<div class="form-group">
								<label class="col-sm-2 control-label">QQ:</label>

								<div class="col-sm-10">
									<input type="text" id="qqId" name="qq" class="form-control" value="${user.qq }">
									 <span id="qqSpan"></span>
								</div>
							</div>

							<div class="hr-line-dashed"></div>
							<div class="form-group">
								<div class="col-sm-4 col-sm-offset-2">

								</div>
							</div>
						</form>
						<div>
						<button class="btn btn-primary" onclick="updateuser()" >修改用户</button>
									<button class="btn btn-white" type="submit">取消</button>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>



	<!-- 全局js -->
	<script src="/pms/js/jquery.min.js?v=2.1.4"></script>
	<script src="/pms/js/bootstrap.min.js?v=3.3.6"></script>

	<!-- 自定义js -->
	<script src="/pms/js/content.js?v=1.0.0"></script>

	<!-- iCheck -->
	<script src="/pms/js/plugins/iCheck/icheck.min.js"></script>
	<script>
		$(document).ready(function() {
			$('.i-checks').iCheck({
				checkboxClass : 'icheckbox_square-green',
				radioClass : 'iradio_square-green',
			});
		});
		
		
		//给用户名输入框 添加 失去焦点事件
		
		$(function() {
			$("#usernameId").blur(function () {
				checkName();
			});
		});
			
		//修改用户
		function updateuser() {
			//判断表单的验证
			var nameFlag = checkName();
			
			if (nameFlag) {
				
				var uid = $("#uid").val();
				var name = $("#usernameId").val();
				var realname = $("#realnameId").val();
				var phone = $("#phoneId").val();
				var email = $("#emailId").val();
				var qq = $("#qqId").val();
				
				//ajax 	请求
				
				$.ajax({
				
					type:"post",
					url:"/pms/user",//ajax请求的url
					async:true,//ajax    是否异步请求
					data:{action:"updateuser",
						username:name,
						id : uid,
						realname:realname,
						phone:phone,
						email:email,
						qq:qq
						
					
					},//参数
					dataType:"json",//服务返回的数据类型
					success:function(data){//请求成功的数据
						if (data.status==1) {
							alert(data.msg);
						}else {
							alert(data.msg); //添加失败 
						}
					}
					
				});
				
			}
			
		}
		
		//输入框的校验
		function checkInput(objId,msgId,reg,msg) {
			//拿到输入框的内容
			var content = $(objId).val();
			if (content!=null && content.length>0) {
				
				if (reg.test(content)) {
					return true;//输入符合规则
				}else {
					$(msgId).text(msg).css("color","red");//输入不符合规则,字体为红色;
					return false;
				}
			}
		}
		
		//判断用户名是否存在
		function checkName() {
			
			var nameFlag = true;
			//拿到输入文本
			var name = $("#usernameId").val();
			
			if (name!=null && name.length > 0) {
				//ajax 发送数据到  服务
				$.ajax({
					
					type:"post",//请求数据类型
					
					url:"/pms/user",//ajax请求的url
					
					async:false,//ajax    同步请求
					
					data:{action:"checkName",username:name},//参数
					
					dataType:"json",//服务返回的数据类型
					
					success:function(data){//请求成功的数据
						if (data.status==1) {
							$("#nameSpan").text(data.msg).css("color","red");
							nameFlag = false; //用户名存在 标记为false 不可以提交
						}else {
							$("#nameSpan").text(data.msg).css("color","green"); //用户名不存在  可以 提交  
							nameFlag = true;
						}
					}
					
				});
				
			} else {
				$("#nameSpan").text("用户名不能为空!").css("color","red");
			}
			return nameFlag;
		}
	</script>

	<script type="text/javascript"
		src="http://tajs.qq.com/stats?sId=9051096" charset="UTF-8"></script>
	<!--统计代码,可删除-->

</body>

</html>

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页