当前位置:   article > 正文

jsp+servlet+jdbc实现对数据库简单的增删改查_jsp连接数据库增删改查

jsp连接数据库增删改查

      入职以来(来京六整月),一直在学习JavaWeb的知识,分享下最近几个月(断断续续)用jsp+servlet+jdbc实现的一个demo,这个demo借鉴了网上很多前辈的经验,希望自己能够不断进步。

效果图如下:

1、首先介绍下开发所需要工具 ,以及相应的开发环境:
      eclipse+tomcat+mysql+jdk;

2、创建数据库userdemo,然后创建userdemo及userinfo表

3、接下来在eclipse中搭建web工程,相应目录如下图所示,并导入相应的包(需要mysql连接jdbc的jar包,以及jstl的jar包


4、对应jsp页面的代码
(1)登陆界面logon.jsp:

  1. <%@ page import="java.sql.*" language="java" import="java.util.*" pageEncoding="utf-8" %>
  2. <%
  3. String path = request.getContextPath();
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  5. %>
  6. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  7. <html>
  8. <head>
  9. <meta http-equiv ="Content-Type" content="text/html; charset=ISO-8859-1">
  10. <title>用户登陆界面</title>
  11. <style type="text/css">
  12. body {
  13. background-attachment: fixed;
  14. background-repeat: no-repeat;
  15. background-size: 100% 100%;
  16. color: #000;
  17. font-family: "微软雅黑";
  18. font-size: 1.6em;
  19. }
  20. #div1 {
  21. text-align: center;
  22. width: 200px;
  23. height: 200px;
  24. }
  25. #span {
  26. font-size: 9px;
  27. }
  28. </style>
  29. <script>
  30. function myFunction(){
  31. var x = document.getElementById("psw").value;
  32. if(x==""||isNaN(x)){
  33. alert("密码不能为空!");
  34. return;
  35. }
  36. var y = document.getElementById("usn").value;
  37. if(y==""){
  38. alert("用户名不能为空!");
  39. return;
  40. }
  41. document.getElementById("form1").submit();
  42. }
  43. </script>
  44. </head>
  45. <body>
  46. <div id="div1">
  47. <form id="form1" action="logon" method="post">
  48. <p>
  49. <label for="username">用户名</label>
  50. <input id="usn" type="text" name="username">
  51. </p>
  52. <p>
  53. <label for="password">密码</label>
  54. <input id="psw" type="password" name="password">
  55. </p>
  56. <input type="button" onclick="myFunction()" value="登陆" >
  57. </form>
  58. </div>
  59. </body>
  60. </html>

(2)主界面home.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>人员信息</title>
  8. </head>
  9. <!-- frame对应的导航框架 -->
  10. <frameset rows="93%,*" >
  11. <frameset cols="20%, *" noresize="noresize" >
  12. <frame src="left.jsp" frameborder="1" name="leftFrame" />
  13. <frame src="userlistright" frameborder="1" name="rightFrame" />
  14. </frameset>
  15. <frame src="footer.jsp" frameborder="1" name="footerFrame"/>
  16. </frameset>
  17. </html>

(3)左侧部分left.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <!-- head部分 -->
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  8. <title>人员信息</title>
  9. <style type="text/css">
  10. a:link,a:visited {
  11. text-decoration: none; /*超链接无下划线*/
  12. }
  13. a:hover{
  14. text-decoration:underline; /*鼠标放上去有下划线*/
  15. }
  16. li{
  17. list-style: none; /*去除li前面的小黑点*/
  18. }
  19. </style>
  20. </head>
  21. <!--js:对应跳转部分 -->
  22. <script type="text/javascript">
  23. function add(){
  24. window.parent.rightFrame.location.href='addright.jsp'
  25. }
  26. function userList(){
  27. window.parent.rightFrame.location.href='userlistright'
  28. }
  29. </script>
  30. <body>
  31. <div>
  32. <h3 style="margin-center">人员信息</h3>
  33. <ul>
  34. <li>
  35. <a href="#" onclick="add()">新增</a>
  36. </li>
  37. <li>
  38. <a href="#" onclick="userList()">人员列表</a>
  39. </li>
  40. </ul>
  41. </div>
  42. </body>
  43. </html>

(4)右侧部分(人员列表)userlistright

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
  4. <%@ page import="dao.UserInfoDaoMrg" %>
  5. <%@ page import="entity.UserInfo" %>
  6. <%@ page import="java.util.*" %>
  7. <%@ page import="bean.Page" %>
  8. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  9. <html>
  10. <!-- head部分 -->
  11. <head>
  12. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  13. <title>人员列表</title>
  14. <style type="text/css">
  15. a:link,a:visited {
  16. text-decoration: none; /*超链接无下划线*/
  17. }
  18. a:hover{
  19. text-decoration:underline; /*鼠标放上去有下划线*/
  20. }
  21. td{
  22. text-align:center;
  23. }
  24. </style>
  25. </head>
  26. <!--js:对应跳转部分 -->
  27. <script>
  28. function refreshList(){
  29. window.parent.rightFrame.location.href='userlistright' //servlet
  30. }
  31. function add(){
  32. window.parent.rightFrame.location.href='addright.jsp' //
  33. }
  34. function delFun(){
  35. window.parent.rightFrame.location.href='userlistright' //
  36. }
  37. function editFun(){
  38. window.parent.rightFrame.location.href='addright.jsp' //
  39. }
  40. </script>
  41. <body>
  42. <div style="margin-top:10px; margin-bottom:10px;">
  43. <button id="refreshbutton" style="width:80px;height:40px;margin-left:10px" type="button" onclick="refreshList()">刷新界面</button>
  44. <button id="addbutton" style="width:80px;height:40px;" type="button" onclick="add()">新增</button>
  45. </div>
  46. <div>
  47. <table id="user_list" border="1" cellspacing="0" cellpadding="0" style="border:1px solid gray; border-radius:4px">
  48. <thead>
  49. <tr>
  50. <th style="width:100px;text-align:center">工号</th>
  51. <th style="width:80px;text-align:center">姓名</th>
  52. <th style="width:120px;text-align:center">技术水平</th>
  53. <th style="width:120px;text-align:center">所在部门</th>
  54. <th style="width:160px;text-align:center">角色</th>
  55. <th style="width:180px;text-align:center">操作</th>
  56. </tr>
  57. </thead>
  58. <tbody>
  59. <%
  60. List<UserInfo> list = (List<UserInfo>)request.getAttribute("list");
  61. for(UserInfo user : list){
  62. %>
  63. <tr>
  64. <td style="width:100px;text-align:center"><%=user.getJobNumber()%></td>
  65. <td style="width:80px;text-align:center"><%=user.getName()%></td>
  66. <td style="width:120px;text-align:center"><%=user.getLevel()%></td>
  67. <td style="width:120px;text-align:center"><%=user.getDepartment()%></td>
  68. <td style="width:160px;text-align:center"><%=user.getRole()%></td>
  69. <td><a href="deleteUserServlet?id=<%=user.getId()%>" onclick="return confirm('是否确认删除<%=user.getName()%>信息?')">删除</a>
  70. <a href="selectUserServlet?id=<%=user.getId()%>">修改</a></td>
  71. </tr>
  72. <%
  73. }
  74. %>
  75. </tbody>
  76. </table>
  77. </div>
  78. <div style="width:800px">
  79. <c:choose>
  80. <c:when test="${page.pageNum<=1}">
  81. <a href="userlistright?pageNum = 1 ">前一页</a>
  82. </c:when>
  83. <c:otherwise>
  84. <a href="userlistright?pageNum=${page.pageNum-1}">前一页</a>
  85. </c:otherwise>
  86. </c:choose>
  87. <c:forEach var="i" begin="1" end="${page.pageTotal}" step="1">
  88. <a href="userlistright?pageNum=${i}">${i}</a>
  89. </c:forEach>
  90. <c:choose>
  91. <c:when test="${page.pageNum >= page.pageTotal}%>">
  92. <a href="userlistright?pageNum=${page.pageTotal}">后一页</a>
  93. </c:when>
  94. <c:otherwise>
  95. <a href="userlistright?pageNum=${page.pageNum + 1}">后一页</a>
  96. </c:otherwise>
  97. </c:choose>
  98. <span style="margin-left:10px">一共${page.pageTotal}页</span>
  99. </div>
  100. </body>
  101. </html>

(5)footer.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <div class="footer">
  5. <div class="container_1">
  6. <p>
  7. Designed by <a href="http://www.baidu.com" target="_blank">百度</a>
  8. </p>
  9. </div>
  10. </div>

(6)增加人员界面addright.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  7. <title>新增</title>
  8. </head>
  9. <script>
  10. function confirmFun(){
  11. var x1 = document.getElementById("name").value;
  12. var x2 = document.getElementById("jobNumber").value;
  13. var x3 = document.getElementById("level").value;
  14. var x4 = document.getElementById("department").value;
  15. var x5 = document.getElementById("role").value;
  16. if(x1==""||isNaN(x1)||x2==""||isNaN(x2)||x3==""||isNaN(x3)||x4==""||isNaN(x4)
  17. ||x5==""||isNaN(x5)){
  18. alert("添加信息不完整");
  19. return;
  20. }
  21. document.getElementById("form").submit();
  22. }
  23. function resetFun(){
  24. var spans = document.getElementsByTagName("input");
  25. for(var j=0;j<spans.length;j++){
  26. var span = spans[j]; // input标签的数组
  27. document.getElementById(span.id).value ="";//
  28. console.info(span.id);
  29. }
  30. }
  31. </script>
  32. <body>
  33. <h3>新增页面</h3>
  34. <form id="form" action="addright" method="post">
  35. 工号:<input id="jobNumber" name="jobNumber"><br>
  36. 姓名:<input id="name" name="name"><br>
  37. 技术水平:<input id="level" name="level"><br>
  38. 所在部门:<input id="department" name="department"><br>
  39. 角色:<input id="role" name="role"><br>
  40. <input type="button" value="确定" onclick="confirmFun()"> <input type="reset" value="重置" onclick="resetFun()">
  41. </form>
  42. </body>
  43. </html>

(7)编辑人员信息界面updateuser.jsp

  1. <%@ page language="java" contentType="text/html; charset=UTF-8"
  2. pageEncoding="UTF-8"%>
  3. <%@ page import="entity.UserInfo" %>
  4. <%@ page import="dao.UserInfoDaoMrg" %>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  9. <title>修改</title>
  10. </head>
  11. <script>
  12. function confirmFun(){
  13. var x1 = document.getElementById("name").value;
  14. var x2 = document.getElementById("jobNumber").value;
  15. var x3 = document.getElementById("level").value;
  16. var x4 = document.getElementById("department").value;
  17. var x5 = document.getElementById("role").value;
  18. if(x1==""||isNaN(x1)||x2==""||isNaN(x2)||x3==""||isNaN(x3)||x4==""||isNaN(x4)
  19. ||x5==""||isNaN(x5)){
  20. alert("添加信息不完整");
  21. return;
  22. }
  23. document.getElementById("updform").submit();
  24. }
  25. function resetFun(){
  26. var spans = document.getElementsByTagName("input");
  27. for(var i=0;j<spans.length;i++){
  28. var span = spans[i]; // input标签的数组
  29. document.getElementById(span.id).value ="";//
  30. console.info(span.id);
  31. }
  32. }
  33. </script>
  34. <body>
  35. <h3>修改页面</h3>
  36. <%
  37. UserInfo user = (UserInfo)request.getAttribute("user");
  38. %>
  39. <form id="updform" action="updateuser" method="post">
  40. <input type="hidden" name="id" value="<%=user.getId()%>">
  41. 工号:<input name="jobNumber" value="<%=user.getJobNumber()%>"><br>
  42. 姓名:<input name="name" value="<%=user.getName()%>"> <br>
  43. 技术水平:<input name="level" value="<%=user.getLevel()%>"><br>
  44. 所在部门:<input name="department" value="<%=user.getDepartment()%>"><br>
  45. 角色:<input name="role" value="<%=user.getRole()%>"><br>
  46. <input type="submit" value="确定" onclick="confirmFun()"> <input type="reset" value="重置" onclick="resetFun()">
  47. </form>
  48. </body>
  49. </html>

5、配置web.xml文件的信息如下:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  3. <display-name>webexample</display-name>
  4. <welcome-file-list>
  5. <welcome-file>/logon.jsp</welcome-file>
  6. </welcome-file-list>
  7. <servlet>
  8. <servlet-name>s1</servlet-name>
  9. <servlet-class>servlet.ActionServlet</servlet-class>
  10. </servlet>
  11. <servlet-mapping>
  12. <servlet-name>s1</servlet-name>
  13. <url-pattern>/logon</url-pattern>
  14. </servlet-mapping>
  15. <servlet>
  16. <servlet-name>s2</servlet-name>
  17. <jsp-file>/home.jsp</jsp-file>
  18. </servlet>
  19. <servlet-mapping>
  20. <servlet-name>s2</servlet-name>
  21. <url-pattern>/home</url-pattern>
  22. </servlet-mapping>
  23. <servlet>
  24. <servlet-name>s3</servlet-name>
  25. <servlet-class>servlet.UserListServlet</servlet-class>
  26. </servlet>
  27. <servlet-mapping>
  28. <servlet-name>s3</servlet-name>
  29. <url-pattern>/userlistright</url-pattern>
  30. </servlet-mapping>
  31. <servlet>
  32. <servlet-name>s4</servlet-name>
  33. <servlet-class>servlet.AddUserServlet</servlet-class>
  34. </servlet>
  35. <servlet-mapping>
  36. <servlet-name>s4</servlet-name>
  37. <url-pattern>/addright</url-pattern>
  38. </servlet-mapping>
  39. <servlet>
  40. <servlet-name>s5</servlet-name>
  41. <servlet-class>servlet.UpdateUserServlet</servlet-class>
  42. </servlet>
  43. <servlet-mapping>
  44. <servlet-name>s5</servlet-name>
  45. <url-pattern>/updateuser</url-pattern>
  46. </servlet-mapping>
  47. <servlet>
  48. <servlet-name>s6</servlet-name>
  49. <servlet-class>servlet.DeleteUserServlet</servlet-class>
  50. </servlet>
  51. <servlet-mapping>
  52. <servlet-name>s6</servlet-name>
  53. <url-pattern>/deleteUserServlet</url-pattern>
  54. </servlet-mapping>
  55. <servlet>
  56. <servlet-name>s7</servlet-name>
  57. <servlet-class>servlet.SelectUserServlet</servlet-class>
  58. </servlet>
  59. <servlet-mapping>
  60. <servlet-name>s7</servlet-name>
  61. <url-pattern>/selectUserServlet</url-pattern>
  62. </servlet-mapping>
  63. </web-app>

6、对应的Java代码如下:
(1)util包下的DBUtil.java

  1. package util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.sql.Statement;
  7. import org.junit.Test;
  8. /**
  9. * JDBC工具类:
  10. * 提供了获得连接,关闭连接的相关的方法
  11. * @author Administrator
  12. *
  13. */
  14. public class DBUtil {
  15. static Connection conn = null;
  16. static Statement stmt = null;
  17. //建立连接
  18. public static Connection getConnection() throws Exception{
  19. try {
  20. Class.forName("com.mysql.jdbc.Driver");
  21. System.out.println("成功加载驱动程序");
  22. conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/userdemo", "root", "root");
  23. System.out.println("数据库连接成功");
  24. } catch (Exception e) {
  25. System.out.println("未连接成功");
  26. e.printStackTrace();
  27. }
  28. return conn;
  29. }
  30. }


(2)entity包下的User.java、UserInfo.java

(2.1) User.java类

  1. package entity;
  2. /**
  3. * 实体类
  4. * @author Administrator
  5. * 对应登陆界面
  6. */
  7. public class User {
  8. private int id;
  9. private String username;
  10. private String pwd;
  11. private String name;
  12. private String gender;
  13. public int getId() {
  14. return id;
  15. }
  16. public void setId(int id) {
  17. this.id = id;
  18. }
  19. public String getUsername() {
  20. return username;
  21. }
  22. public void setUsername(String username) {
  23. this.username = username;
  24. }
  25. public String getPwd() {
  26. return pwd;
  27. }
  28. public void setPwd(String pwd) {
  29. this.pwd = pwd;
  30. }
  31. public String getName() {
  32. return name;
  33. }
  34. public void setName(String name) {
  35. this.name = name;
  36. }
  37. public String getGender() {
  38. return gender;
  39. }
  40. public void setGender(String gender) {
  41. this.gender = gender;
  42. }
  43. @Override
  44. public String toString() {
  45. return "User [id=" + id + ", username=" + username + ", pwd=" + pwd
  46. + ", name=" + name + ", gender=" + gender + "]";
  47. }
  48. }

(2.2)UserInfo.java类 

  1. package entity;
  2. /**
  3. * @author
  4. * 人员信息的实体类
  5. * 对应人员信息界面
  6. */
  7. public class UserInfo {
  8. private Integer id;
  9. private String jobNumber;
  10. private String name;
  11. private String level;
  12. private String department;
  13. private String role;
  14. //初始化
  15. public UserInfo(Integer id ,String jobNumber,String name, String level, String department, String role) {
  16. this.id = id;
  17. this.jobNumber = jobNumber;
  18. this.name = name;
  19. this.level = level;
  20. this.department = department;
  21. this.role = role;
  22. }
  23. //初始化
  24. public UserInfo(String jobNumber,String name, String level, String department, String role) {
  25. this.jobNumber = jobNumber;
  26. this.name = name;
  27. this.level = level;
  28. this.department = department;
  29. this.role = role;
  30. }
  31. public int getId() {
  32. return id;
  33. }
  34. public void setId(int id) {
  35. this.id = id;
  36. }
  37. public String getJobNumber() {
  38. return jobNumber;
  39. }
  40. public void setJobNumber(String jobNumber) {
  41. this.jobNumber = jobNumber;
  42. }
  43. public String getName() {
  44. return name;
  45. }
  46. public void setName(String name) {
  47. this.name = name;
  48. }
  49. public String getLevel() {
  50. return level;
  51. }
  52. public void setLevel(String level) {
  53. this.level = level;
  54. }
  55. public String getDepartment() {
  56. return department;
  57. }
  58. public void setDepartment(String department) {
  59. this.department = department;
  60. }
  61. public String getRole() {
  62. return role;
  63. }
  64. public void setRole(String role) {
  65. this.role = role;
  66. }
  67. @Override
  68. public String toString() {
  69. return "UserInfo [id=" + id + ", jobNumber=" + jobNumber + ", name="
  70. + name + ", level=" + level + ", department=" + department
  71. + ", role=" + role + "]";
  72. }
  73. }

(3)dao包下的UserDao.java、UserInfoDaoMrg.java

(3.1) UserDao.java类

  1. package dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import util.DBUtil;
  6. import entity.User;
  7. /**
  8. * @author
  9. * 对应登陆界面
  10. */
  11. public class UserDao {
  12. public User findByUsername(String username){
  13. User user = null;
  14. Connection conn = null;
  15. //获取连接
  16. try {
  17. conn = DBUtil.getConnection();
  18. //预处理语句
  19. PreparedStatement prep = conn.prepareStatement("select * from userdemo where username=?");//username
  20. prep.setString(1, username);//查询sql语句中第一个“?”的位置
  21. //遍历数据库
  22. ResultSet rst = prep.executeQuery();//rst.next()指针游标,输出之后其值会发生变化
  23. if(rst.next()){
  24. System.out.println(rst.getInt("id"));
  25. user = new User();
  26. user.setId(rst.getInt("id"));//id
  27. user.setUsername(username);//username
  28. user.setPwd(rst.getString("pwd"));//pwd
  29. user.setName(rst.getString("name"));//name
  30. user.setGender(rst.getString("gender"));//gender
  31. }
  32. } catch (Exception e) {
  33. e.printStackTrace();//抛出异常
  34. System.out.println("查询失败");
  35. // DBUtil.close(conn);
  36. }
  37. return user;
  38. }
  39. }

(3.2)UserInfoDaoMrg.java 类

  1. package dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.util.*;
  6. import bean.Page;
  7. import util.DBUtil;
  8. import entity.User;
  9. import entity.UserInfo;
  10. /**
  11. * @author
  12. * 负责访问数据库
  13. */
  14. public class UserInfoDaoMrg {
  15. List<UserInfo> userList = new ArrayList<>();
  16. UserInfo user = null;
  17. //查找所有员工
  18. public List<UserInfo> getUserInfo(){
  19. try {
  20. //获取连接
  21. Connection conn = DBUtil.getConnection();
  22. //预处理语句
  23. PreparedStatement prep = conn.prepareStatement("select * from userinfo");
  24. //遍历数据库
  25. ResultSet rst = prep.executeQuery();
  26. while(rst.next()){
  27. int id = rst.getInt("id");
  28. System.out.println("-----" + id);
  29. String jobNumber = rst.getString("jobNumber");
  30. String name = rst.getString("name");
  31. String technicalLevel = rst.getString("level");
  32. String department = rst.getString("department");
  33. String role = rst.getString("role");
  34. user = new UserInfo(id, jobNumber, name, technicalLevel, department, role);
  35. userList.add(user);
  36. }
  37. prep.close();
  38. conn.close();
  39. } catch (Exception e) {
  40. e.printStackTrace();//抛出异常
  41. System.out.println("查询失败");
  42. }
  43. return userList;
  44. }
  45. //添加
  46. public void addUserInfo(String jobNumber, String name, String technicalLevel, String department, String role) {
  47. try {
  48. //获取连接
  49. Connection conn = DBUtil.getConnection();
  50. //预处理语句
  51. String sql = "insert into userinfo (jobNumber,name,level,department,role) values (?, ?, ?, ?, ?)";
  52. PreparedStatement prep = conn.prepareStatement(sql);
  53. prep.setString(1, jobNumber);
  54. prep.setString(2, name);
  55. prep.setString(3, technicalLevel);
  56. prep.setString(4, department);
  57. prep.setString(5, role);
  58. prep.executeUpdate();
  59. prep.close();
  60. conn.close();
  61. } catch (Exception e) {
  62. e.printStackTrace();//抛出异常 (检查出现的问题)
  63. System.out.println("增加失败");
  64. }
  65. }
  66. //加载员工信息,用于更新界面
  67. public UserInfo selectUserInfo(int id){
  68. UserInfo user = null;
  69. Connection con = null;
  70. PreparedStatement prep = null;
  71. ResultSet rst = null;
  72. try {
  73. con=DBUtil.getConnection();
  74. String sql = "select * from userinfo where id =?";
  75. prep = con.prepareStatement(sql);
  76. prep.setInt(1, id);
  77. rst = prep.executeQuery();
  78. while(rst.next()){
  79. String jobNumber = rst.getString("jobNumber");
  80. String name = rst.getString("name");
  81. String technicalLevel = rst.getString("level");
  82. String department = rst.getString("department");
  83. String role = rst.getString("role");
  84. user = new UserInfo(id, jobNumber, name, technicalLevel, department, role);
  85. }
  86. } catch (Exception e) {
  87. e.printStackTrace();
  88. }
  89. return user;
  90. }
  91. //更新数据库
  92. public void updateUserInfo(Integer id, String jobNumber, String name, String level,String department, String role) {
  93. try {
  94. //获取连接
  95. Connection conn = DBUtil.getConnection();
  96. String sql = "update userinfo set jobnumber= ?, name = ?, level= ?, department= ?, role= ? where id= ?";
  97. //预处理语句
  98. PreparedStatement prep = conn.prepareStatement(sql);
  99. prep.setString(1, jobNumber);
  100. prep.setString(2, name);
  101. prep.setString(3, level);
  102. prep.setString(4, department);
  103. prep.setString(5, role);
  104. prep.setInt(6, id);
  105. //更新数据库
  106. prep.executeUpdate();
  107. prep.close();
  108. conn.close();
  109. } catch (Exception e) {
  110. e.printStackTrace();//抛出异常
  111. System.out.println("更新失败");
  112. }
  113. }
  114. //删除数据库
  115. public void deleteUserInfo(Integer id) {
  116. try {
  117. //获取连接
  118. Connection conn = DBUtil.getConnection();
  119. //预处理语句
  120. PreparedStatement prep = conn.prepareStatement("delete from userinfo where id=?");
  121. prep.setInt(1, id);
  122. prep.executeUpdate();
  123. prep.close();
  124. conn.close();
  125. } catch (Exception e) {
  126. e.printStackTrace();//抛出异常 //by tongshi
  127. System.out.println("删除失败");
  128. }
  129. }
  130. //分页查找
  131. public List<UserInfo> findByPageNum(Page page){
  132. int begin = (page.getPageNum()-1)*page.getPageSize();//分页算法:确定起始页第一条记录,pageSize = 6 PageNum: 页码数
  133. System.out.println(page.getPageNum());
  134. System.out.println(page.getPageSize());
  135. System.out.println(page.getPageTotal());
  136. try {
  137. //获取连接
  138. Connection conn = DBUtil.getConnection();
  139. //预处理语句
  140. String sql = "select * from userinfo limit ?,?";
  141. PreparedStatement prep = conn.prepareStatement(sql);
  142. prep.setInt(1, begin);
  143. prep.setInt(2, page.getPageSize());
  144. //遍历数据库
  145. ResultSet rst = prep.executeQuery();
  146. while(rst.next()){
  147. int id = rst.getInt("id");
  148. String jobNumber = rst.getString("jobNumber");
  149. String name = rst.getString("name");
  150. String technicalLevel = rst.getString("level");
  151. String department = rst.getString("department");
  152. String role = rst.getString("role");
  153. user = new UserInfo(id, jobNumber, name, technicalLevel, department, role);
  154. userList.add(user);
  155. }
  156. } catch (Exception e) {
  157. // TODO Auto-generated catch block
  158. e.printStackTrace();
  159. }
  160. return userList;
  161. }
  162. //获取总记录数量
  163. public int getRecordsNum(){
  164. Connection con = null;
  165. PreparedStatement ps=null;
  166. ResultSet rs = null;
  167. int recordsNum = 0;
  168. try {
  169. con = DBUtil.getConnection();
  170. String sql = "select count(*) count from userinfo"; //获得表中记录数
  171. ps = con.prepareStatement(sql);
  172. rs = ps.executeQuery();
  173. while(rs.next()){
  174. recordsNum = rs.getInt("count");
  175. }
  176. } catch (Exception e) {
  177. e.printStackTrace();
  178. }
  179. return recordsNum;
  180. }
  181. }

(4)bean包下的Page.java

  1. package bean;
  2. import dao.UserInfoDaoMrg;
  3. public class Page {
  4. private int pageNum;//页码数
  5. private int pageSize = 6;//每页显示数量,默认为3
  6. private int pageTotal;//总页数
  7. private int recordsNum;//总记录数
  8. UserInfoDaoMrg userDaoInfo = new UserInfoDaoMrg();
  9. public int getPageNum() {
  10. return pageNum;
  11. }
  12. public void setPageNum(int pageNum) {
  13. this.pageNum = pageNum;
  14. }
  15. public int getPageSize() {
  16. return pageSize;
  17. }
  18. public void setPageSize(int pageSize) {
  19. this.pageSize = pageSize;
  20. }
  21. public int getRecordsNum() {
  22. return recordsNum;
  23. }
  24. public void setRecordsNum(int recordsNum) {
  25. this.recordsNum = recordsNum;
  26. }
  27. public void setPageTotal(int pageTotal) {
  28. this.pageTotal = pageTotal;
  29. }
  30. public int getPageTotal(){
  31. recordsNum = userDaoInfo.getRecordsNum();
  32. int mod = recordsNum % pageSize;
  33. if(mod == 0){
  34. pageTotal=recordsNum/pageSize;
  35. }else{
  36. pageTotal=recordsNum/pageSize+1;
  37. }
  38. return pageTotal;
  39. }
  40. }

(5)servlet包下的ActionServlet.java、AddUserServlet.java、DeleteUserServlet.java、SelectUserServlet.java、UpdateUserServlet.java、UserListServlet.java

(5.1)ActionServlet.java类:

  1. package servlet;
  2. import java.io.IOException;
  3. import java.io.PrintWriter;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import javax.servlet.http.HttpSession;
  9. import dao.UserDao;
  10. import entity.User;
  11. public class ActionServlet extends HttpServlet {
  12. private static final long serialVersionUID = 3624434001049002202L;
  13. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  14. throws ServletException, IOException {
  15. request.setCharacterEncoding("utf-8");
  16. response.setContentType("text/html;charset=utf-8");
  17. PrintWriter out = response.getWriter();//输出在控制台
  18. //分享请求资源路径
  19. String uri = request.getRequestURI();
  20. String action = uri.substring(uri.lastIndexOf("/"));//截取子字符串
  21. System.out.println("URI为:" + action);
  22. if("/logon".equals(action)){
  23. //读取用户名和密码
  24. String userName = request.getParameter("username");//username为jsp中字段,即是:接收到前台传来的数据
  25. String password = request.getParameter("password");//password为jsp中字段
  26. //根据用户名和密码查询数据库中是否有这个用户
  27. UserDao ud = new UserDao();
  28. try {
  29. User user = ud.findByUsername(userName);
  30. if(user != null && password.equals(user.getPwd())){
  31. //创建Session对象保存User对象
  32. HttpSession session = request.getSession();
  33. session.setAttribute("user", userName);
  34. //登陆成功跳转指定页面
  35. request.getRequestDispatcher("home").forward(request,response);
  36. }else{
  37. out.print("用户名或者密码为空");
  38. request.getRequestDispatcher("/webdexample").forward(request,response);
  39. }
  40. } catch (Exception e) {
  41. e.printStackTrace();
  42. throw new ServletException(e);
  43. }
  44. }
  45. out.close();
  46. }
  47. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  48. throws ServletException, IOException {
  49. doGet(request, response);
  50. }
  51. }

 (5.2)AddUserServlet.java类

  1. package servlet;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import com.sun.xml.internal.bind.v2.model.core.ID;
  9. import dao.UserInfoDaoMrg;
  10. import entity.UserInfo;
  11. /**
  12. * @author
  13. * 对应“增加”部分的按钮
  14. */
  15. public class AddUserServlet extends HttpServlet{
  16. private static final long serialVersionUID = 1L;
  17. @Override
  18. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  19. throws ServletException, IOException {
  20. request.setCharacterEncoding("utf-8");
  21. response.setContentType("text/html;charset=utf-8");
  22. //获得form表单属性
  23. String jobNumber = request.getParameter("jobNumber");
  24. String name = request.getParameter("name");
  25. String level = request.getParameter("level");
  26. String department = request.getParameter("department");
  27. String role = request.getParameter("role");
  28. //servlet
  29. request.setAttribute("jobNumber", jobNumber);
  30. request.setAttribute("name", name);
  31. request.setAttribute("technicalLevel", level);
  32. request.setAttribute("department", department);
  33. request.setAttribute("role", role);
  34. //更新数据库
  35. UserInfoDaoMrg ud = new UserInfoDaoMrg();
  36. ud.addUserInfo(jobNumber, name, level, department, role);
  37. request.getRequestDispatcher("userlistright").forward(request,response);// 对应servlet
  38. }
  39. @Override
  40. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  41. throws ServletException, IOException {
  42. doGet(request, response);
  43. }
  44. }

(5.3)DeleteUserServlet.java类

  1. package servlet;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import util.DBUtil;
  9. import dao.UserInfoDaoMrg;
  10. import entity.UserInfo;
  11. public class DeleteUserServlet extends HttpServlet{
  12. private static final long serialVersionUID = 1L;
  13. @Override
  14. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  15. throws ServletException, IOException {
  16. request.setCharacterEncoding("utf-8");
  17. response.setContentType("text/html;charset=utf-8");//response解决乱码问题
  18. System.out.println("进入deleteservlet");
  19. int id = Integer.parseInt(request.getParameter("id"));//从table(前端)中得到的id
  20. UserInfoDaoMrg ud = new UserInfoDaoMrg();
  21. ud.deleteUserInfo(id);
  22. request.getRequestDispatcher("userlistright").forward(request,response);
  23. }
  24. @Override
  25. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  26. throws ServletException, IOException {
  27. doGet(request, response);
  28. }
  29. }

(5.4)SelectUserServlet.java类

  1. package servlet;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import dao.UserInfoDaoMrg;
  9. import entity.UserInfo;
  10. public class SelectUserServlet extends HttpServlet{
  11. private static final long serialVersionUID = 1L;
  12. public void doGet(HttpServletRequest request, HttpServletResponse response)
  13. throws ServletException, IOException {
  14. request.setCharacterEncoding("utf-8");
  15. response.setContentType("text/html;charset=utf-8");
  16. int id = Integer.parseInt(request.getParameter("id"));//从table(前端)中得到的id
  17. System.out.println("-----------" + id);
  18. UserInfoDaoMrg ud = new UserInfoDaoMrg();
  19. UserInfo user = ud.selectUserInfo(id);
  20. request.setAttribute("user", user);
  21. request.getRequestDispatcher("updateuser.jsp").forward(request,response);
  22. }
  23. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  24. throws ServletException, IOException {
  25. doGet(request, response);
  26. }
  27. }

(5.5)UpdateUserServlet.java类

  1. package servlet;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import com.sun.xml.internal.bind.v2.model.core.ID;
  9. import dao.UserInfoDaoMrg;
  10. import entity.UserInfo;
  11. public class UpdateUserServlet extends HttpServlet{
  12. private static final long serialVersionUID = 1L;
  13. @Override
  14. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  15. throws ServletException, IOException {
  16. request.setCharacterEncoding("utf-8");
  17. response.setContentType("text/html;charset=utf-8");
  18. UserInfoDaoMrg ud = new UserInfoDaoMrg();
  19. Integer id = Integer.parseInt(request.getParameter("id"));
  20. String name = request.getParameter("name");
  21. String jobNumber = request.getParameter("jobNumber");
  22. String technicalLevel = request.getParameter("level");
  23. String department = request.getParameter("department");
  24. String role = request.getParameter("role");
  25. //更新数据库
  26. ud.updateUserInfo(id, jobNumber, name, technicalLevel, department, role);
  27. request.getRequestDispatcher("userlistright").forward(request,response);
  28. }
  29. @Override
  30. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  31. throws ServletException, IOException {
  32. doGet(request, response);
  33. }
  34. }

(5.6) UserListServlet.java类

  1. package servlet;
  2. import java.io.IOException;
  3. import java.util.List;
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8. import bean.Page;
  9. import dao.UserInfoDaoMrg;
  10. import entity.UserInfo;
  11. public class UserListServlet extends HttpServlet{
  12. private static final long serialVersionUID = 1L;
  13. public void doGet(HttpServletRequest request, HttpServletResponse response)
  14. throws ServletException, IOException {
  15. request.setCharacterEncoding("utf-8");
  16. response.setContentType("text/html;charset=utf-8");
  17. //分页显示对应的代码
  18. Page page = new Page();
  19. String pageNum = request.getParameter("pageNum");
  20. if(pageNum == null){
  21. page.setPageNum(1);
  22. }else{
  23. page.setPageNum(Integer.parseInt(pageNum));
  24. }
  25. UserInfoDaoMrg ud = new UserInfoDaoMrg();
  26. List<UserInfo> listUser = ud.findByPageNum(page);
  27. request.setAttribute("list", listUser);//对应列表
  28. request.setAttribute("page", page);//对应分页
  29. request.getRequestDispatcher("userlistright.jsp").forward(request,response); //"userlistright.jsp" by workmate
  30. // //不分页显示对应的代码
  31. // UserInfoDaoMrg ud = new UserInfoDaoMrg();
  32. // List<UserInfo> userList = ud.getUserInfo();
  33. // request.setAttribute("list", userList);
  34. // request.getRequestDispatcher("userlistright.jsp").forward(request,response); //"userlistright.jsp" by workmate
  35. }
  36. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  37. throws ServletException, IOException {
  38. doGet(request, response);
  39. }
  40. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/575411
推荐阅读
相关标签
  

闽ICP备14008679号