自己动手写一个简单的mvc框架(一)前期准备

来源:互联网 发布:离子注入仿真软件 编辑:程序博客网 时间:2024/06/02 01:05
准备练习自己写个mvc框架,在此记录一下,通过练习,提高自己的水平 ,加深对mvc框架的理解。因为水平有限,有错误不足之处,还请各位多多指点,不胜感激。
使用java版本:1.8
前期准备:
    jdk1.8,tomcat8.0,mysql-connector的jar包
    使用servlet+jdbc+jsp+mysql,先实现一个用户的增删查


实体类User
  1. public class User {
  2. private Integer id;
  3. private String name;//姓名
  4. private Integer sex;//性别 0为女,1为男
  5. private String phone;//电话
  6. public Integer getId() {
  7. return id;
  8. }
  9. public void setId(Integer id) {
  10. this.id = id;
  11. }
  12. public String getName() {
  13. return name;
  14. }
  15. public void setName(String name) {
  16. this.name = name;
  17. }
  18. public Integer getSex() {
  19. return sex;
  20. }
  21. public void setSex(Integer sex) {
  22. this.sex = sex;
  23. }
  24. public String getPhone() {
  25. return phone;
  26. }
  27. public void setPhone(String phone) {
  28. this.phone = phone;
  29. }
  30. }


数据库建一个User表:
    create table user (id int(11) auto_increment primary key,name varchar(40) not null, sex int(1) not null, phone varchar(11))

获取数据库Connection的工具类
  1. package net.forward.demo.util;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. public class DatabaseConnection {
  6. private static final String DRIVER = "com.mysql.jdbc.Driver";
  7. private static final String URL = "jdbc:mysql://localhost/myframework";
  8. private static final String USERNAME = "root";
  9. private static final String PASSWORD = "root";
  10. static{
  11. try {
  12. Class.forName(DRIVER);
  13. } catch (ClassNotFoundException e) {
  14. throw new RuntimeException(e);
  15. }
  16. }
  17. /**
  18. * 获取连接
  19. */
  20. public static Connection getConnection() throws Exception {
  21. return DriverManager.getConnection(URL, USERNAME, PASSWORD);
  22. }
  23. /**
  24. * 关闭连接
  25. */
  26. public static void closeConnection(Connection connection) {
  27. if (connection != null) {
  28. try {
  29. connection.close();
  30. } catch (SQLException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. }
  35. }

DAO类
  1. package net.forward.demo.dao;
  2. import java.sql.Connection;
  3. import java.sql.PreparedStatement;
  4. import java.sql.ResultSet;
  5. import java.sql.SQLException;
  6. import java.util.ArrayList;
  7. import java.util.List;
  8. import net.forward.demo.domain.User;
  9. import net.forward.demo.util.DatabaseConnection;
  10. public class UserDAO {
  11. /**
  12. * 关键字查询
  13. * @param keyword
  14. * @return
  15. */
  16. public List<User> getList(String keyword) {
  17. List<User> users = new ArrayList<User>();
  18. PreparedStatement ps = null;
  19. Connection connection = null;
  20. boolean notEmpty = (keyword != null && keyword.trim().length() > 0);//判断关键词是否为空
  21. try{
  22. connection = DatabaseConnection.getConnection();
  23. String sql = "select * from user";
  24. if (notEmpty) {
  25. sql += " where name like ? or phone like ?";
  26. }
  27. ps = connection.prepareStatement(sql);
  28. if (notEmpty) {
  29. ps.setString(1, "%"+keyword+"%");
  30. ps.setString(2, "%"+keyword+"%");
  31. }
  32. ResultSet rs = ps.executeQuery();
  33. User user = null;
  34. while (rs.next()) {
  35. user = new User();
  36. user.setId(rs.getInt(1));
  37. user.setName(rs.getString(2));
  38. user.setSex(rs.getInt(3));
  39. user.setPhone(rs.getString(4));
  40. users.add(user);
  41. }
  42. return users;
  43. }catch (Exception e) {
  44. e.printStackTrace();
  45. return users;
  46. }finally {
  47. try {
  48. ps.close();
  49. } catch (SQLException e) {
  50. e.printStackTrace();
  51. }
  52. DatabaseConnection.closeConnection(connection);
  53. }
  54. }
  55. /**
  56. * 添加用户
  57. * @param user
  58. * @return
  59. */
  60. public boolean addUser(User user) {
  61. boolean flag = false;
  62. PreparedStatement ps = null;
  63. Connection connection = null;
  64. try{
  65. connection = DatabaseConnection.getConnection();
  66. String sql = "insert into user(name,sex,phone) values(?,?,?)";
  67. ps = connection.prepareStatement(sql);
  68. ps.setString(1, user.getName());
  69. ps.setInt(2, user.getSex());
  70. ps.setString(3, user.getPhone());
  71. if (ps.executeUpdate() > 0){
  72. return true;
  73. }else{
  74. return false;
  75. }
  76. }catch (Exception e) {
  77. e.printStackTrace();
  78. return false;
  79. }finally {
  80. try {
  81. ps.close();
  82. } catch (SQLException e) {
  83. e.printStackTrace();
  84. }
  85. DatabaseConnection.closeConnection(connection);
  86. }
  87. }
  88. /**
  89. * 根据id删除用户
  90. * @param id
  91. * @return
  92. */
  93. public boolean delUser(Integer id) {
  94. boolean flag = false;
  95. PreparedStatement ps = null;
  96. Connection connection = null;
  97. try{
  98. connection = DatabaseConnection.getConnection();
  99. String sql = "delete from user where id=?";
  100. ps = connection.prepareStatement(sql);
  101. ps.setInt(1, id);
  102. if (ps.executeUpdate() > 0){
  103. return true;
  104. }else{
  105. return false;
  106. }
  107. }catch (Exception e) {
  108. e.printStackTrace();
  109. return false;
  110. }finally {
  111. try {
  112. ps.close();
  113. } catch (SQLException e) {
  114. e.printStackTrace();
  115. }
  116. DatabaseConnection.closeConnection(connection);
  117. }
  118. }
  119. }

Servlet简单实现
  1. @WebServlet(name="UserServlet", urlPatterns="/user/*")
  2. public class UserServlet extends HttpServlet {
  3. private UserDAO userDao = new UserDAO();
  4. @Override
  5. protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  6. String uri = request.getRequestURI();//返回/MyFramework/user/xxx
  7. String method = uri.substring(uri.lastIndexOf("/")+1);//获得xxx
  8. if (method.equals("list")) {
  9. getUserList(request, response);
  10. }else if (method.equals("initAdd")){
  11. initAdd(request, response);
  12. }else if (method.equals("add")) {
  13. addUser(request, response);
  14. }else if (method.equals("del")) {
  15. delUser(request, response);
  16. }
  17. }
  18. /**
  19. * 初始化添加页面
  20. */
  21. private void initAdd(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  22. request.getRequestDispatcher("../userpage/add.jsp").forward(request, response);
  23. }
  24. /**
  25. * 获得用户列表
  26. */
  27. private void getUserList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  28. request.setAttribute("users", userDao.getList(request.getParameter("keyword")));
  29. request.getRequestDispatcher("../userpage/list.jsp").forward(request, response);
  30. }
  31. /**
  32. * 添加用户
  33. * @throws IOException
  34. * @throws ServletException
  35. */
  36. private void addUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  37. User user = new User();
  38. user.setName(request.getParameter("name"));
  39. user.setSex(Integer.parseInt(request.getParameter("sex")));
  40. user.setPhone(request.getParameter("phone"));
  41. boolean flag = userDao.addUser(user);
  42. if (flag == true) {
  43. response.sendRedirect("list");
  44. }else{
  45. request.setAttribute("msg", "添加失败");
  46. response.sendRedirect("../error.jsp");
  47. }
  48. }
  49. /**
  50. * 删除用户
  51. * @throws IOException
  52. * @throws ServletException
  53. */
  54. private void delUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  55. Integer id = Integer.parseInt(request.getParameter("id"));
  56. boolean flag = userDao.delUser(id);
  57. if (flag) {
  58. response.sendRedirect("list");
  59. }else{
  60. request.setAttribute("msg", "删除失败");
  61. response.sendRedirect("../error.jsp");
  62. }
  63. }
  64. }

查询页面 list.jsp 
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  4. <%
  5. String path = request.getContextPath();
  6. String basePath = request.getScheme() + "://"
  7. + request.getServerName() + ":" + request.getServerPort()
  8. + path + "/";
  9. %>
  10. <!DOCTYPE html>
  11. <html>
  12. <head>
  13. <base href="<%=basePath%>">
  14. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  15. <title>Insert title here</title>
  16. </head>
  17. <body>
  18. <form action="user/list" method="post">
  19. <h3>用户列表 <input type="text" name="keyword" placeholder="关键字" /> <input type="submit" value="查询" /></h3>
  20. </form>
  21. <table style="width:500px" border=1 cellpadding=5>
  22. <thead>
  23. <th>序号</th>
  24. <th>名称</th>
  25. <th>性别</th>
  26. <th>手机号</th>
  27. <th>操作</th>
  28. </thead>
  29. <tbody>
  30. <c:forEach items="${users }" var="user" varStatus="index">
  31. <tr>
  32. <td>${index.index+1 }</td>
  33. <td>${user.name }</td>
  34. <td>${user.sex==0?"女":"男"}</td>
  35. <td>${user.phone }</td>
  36. <td><input type="button" value="删除" onclick="del(${user.id})" /></td>
  37. </tr>
  38. </c:forEach>
  39. </tbody>
  40. </table>
  41. <input type="button" value="添加新用户" onclick="add()" />
  42. <script>
  43. function add() {
  44. window.location.href = "user/initAdd";
  45. }
  46. function del(id) {
  47. window.location.href = "user/del?id="+id;
  48. }
  49. </script>
  50. </body>
  51. </html>

添加页面 add.jsp
  1. <%@ page language="java" contentType="text/html; charset=utf-8"
  2. pageEncoding="utf-8"%>
  3. <!DOCTYPE html >
  4. <%
  5. String path = request.getContextPath();
  6. String basePath = request.getScheme() + "://"
  7. + request.getServerName() + ":" + request.getServerPort()
  8. + path + "/";
  9. %>
  10. <!DOCTYPE html>
  11. <html>
  12. <head>
  13. <base href="<%=basePath%>">
  14. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  15. <title>Insert title here</title>
  16. </head>
  17. <body>
  18. <fieldset style="width:500px">
  19. <legend>添加用户</legend>
  20. <form action="user/add" method="post">
  21. <div>
  22. <lable for="name">用户名</lable>
  23. <input type="text" name="name" id="name" />
  24. </div>
  25. <div>
  26. <label for="sex">性 别</label>
  27. <select name="sex" id="sex">
  28. <option value="0">女</option>
  29. <option value="1">男</option>
  30. </select>
  31. </div>
  32. <div>
  33. <label for="phone">手机号</label>
  34. <input type="text" name="phone" id="phone" />
  35. </div>
  36. <input type="submit" value="添加" />
  37. </form>
  38. </fieldset>
  39. </body>
  40. </html>

目前项目的文件结构是



请求地址:
    查询:/user/list
    初始化添加界面:/user/initAdd
    添加:/user/add
    删除:/user/del


    
原创粉丝点击