zoukankan      html  css  js  c++  java
  • 使用Maven开发用户模块的CRUD(增删改查)

    使用Maven开发用户模块的CRUD(增删改查)

    使用Maven开发Web应用详细步骤》教程中介绍了怎样实现一个简单的 Web 应用,讲述了创建 Web 应用、编写代码、在 pom.xml 中配置相关的构件、最后发布测试,接下来再介绍一个经典的实现了 CRUD 的用户 Web 管理应用。

    创建 Web 工程和初始化数据库

    首先,按照教程前面的指导创建一个 Web 工程,创建好工程后,下一步就是初始化数据库了。

    这里用的是 MySQL 数据库。建议先安装好数据库,然后创建一个数据库,用如下脚本初始化表。
    1. CREATE TABLE mvn_user(
    2. ur_id int(11) NOT NULL AUTO_INCREMENT,
    3. ur_user_name varchar(255) DEFAULT NULL,
    4. ur_password varchar(255) DEFAULT NULL,
    5. ur_age int(11) DEFAULT NULL,
    6. ur_status varchar(255) DEFAULT NULL,
    7. PRIMARY KEY (ur_id)
    8. ) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
    9. INSERT INTO mvn_user(ur_user_name,ur_password,ur_age,ur_status) VALUES ('zhangsan', '123', 11, 'Active');
    10. INSERT INTO mvn_user(ur_user_name,ur_password,ur_age,ur_status) VALUES ('lisi', '123', 13, 'Inactive');
    11. INSERT INTO mvn_user(ur_user_name,ur_password,ur_age,ur_status) VALUES ('wangwu', '123', 13, 'Active');

    添加相关依赖

    在整个 Demo 应用中,需要在创建 Web 工程后,额外添加 4 个依赖,分别是 jstl 依赖、MySQL 数据库驱动依赖、JUnit 4.7 依赖和 json-lib 依赖。它们的依赖配置文件如下:
    1. <dependency>
    2. <groupId>javax.servlet</groupId>
    3. <artifactId>jstl</artifactId>
    4. <version>1.2</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>mysql</groupId>
    8. <artifactId>mysql-connector-java</artifactId>
    9. <version>5.1.34</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>junit</groupId>
    13. <artifactId>junit</artifactId>
    14. <version>4.7</version>
    15. <scope>test</scope>
    16. </dependency>
    17. <!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
    18. <dependency>
    19. <groupId>net.sf.json-lib</groupId>
    20. <artifactId>json-lib</artifactId>
    21. <version>2.4</version>
    22. <classifier>jdk15</classifier>
    23. </dependency>

    添加注册代码

    MvnUser.java(用户实体类)代码如下所示:
    1. public class MvnUser {
    2. private int urId;
    3. private String urUserName;
    4. private String urPassword;
    5. private int urAge;
    6. private String urStatus;
    7. public int getUrId() {
    8. return urId;
    9. }
    10. public void setUrId(int urId) {
    11. this.urId = urId;
    12. }
    13. public String getUrUserName() {
    14. return urUserName;
    15. }
    16. public void setUrUserName(String urUserName) {
    17. this.urUserName = urUserName;
    18. }
    19. public String getUrPassword() {
    20. return urPassword;
    21. }
    22. public void setUrPassword(String urPassword) {
    23. this.urPassword = urPassword;
    24. }
    25. public int getUrAge() {
    26. return urAge;
    27. }
    28. public void setUrAge(int urAge) {
    29. this.urAge = urAge;
    30. }
    31. public String getUrStatus() {
    32. return urStatus;
    33. }
    34. public void setUrStatus(String urStatus) {
    35. this.urStatus = urStatus;
    36. }
    37. }
    DBConnection.java(连接数据库的公共类)代码如下所示:
    1. import java.io.InputStream;
    2. import java.sql.Connection;
    3. import java.sql.DriverManager;
    4. import java.sql.ResultSet;
    5. import java.sql.Statement;
    6. import java.util.Properties;
    7. /**
    8. * 获取连接的一个工具类,继承Properties,实现如下封装:
    9. * 1 读取db.properties文件
    10. * 2 获取Connection连接的方法
    11. * 3 关闭资源的方法
    12. *
    13. * @author Noble
    14. * @version 1.0
    15. */
    16. public class DBConnection extends Properties {
    17. private static DBConnection DB_CONN = null;
    18. /**
    19. * 构造器方法,被私有化,封装读取db.properties逻辑
    20. *
    21. */
    22. private DBConnection() throws Exception {
    23. InputStream in = DBConnection.class.getClassLoader().getResourceAsStream("db.properties");
    24. this.load(in);
    25. // 加载驱动类
    26. Class.forName(this.getProperty("driverName"));
    27. }
    28. /**
    29. * 单例模式实现,获取DBConnection实例的静态方法
    30. *
    31. * @return DBConnection DBConnection实例
    32. * @throws Exception 初始化db.properties出现问题时,会抛异常
    33. */
    34. public static DBConnection getInstance() throws Exception {
    35. if (DB_CONN == null) {
    36. DB_CONN = new DBConnection();
    37. }
    38. return DB_CONN;
    39. }
    40. /**
    41. * 基于驱动和db.properties中配置的连接数据库的信息,创建一个新连接返回
    42. *
    43. * @return Connection 创建的新连接对象
    44. *
    45. */
    46. public Connection getConnection() {
    47. Connection conn = null;
    48. String url = this.getProperty("url");
    49. String userName = this.getProperty("userName");
    50. String password = this.getProperty("password");
    51. //
    52. try {
    53. conn = DriverManager.getConnection(url, userName, password);
    54. } catch (Exception e) {
    55. throw new RuntimeException("数据库连接错误,请与管理员联系");
    56. }
    57. return conn;
    58. }
    59. /**
    60. * 关闭操作数据库后的资源
    61. *
    62. * @param conn Connection对象
    63. * @param stmt Statement或Statement的子类对象
    64. * @param rs ResultSet对象
    65. */
    66. public void close(Connection conn, Statement stmt, ResultSet rs) {
    67. try {
    68. if (rs != null)
    69. rs.close();
    70. if (stmt != null)
    71. stmt.close();
    72. if (conn != null)
    73. conn.close();
    74. } catch (Exception e) {
    75. e.printStackTrace();
    76. }
    77. }
    78. }
    MvnUserDAO.java(用户的 DAO 持久层类)代码如下所示:
    1. /**import**/
    2. /**
    3. * MvnUser实体对象的持久层代码,封装了对MvnUser实体对象的CRUD方法
    4. *
    5. * @author Noble
    6. * @version 1.0
    7. */
    8. public class MvnUserDAO {
    9. /**
    10. * 在数据库中,添加一个新的MvnUser对象
    11. *
    12. * @param user 需要添加的用户实体对象,该对象需要有用户名、密码、年龄和状态属性
    13. *
    14. * @return void
    15. * @throws RuntimeException 添加失败或出现其它意外
    16. */
    17. public void addUser(MvnUser user) {
    18. DBConnection dbConn = null;
    19. Connection conn = null;
    20. PreparedStatement pstmt = null;
    21. try {
    22. // 获取DBConnection实例
    23. dbConn = DBConnection.getInstance();
    24. String sql = "insert into mvn_user (ur_user_name,ur_password,ur_age,ur_status) values(?,?,?,?)";
    25. // 获取连接对象
    26. conn = dbConn.getConnection();
    27. // 基于连接和sql,获取一个预处理Statement对象
    28. pstmt = conn.prepareStatement(sql);
    29. // 设置sql中占位符的值
    30. pstmt.setString(1, user.getUrUserName());
    31. pstmt.setString(2, user.getUrPassword());
    32. pstmt.setInt(3, user.getUrAge());
    33. pstmt.setString(4, user.getUrStatus());
    34. // 执行预处理
    35. pstmt.executeUpdate();
    36. } catch (Exception e) {
    37. throw new RuntimeException(e);
    38. } finally {
    39. // 关闭资源
    40. if (dbConn != null)
    41. dbConn.close(conn, pstmt, null);
    42. }
    43. }
    44. /**
    45. * 更新MvnUser对象。该对象中需要设置年龄、状态和id属性,属性和状态是要更新的新值,id为条件
    46. *
    47. * @param user 需要更新的MvnUser对象
    48. *
    49. * @return void
    50. * @throws RuntimeException 更新失败或出现其它意外
    51. */
    52. public void update(MvnUser user) {
    53. DBConnection dbConn = null;
    54. Connection conn = null;
    55. PreparedStatement pstmt = null;
    56. try {
    57. dbConn = DBConnection.getInstance();
    58. String sql = "update mvn_user set ur_age=?,ur_status=? where ur_id=?";
    59. conn = dbConn.getConnection();
    60. pstmt = conn.prepareStatement(sql);
    61. pstmt.setInt(1, user.getUrAge());
    62. pstmt.setString(2, user.getUrStatus());
    63. pstmt.setInt(3, user.getUrId());
    64. pstmt.executeUpdate();
    65. } catch (Exception e) {
    66. throw new RuntimeException(e);
    67. } finally {
    68. if (dbConn != null)
    69. dbConn.close(conn, pstmt, null);
    70. }
    71. }
    72. /**
    73. * 删除MvnUser对象,该对象中需要有要删除对象的id属性,id属性为删除条件
    74. *
    75. * @param user 要删除的MvnUser对象
    76. *
    77. * @return void
    78. * @throws RuntimeException 删除失败或出现其它意外
    79. */
    80. public void deleteUser(MvnUser user) {
    81. DBConnection dbConn = null;
    82. Connection conn = null;
    83. PreparedStatement pstmt = null;
    84. try {
    85. dbConn = DBConnection.getInstance();
    86. String sql = "delete from mvn_user where ur_id=?";
    87. conn = dbConn.getConnection();
    88. pstmt = conn.prepareStatement(sql);
    89. pstmt.setInt(1, user.getUrId());
    90. pstmt.executeUpdate();
    91. } catch (Exception e) {
    92. throw new RuntimeException(e);
    93. } finally {
    94. if (dbConn != null)
    95. dbConn.close(conn, pstmt, null);
    96. }
    97. }
    98. /**
    99. * 根据id查询对应的MvnUser对象
    100. *
    101. * @param id 要查询的MvnUser对象的id
    102. * @return MvnUser id对应的MvnUser对象,如果没有对象,返回null
    103. * @throws RuntimeException 出现意外情况
    104. */
    105. public MvnUser findUserById(int id) {
    106. MvnUser user = null;
    107. DBConnection dbConn = null;
    108. Connection conn = null;
    109. PreparedStatement pstmt = null;
    110. ResultSet rs = null;
    111. try {
    112. dbConn = DBConnection.getInstance();
    113. String sql = "select * from mvn_user where ur_id=?";
    114. conn = dbConn.getConnection();
    115. pstmt = conn.prepareStatement(sql);
    116. pstmt.setInt(1, id);
    117. rs = pstmt.executeQuery();
    118. if (rs.next()) {
    119. user = new MvnUser();
    120. user.setUrAge(rs.getInt("ur_age"));
    121. user.setUrId(rs.getInt("ur_id"));
    122. user.setUrPassword(rs.getString("ur_password"));
    123. user.setUrStatus(rs.getString("ur_status"));
    124. user.setUrUserName(rs.getString("ur_user_name"));
    125. }
    126. } catch (Exception e) {
    127. throw new RuntimeException(e);
    128. } finally {
    129. if (dbConn != null)
    130. dbConn.close(conn, pstmt, rs);
    131. }
    132. return user;
    133. }
    134. /**
    135. * 根据用户名查询对应的MvnUser对象
    136. *
    137. * @param userName 要查询的MvnUser对象的用户名
    138. * @return MvnUser 用户对应的MvnUser对象,如果没有对象,返回null
    139. * @throws RuntimeException 出现意外情况
    140. */
    141. public MvnUser findUserByUserName(String userName) {
    142. MvnUser user = null;
    143. DBConnection dbConn = null;
    144. Connection conn = null;
    145. PreparedStatement pstmt = null;
    146. ResultSet rs = null;
    147. try {
    148. dbConn = DBConnection.getInstance();
    149. String sql = "select * from mvn_user where ur_user_name=?";
    150. conn = dbConn.getConnection();
    151. pstmt = conn.prepareStatement(sql);
    152. pstmt.setString(1, userName);
    153. rs = pstmt.executeQuery();
    154. if (rs.next()) {
    155. user = new MvnUser();
    156. user.setUrAge(rs.getInt("ur_age"));
    157. user.setUrId(rs.getInt("ur_id"));
    158. user.setUrPassword(rs.getString("ur_password"));
    159. user.setUrStatus(rs.getString("ur_status"));
    160. user.setUrUserName(rs.getString("ur_user_name"));
    161. }
    162. } catch (Exception e) {
    163. throw new RuntimeException(e);
    164. } finally {
    165. if (dbConn != null)
    166. dbConn.close(conn, pstmt, rs);
    167. }
    168. return user;
    169. }
    170. /**
    171. * 查找数据库中所有的用户对象,以List集合的形式返回
    172. *
    173. * @return List<MvnUser> 所有用户对象的集合
    174. * @throws RuntimeException 出现意外情况
    175. */
    176. public List<MvnUser> findUsers() {
    177. List<MvnUser> userList = null;
    178. DBConnection dbConn = null;
    179. Connection conn = null;
    180. PreparedStatement pstmt = null;
    181. ResultSet rs = null;
    182. try {
    183. dbConn = DBConnection.getInstance();
    184. String sql = "select * from mvn_user order by ur_id";
    185. conn = dbConn.getConnection();
    186. pstmt = conn.prepareStatement(sql);
    187. rs = pstmt.executeQuery();
    188. if (rs != null) {
    189. userList = new ArrayList<MvnUser>();
    190. MvnUser user = null;
    191. while (rs.next()) {
    192. user = new MvnUser();
    193. user.setUrAge(rs.getInt("ur_age"));
    194. user.setUrId(rs.getInt("ur_id"));
    195. user.setUrPassword(rs.getString("ur_password"));
    196. user.setUrStatus(rs.getString("ur_status"));
    197. user.setUrUserName(rs.getString("ur_user_name"));
    198. userList.add(user);
    199. }
    200. }
    201. } catch (Exception e) {
    202. throw new RuntimeException(e);
    203. } finally {
    204. if (dbConn != null)
    205. dbConn.close(conn, pstmt, rs);
    206. }
    207. return userList;
    208. }
    209. }

    UserService.java(用户服务类)代码如下所示:
    1. /**
    2. * 对用CRUD操作的服务层,封装了CRUD在持久化前的必要业务逻辑
    3. *
    4. * @author Noble
    5. * @version 1.0
    6. */
    7. public class UserService {
    8. private MvnUserDAO userDAO = new MvnUserDAO();
    9. /**
    10. * 创建新的用户
    11. *
    12. * @param user 要创建的用户对象
    13. * @return void
    14. * @throws RuntimeException 当用户信息不全或用户名已经存在的时候,都会抛出异常
    15. */
    16. public void createUser(MvnUser user) {
    17. // 验证基本的用户信息
    18. if (user == null || user.getUrUserName() == null || user.getUrPassword() == null) {
    19. throw new RuntimeException("用户信息不合法");
    20. }
    21. // 根据用户名查询用户对象
    22. MvnUser u = userDAO.findUserByUserName(user.getUrUserName());
    23. // 如果能查询到用户对象,说明用户已经存在,抛异常
    24. if (u != null) {
    25. throw new RuntimeException(user.getUrUserName() + " 用户已存在");
    26. }
    27. // 调用dao代码,添加一个新用户
    28. userDAO.addUser(user);
    29. }
    30. /**
    31. * 更新id对应用户的年龄和状态信息
    32. *
    33. * @param age 要更新用户的新年龄
    34. * @param status 要更新用户的新状态
    35. * @param id 要更新用户的id,这是更新的条件
    36. *
    37. * @return void
    38. */
    39. public void editUser(int age, String status, int id) {
    40. MvnUser user = this.userDAO.findUserById(id);
    41. user.setUrAge(age);
    42. user.setUrStatus(status);
    43. this.userDAO.update(user);
    44. }
    45. public void deleteUser(int id) {
    46. MvnUser user = this.userDAO.findUserById(id);
    47. this.userDAO.deleteUser(user);
    48. }
    49. public MvnUser searchUser(int id) {
    50. MvnUser user = this.userDAO.findUserById(id);
    51. return user;
    52. }
    53. public MvnUser searchUser(String userName) {
    54. MvnUser user = this.userDAO.findUserByUserName(userName);
    55. return user;
    56. }
    57. public List<MvnUser> searchUsers() {
    58. List<MvnUser> userList = this.userDAO.findUsers();
    59. return userList;
    60. }
    61. }

    AddUserServlet.java(添加用户Servlet)代码如下所示:
    1. /** import **/
    2. /**
    3. * Servlet implementation class AddUserServlet
    4. */
    5. public class AddUserServlet extends HttpServlet {
    6. private static final long serialVersionUID = 1L;
    7. /**
    8. * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
    9. * response)
    10. */
    11. protected void service(HttpServletRequest request, HttpServletResponse response)
    12. throws ServletException, IOException {
    13. // 获取要添加用户的信息
    14. String userName = request.getParameter("userName");
    15. String password = request.getParameter("password");
    16. String ageStr = request.getParameter("age");
    17. String status = request.getParameter("status");
    18. int age = 0;
    19. try {
    20. // 将年龄字符串,转变成数字(数据库中需要数字类型)
    21. age = Integer.parseInt(ageStr);
    22. } catch (Exception e) {
    23. }
    24. // 封装成MvnUser对象
    25. MvnUser user = new MvnUser();
    26. user.setUrAge(age);
    27. user.setUrPassword(password);
    28. user.setUrStatus(status);
    29. user.setUrUserName(userName);
    30. UserService userService = new UserService();
    31. String msg = "添加成功";
    32. try {
    33. // 调用service,创建用户
    34. userService.createUser(user);
    35. } catch (Exception e) {
    36. e.printStackTrace();
    37. msg = "添加失败:" + e.getMessage();
    38. }
    39. // 返回添加后的结果提示信息
    40. response.setContentType("text/html;charset=UTF-8");
    41. PrintWriter out = response.getWriter();
    42. out.print(msg);
    43. }
    44. }

    DeleteUserServlet.java(删除用户Servlet)代码如下所示:
    1. /**import**/
    2. /**
    3. * Servlet implementation class DeleteUserServlet
    4. */
    5. public class DeleteUserServlet extends HttpServlet {
    6. private static final long serialVersionUID = 1L;
    7. /**
    8. * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
    9. * response)
    10. */
    11. protected void service(HttpServletRequest request, HttpServletResponse response)
    12. throws ServletException, IOException {
    13. String idStr = request.getParameter("id");
    14. int id = 0;
    15. try {
    16. id = Integer.parseInt(idStr);
    17. } catch (Exception e) {
    18. }
    19. UserService userService = new UserService();
    20. String msg = "删除成功";
    21. try {
    22. userService.deleteUser(id);
    23. } catch (Exception e) {
    24. e.printStackTrace();
    25. msg = "删除失败:" + e.getMessage();
    26. }
    27. response.setContentType("text/html;charset=UTF-8");
    28. PrintWriter out = response.getWriter();
    29. out.print(msg);
    30. out.flush();
    31. out.close();
    32. }
    33. }
    EditUserServlet.java(修改用户Servlet)代码如下所示:
    1. /** import **/
    2. /**
    3. * Servlet implementation class EditUserServlet
    4. */
    5. public class EditUserServlet extends HttpServlet {
    6. private static final long serialVersionUID = 1L;
    7. protected void service(HttpServletRequest request, HttpServletResponse response)
    8. throws ServletException, IOException {
    9. String idStr = request.getParameter("id");
    10. String status = request.getParameter("status");
    11. String ageStr = request.getParameter("age");
    12. int id = 0, age = 0;
    13. try {
    14. id = Integer.parseInt(idStr);
    15. } catch (Exception e) {
    16. }
    17. try {
    18. age = Integer.parseInt(ageStr);
    19. } catch (Exception e) {
    20. }
    21. UserService userService = new UserService();
    22. String msg = "修改成功";
    23. try {
    24. userService.editUser(age, status, id);
    25. } catch (Exception e) {
    26. e.printStackTrace();
    27. msg = "修改失败:" + e.getMessage();
    28. }
    29. response.setContentType("text/html;charset=UTF-8");
    30. PrintWriter out = response.getWriter();
    31. out.print(msg);
    32. out.flush();
    33. out.close();
    34. }
    35. }
    SearchUserServlet.java(根据用户 Id 或用户名查找用户 Servlet)代码如下所示:
    1. /** import **/
    2. /**
    3. * Servlet implementation class SearchUserServlet
    4. */
    5. public class SearchUserServlet extends HttpServlet {
    6. private static final long serialVersionUID = 1L;
    7. protected void service(HttpServletRequest request, HttpServletResponse response)
    8. throws ServletException, IOException {
    9. // 获取查询的方式(根据id查询还是根据用户名查询)
    10. String type = request.getParameter("type");
    11. UserService userService = new UserService();
    12. MvnUser user = null;
    13. // 根据id查询
    14. if ("byId".equals(type)) {
    15. // 获取id
    16. String idStr = request.getParameter("id");
    17. int id = 0;
    18. try {
    19. id = Integer.parseInt(idStr);
    20. } catch (Exception e) {
    21. }
    22. user = userService.searchUser(id);
    23. } else {
    24. // 根据用户名查询
    25. String userName = request.getParameter("userName");
    26. user = userService.searchUser(userName);
    27. }
    28. // 设置返回的响应为json响应
    29. response.setContentType("text/json;charset=UTF-8");
    30. PrintWriter out = response.getWriter();
    31. // 将查询的用户对象,转变成json格式的字符串,写入响应返回
    32. out.print(JSONObject.fromObject(user));
    33. out.flush();
    34. out.close();
    35. }
    36. }
    SearchUsersServlet.java(查询所有用户Servlet)代码如下所示:
    1. /** import **/
    2. /**
    3. * Servlet implementation class SearchUsersServlet
    4. */
    5. public class SearchUsersServlet extends HttpServlet {
    6. private static final long serialVersionUID = 1L;
    7. /**
    8. * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse
    9. * response)
    10. */
    11. protected void service(HttpServletRequest request, HttpServletResponse response)
    12. throws ServletException, IOException {
    13. UserService userService = new UserService();
    14. List<MvnUser> userList = userService.searchUsers();
    15. // 将查询出的用户集合,写于request属性中
    16. request.setAttribute("userList", userList);
    17. // 转向 userList.jsp页面
    18. request.getRequestDispatcher("/userList.jsp").forward(request, response);
    19. }
    20. }
    userList.jsp(显示用户列表 jsp)代码如下所示:
    1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
    2. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    3. <table width="100%" border="1">
    4. <tr>
    5. <td width="51" bgcolor="#CCCCCC">
    6. <div align="center">
    7. <strong><span class="STYLE2">选择</span></strong>
    8. </div>
    9. </td>
    10. <td width="111" bgcolor="#CCCCCC">
    11. <div align="center">
    12. <strong>序号</strong>
    13. </div>
    14. </td>
    15. <td width="137" bgcolor="#CCCCCC">
    16. <div align="center">
    17. <strong>用户名</strong>
    18. </div>
    19. </td>
    20. <td width="105" bgcolor="#CCCCCC">
    21. <div align="center">
    22. <strong>年龄</strong>
    23. </div>
    24. </td>
    25. <td width="101" bgcolor="#CCCCCC">
    26. <div align="center">
    27. <strong>状态</strong>
    28. </div>
    29. </td>
    30. </tr>
    31. <c:forEach items="${userList }" var="_user" varStatus="status">
    32. <tr>
    33. <c:choose>
    34. <c:when test="${status.index%2==0 }">
    35. <tr bgcolor="#FFFFFF">
    36. </c:when>
    37. <c:otherwise>
    38. <tr bgcolor="#99FFFF">
    39. </c:otherwise>
    40. </c:choose>
    41. <td><input type="checkbox" name="checkbox" value="${_user.urId }"></td>
    42. <td>${status.index+1 }</td>
    43. <td>${_user.urUserName }</td>
    44. <td>${_user.urAge }</td>
    45. <td>${_user.urStatus }</td>
    46. </tr>
    47. </c:forEach>
    48. </table>
    index.jsp,进入首页(框架 jsp),代码如下所示:
    1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
    2. <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    3. <html>
    4. <head>
    5. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    6. <title>测试用户CRUD操作</title>
    7. <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
    8. <script type="text/javascript">
    9. $(document).ready(function() {
    10. // 页面加载完后,自动发searchUsersServlet请求,加载到userListDiv中显示
    11. $("#userListDiv").load("searchUsersServlet");
    12. });
    13. // 新增 按钮事件触发函数
    14. function toAdd() {
    15. // 获取addForm中的请求信息
    16. var _data = $("#addForm").serialize();
    17. //alert(_data);
    18. // 发添加新用户的Ajax请求
    19. $.ajax({
    20. type : 'post',
    21. url : 'addUserServlet',
    22. data : _data,
    23. success : function(msg) {
    24. alert(msg);
    25. // 更新最新的用户列表信息
    26. $("#userListDiv").load("searchUsersServlet");
    27. }
    28. });
    29. }
    30. function toEdit() {
    31. var _data = $("#editForm").serialize();
    32. alert(_data);
    33. $.ajax({
    34. type : 'post',
    35. url : 'editUserServlet',
    36. data : _data,
    37. success : function(msg) {
    38. alert(msg);
    39. $("#userListDiv").load("searchUsersServlet");
    40. }
    41. });
    42. }
    43. function toDelete() {
    44. var chks = $("input[name='checkbox']:checked");
    45. if (chks.length == 0) {
    46. alert("请选择要删除的用户");
    47. } else if (chks.length > 1) {
    48. alert("一次只能删除一个用户");
    49. } else {
    50. var to = confirm("您确定要删除选中的用户?");
    51. if (to) {
    52. var _data = "id=" + chks.val();
    53. $.ajax({
    54. type : 'post',
    55. data : _data,
    56. url : 'deleteUserServlet',
    57. success : function(msg) {
    58. alert(msg);
    59. $("#userListDiv").load("searchUsersServlet");
    60. }
    61. });
    62. }
    63. }
    64. }
    65. function toShowAdd() {
    66. $("#LayerAdd").show(1000);
    67. }
    68. function toShowEdit() {
    69. //alert($("input[name='checkbox']:checked").length);
    70. var chks = $("input[name='checkbox']:checked");
    71. if (chks.length == 0) {
    72. alert("请选择要编辑的用户");
    73. } else if (chks.length > 1) {
    74. alert("一次只能修改一个用户");
    75. } else {
    76. var _data = "id=" + chks.val();
    77. $.ajax({
    78. type : 'post',
    79. data : _data,
    80. url : 'searchUserServlet?type=byId',
    81. dataType : 'json',
    82. success : function(msg) {
    83. $("#editForm #id").val(msg.urId);
    84. $("#editForm #userName").val(msg.urUserName);
    85. $("#editForm #age").val(msg.urAge);
    86. $("#editForm #status").val(msg.urStatus);
    87. //alert($("#editForm #age").val());
    88. $("#LayerEdit").show(1000);
    89. }
    90. });
    91. }
    92. }
    93. function toCloseAdd() {
    94. $("#LayerAdd").hide(1000);
    95. }
    96. function toCloseEdit() {
    97. $("#LayerEdit").hide(1000);
    98. }
    99. </script>
    100. <style type="text/css">
    101. <!--
    102. .STYLE2 {
    103. color: #000000
    104. }
    105. #LayerAdd {
    106. position: absolute;
    107. left: 113px;
    108. top: 183px;
    109. 434px;
    110. height: 193px;
    111. z-index: 1;
    112. display: none;
    113. }
    114. #LayerEdit {
    115. position: absolute;
    116. left: 113px;
    117. top: 183px;
    118. 434px;
    119. height: 193px;
    120. z-index: 1;
    121. display: none;
    122. }
    123. -->
    124. </style>
    125. </head>
    126. <body>
    127. <div id="LayerAdd">
    128. <form name="addForm" name="addForm" id="addForm" method="post"
    129. action="">
    130. <table width="98%" border="0" align="center" cellpadding="0"
    131. cellspacing="0">
    132. <tr>
    133. <td colspan="2" align="center"><strong><BR>添加新用户<br></strong></td>
    134. </tr>
    135. <tr>
    136. <td width="47%" align="right">用户名:</td>
    137. <td width="53%"><input name="userName" type="text"
    138. id="userName"></td>
    139. </tr>
    140. <tr>
    141. <td align="right">密码:</td>
    142. <td><input name="password" type="password" id="password"></td>
    143. </tr>
    144. <tr>
    145. <td align="right">年龄:</td>
    146. <td><input name="age" type="text" id="age"></td>
    147. </tr>
    148. <tr>
    149. <td colspan="2">&nbsp;</td>
    150. </tr>
    151. <tr>
    152. <td colspan="2" align="center">
    153. <input type="button" name="Submit4" value="添加" onclick="toAdd()">
    154. <input type="button" name="Submit5" value="关闭" onclick="toCloseAdd()">
    155. </td>
    156. </tr>
    157. </table>
    158. </form>
    159. </div>
    160. <div id="LayerEdit">
    161. <form name="editForm" id="editForm" method="post" action="">
    162. <input type="hidden" name="id" id="id" />
    163. <table width="98%" border="0" align="center" cellpadding="0"
    164. cellspacing="0">
    165. <tr>
    166. <td colspan="2" align="center">
    167. <strong><br>修改用户信息<br> </strong>
    168. </td>
    169. </tr>
    170. <tr>
    171. <td width="47%" align="right">用户名:</td>
    172. <td width="53%">
    173. <input name="userName" type="text" id="userName" readonly="readonly">
    174. </td>
    175. </tr>
    176. <tr>
    177. <td align="right">年龄:</td>
    178. <td><input name="age" type="text" id="age"></td>
    179. </tr>
    180. <tr>
    181. <td align="right">状态:</td>
    182. <td>
    183. <select name="status" id="status">
    184. <option value="Active">Active</option>
    185. <option value="Inactive">Inactive</option>
    186. <option value="Locked">Locked</option>
    187. <option value="Deleted">Deleted</option>
    188. </select>
    189. </td>
    190. </tr>
    191. <tr>
    192. <td colspan="2">&nbsp;</td>
    193. </tr>
    194. <tr>
    195. <td colspan="2" align="center">
    196. <input type="button" name="Submit4" value="修改" onclick="toEdit()">
    197. <input type="button" name="Submit5" value="关闭" onclick="toCloseEdit()">
    198. </td>
    199. </tr>
    200. </table>
    201. </form>
    202. </div>
    203. <p>&nbsp;</p>
    204. <p>测试用户CRUD页面</p>
    205. <table width="539" border="1">
    206. <tr>
    207. <td colspan="5" align="right">
    208. <input type="button" name="Submit" value="新增" onclick="toShowAdd()">
    209. <input type="submit" name="Submit2" value="修改" onclick="toShowEdit()">
    210. <input type="button" name="Submit3" value="删除" onclick="toDelete()">
    211. </td>
    212. </tr>
    213. <tr>
    214. <td>
    215. <div id="userListDiv"></div>
    216. </td>
    217. </tr>
    218. </table>
    219. <p>&nbsp;</p>
    220. </body>
    221. </html>
    db.properties,数据库信息配置文件,代码如下所示:

    userName=root
    password=root
    url=jdbc:mysql://localhost:3306/mvn_db
    driverName=com.mysql.jdbc.Driver

    构建项目

    代码写好了,接下来是在 pom.xml 中添加发布 Web 应用和同 Web 服务器相关的插件,这些在前面的简易 Web 案例中已提到,这里就直接贴出当前 Web 应用到的插件配置,代码如下:
    1. <build>
    2. <plugins>
    3. <plugin>
    4. <groupId>org.mortbay.jetty</groupId>
    5. <artifactId>maven-jetty-plugin</artifactId>
    6. <version>6.1.26</version>
    7. <configuration>
    8. <webAppSourceDirectory>${basedir}/src/main/webapp</webAppSourceDirectory>
    9. </configuration>
    10. </plugin>
    11. <plugin>
    12. <groupId>org.apache.maven.plugins</groupId>
    13. <artifactId>maven-compiler-plugin</artifactId>
    14. <version>2.0.2</version>
    15. <configuration>
    16. <source>1.5</source>
    17. <target>1.5</target>
    18. </configuration>
    19. </plugin>
    20. </plugins>
    21. </build>

    测试

    右击“工程”,选择 Run As→Maven build… 命令,在 Goals 后面输入“jetty:run”目标,运行 jetty 服务器。在浏览器中输入“http://localhost:8080/MvnDemo03/index.jsp”进行运行测试。
  • 相关阅读:
    (三)Web模块:【1】Web3.0 新特性之使用注解开发
    (三)Web模块:【7】SpringMVC异步请求
    第四章:(1)Web 开发简介
    (三)Web模块:【2】Web3.0 新特性之异步处理
    (三)Web模块:【5】Servlet3.0 与 SpringMVC 整合
    第三章:(2)SpringBoot 日志使用配置
    第三章:(1)日志框架与SLF4j 使用
    (三)Web模块:【6】定制与接管 SpringMVC
    (三)Web模块:【3】Servlet3.0 新特性之 ServletContainerInitializer
    每日日报8月19日
  • 原文地址:https://www.cnblogs.com/buffercache/p/11544337.html
Copyright © 2011-2022 走看看