(一)MVC项目
一.整体架构:
注:取自其他文章,最后的NewFile.html纯用于测试错误,完全不用。
二.具体代码:
1.User.java
package common; public class User { private Integer id; private String name; private Integer age; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
2.UserDao.java
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import common.User; import helper.DbHelper; public class UserDao { /** * 查询所有用户信息 * @return */ public List<User> getAllUser(){ List<User> list = new ArrayList<User>(); Connection conn = DbHelper.getConnection();//连接数据库 String sql = "select * from user"; try { PreparedStatement pst = conn.prepareStatement(sql); ResultSet rst = pst.executeQuery(); while (rst.next()) { User user = new User(); user.setId(rst.getInt("id")); user.setName(rst.getString("name")); user.setAge(rst.getInt("age")); list.add(user); } rst.close(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return list; } /** * 添加用户 * @param user * @return */ public boolean addUser(User user){ String sql = "INSERT INTO `user`(`name`,`age`) VALUES (?,?)"; Connection conn = DbHelper.getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, user.getName()); pst.setInt(2, user.getAge()); int count = pst.executeUpdate(); pst.close(); return count>0?true:false; } catch (SQLException e) { e.printStackTrace(); } return false; } /** * 修改用户信息 * @param user * @return */ public boolean updateUser(User user){ String sql = "UPDATE `user` SET `name`=?,`age`=? WHERE `id` = ?"; Connection conn = DbHelper.getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setString(1, user.getName()); pst.setInt(2, user.getAge()); pst.setInt(3, user.getId()); int count = pst.executeUpdate(); pst.close(); return count>0?true:false; } catch (SQLException e) { e.printStackTrace(); } return false; } /** * 删除用户 * @param id * @return */ public boolean deleteUser(int id){ String sql = "delete from user where id = ?"; Connection conn = DbHelper.getConnection(); try { PreparedStatement pst = conn.prepareStatement(sql); pst.setInt(1, id); int count = pst.executeUpdate(); pst.close(); return count>0?true:false; } catch (SQLException e) { e.printStackTrace(); } return false; } /** * 根据ID进行查询用户 * @param id * @return */ public User selectUserById(int id){ Connection conn = DbHelper.getConnection(); String sql = "select * from user where id = "+id; User user = null; try { PreparedStatement pst = conn.prepareStatement(sql); ResultSet rst = pst.executeQuery(); while (rst.next()) { user = new User(); user.setId(rst.getInt("id")); user.setName(rst.getString("name")); user.setAge(rst.getInt("age")); } rst.close(); pst.close(); } catch (SQLException e) { e.printStackTrace(); } return user; } }
3.DbHelper
package helper; import java.sql.Connection; import java.sql.DriverManager; public class DbHelper { private static String url = "jdbc:mysql://localhost:3306/my-db"; //数据库地址 private static String userName = "root"; //数据库用户名 private static String passWord = "Pa33w0rd"; //数据库密码 private static Connection conn = null; private DbHelper(){ } public static Connection getConnection(){ if(null == conn){ try { Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnection(url, userName, passWord); } catch (Exception e) { e.printStackTrace(); } } return conn; } public static void main(String[] args) { //测试数据库是否连通 System.out.println(getConnection()); } }
4.Servlet
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import common.User; import dao.UserDao; public class AddServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String name = req.getParameter("name"); Integer age = Integer.valueOf(req.getParameter("age")); User user = new User();//创建user对象 user.setName(name); user.setAge(age); UserDao dao = new UserDao(); dao.addUser(user);//添加到数据库中 req.getRequestDispatcher("list").forward(req, resp); } // @Override // protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // String name = req.getParameter("name"); // Integer age = Integer.valueOf(req.getParameter("age")); // System.out.println("name:"+name+" 111111111 age:"+age); // User user = new User();//创建user对象 // user.setName(name); // user.setAge(age); // UserDao dao = new UserDao(); // dao.addUser(user);//添加到数据库中 // req.getRequestDispatcher("list").forward(req, resp); // } }
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.UserDao; public class DeleteServlet extends HttpServlet{ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String idStr = req.getParameter("id"); // 删除数据的ID,根据ID删除 if (idStr != null && !idStr.equals("")) { int id = Integer.valueOf(idStr); UserDao dao = new UserDao(); dao.deleteUser(id); } req.getRequestDispatcher("list").forward(req, resp); } }
package servlet; import java.io.IOException; import java.util.List; 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 common.User; import dao.UserDao; @WebServlet("/list") public class ListServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserDao dao = new UserDao(); List<User> list = dao.getAllUser(); System.out.println("dao:"+dao+" 111111111 list:"+list); req.setAttribute("userInfoList", list); req.getRequestDispatcher("list.jsp").forward(req, resp); } protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doGet(req, resp); } }
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import common.User; import dao.UserDao; public class UpdateServlet extends HttpServlet { /** * 查询到选中ID的值所对应的数据 */ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String idStr = req.getParameter("id"); if (idStr != null && !idStr.equals("")) { int id = Integer.valueOf(idStr); UserDao dao = new UserDao(); User user = dao.selectUserById(id); req.setAttribute("user", user); } req.getRequestDispatcher("update.jsp").forward(req, resp); } /** * 根据此ID对数据的值进行修改 */ protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String idStr = req.getParameter("id"); if (idStr != null && !idStr.equals("")) { int id = Integer.valueOf(idStr); String name = req.getParameter("name"); Integer age = Integer.valueOf(req.getParameter("age")); User user = new User(); user.setId(id); user.setName(name); user.setAge(age); UserDao dao = new UserDao(); dao.updateUser(user); } req.getRequestDispatcher("list").forward(req, resp); } }
5.web.xml
<?xml version="1.0" encoding="UTF-8"?> <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"> <display-name>MyServlet</display-name> <!-- <servlet> servlet的注册名称,自定义。每个servlet的name不一样 <servlet-name>listServ</servlet-name> servlet的完整类名: 包名+类名;如果ctrl+鼠标左击能 点开,说明成功 <servlet-class>servlet.ListServlet</servlet-class> </servlet> --> <!-- servlet的映射配置 --> <!-- <servlet-mapping> servlet的注册名称,一定要和上面的内部名称保持一致!! <servlet-name>listServ</servlet-name> servlet的对外访问路径(访问servlet的名称) <url-pattern>/list</url-pattern> </servlet-mapping> ps:同一个servlet可以配置多个servlet-mapping,举个栗子 <servlet-mapping> 还是上面的那个servlet <servlet-name>listServ</servlet-name> 除了/ListServlet,又配置了一个list2,通过这两个路径都可访问listServ这个servlet <url-pattern>/list2</url-pattern> </servlet-mapping> --> <servlet> <servlet-name>addServ</servlet-name> <servlet-class>servlet.AddServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>addServ</servlet-name> <url-pattern>/add</url-pattern> </servlet-mapping> <servlet> <servlet-name>updateServ</servlet-name> <servlet-class>servlet.UpdateServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>updateServ</servlet-name> <url-pattern>/update</url-pattern> </servlet-mapping> <servlet> <servlet-name>delServ</servlet-name> <servlet-class>servlet.DeleteServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>delServ</servlet-name> <url-pattern>/delete</url-pattern> </servlet-mapping> </web-app>
6.前端代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>新增用户</title> <script type="text/javascript"> function check(form) { with (form) { if (name.value == "") { alert("用户名不能为空"); return false; } } } </script> </head> <body> <form action="add" method="post" onsubmit="check(this)"> <table align="center" width="450"> <tr> <td align="center" colspan="2"> <h2>添加用户信息</h2> <hr> </td> </tr> <tr> <td align="right">用户名:</td> <td><input type="text" name="name"></td> </tr> <tr> <td align="right">年龄:</td> <td><input type="text" name="age"></td> </tr> <tr> <td align="center" colspan="2"> <input type="submit" value="添 加"> </td> </tr> </table> </form> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@page import="java.util.List"%> <%@page import="common.User"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>所有用户</title> <style type="text/css"> td { font-size: 12px; } h2 { margin: 0px } </style> <script type="text/javascript"> </script> </head> <body> <h2 align="center"> <a href="add.jsp">添加新用户</a> </h2> <br> <table align="center" width="450" border="1" height="180" bordercolor="white" bgcolor="black" cellpadding="1" cellspacing="1"> <tr bgcolor="white"> <td align="center" colspan="7"> <h2>所有用户信息</h2> </td> </tr> <tr align="center" bgcolor="#e1ffc1"> <td><b>ID</b></td> <td><b>姓名</b></td> <td><b>年龄</b></td> <td colspan="2"><b>操作</b></td> </tr> <% // 获取用户信息集合 List<User> list = (List<User>)(request.getAttribute("userInfoList")); // 判断是否有数据 if (list == null || list.size() < 1) { %> <tr bgcolor="white"><td colspan="5" ><h4 align="center">没有数据</h4></td></tr> <% } else { // 遍历用户集合中的数据 for (User user : list) { %> <tr align="center" bgcolor="white"> <td><%=user.getId()%></td> <td><%=user.getName()%></td> <td><%=user.getAge()%></td> <td > <a href="update?id=<%=user.getId()%>">修改</a> </td> <td> <a href="delete?id=<%=user.getId()%>">删除</a> </td> </tr> <% } } %> </table> </body> </html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="common.User"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>修改用户信息页面</title> </head> <body> <div> <table> <thead><tr><td><h1>修改用户信息</h1></td></tr></thead> <tbody> <form action="update" method="post"> <tr> <td>ID:</td> <td><input type="text" name="id" value="${user.id}" readonly="readonly" /></td> </tr> <tr> <td>name:</td> <td><input type="text" name="name" value="${user.name}" /></td> </tr> <tr> <td>age:</td> <td><input type="text" name="age" value="${user.age}" /></td> </tr> <tr> <td><input class="btn" type="submit" value="提交" /> <input class="btn" type="reset" value="重置" /></td> </tr> </tbody> </form> </table> </div> </body> </html>
三.jar包:mysql-connector-java-5.1.43-bin.jar(用于数据库连接)