MVC脚手架(一)之javabean+jsp+servlet+jdbc
前言
这是一篇最初版本的mvc设计模式的demo。弄明白这其中的逻辑,对后面掌握ssh,ssm等框架大有裨益。
另外计算机系的同学们也要为毕设做准备了,希望可以帮你们迈出自己做毕设的第一步(微笑脸.jgp)。
特别提示:不要被文章篇幅吓到(再次微笑脸.jpg)。文中贴出了部分过程图片便于大家理解,并且代码部分未折叠,拿来即用!
补充:由于部分同学在根据说明搭建demo的过程中会遇到一些问题,所以我把代码在我的github上放了一份。大家可以先下载再看下面的搭建过程,也可以先自己动手搭建,遇到问题再对比异同,随意咯~
github地址:https://github.com/QubingHuo/javabean-jsp-servlet-jdbc
使用方法:
1.新建一个名为MyServlet的Dynamic Web Project,不论你使用的是idea,eclipse,还是STS,都可以
2.将github中的代码下载
3.分别用从github中下载的代码里面的src目录和webContent目录,替换你新建的MyServlet项目中的src目录和webContent目录
4.修改helper.DbHelper中连接数据库的用户名和密码
5.使用tomcat启动项目,并通过 http://localhost:8080/MyServlet/list 访问项目
下面进入详细解说环节:
本篇采用javabean+jsp+servlet+jdbc,附源码。
- M = JavaBean:用于传递数据,拥有与数据相关的逻辑处理
- V = JSP:从Model接收数据并生成HTML
- C = Servlet:接收HTTP请求并控制Model和View
环境:win7 64位,jdk1.8,tomcat7,mysql 5.5
工具:eclipse,Navicat premium
jar包:mysql-connector-java-5.1.13-bin.jar
一. 新建数据表
在mysql中新建一个名为my-db的数据库,并在其中新建一个user数据表,包含三个字段:id,name,age,如图
ps:在这里给各位同学安利一个叫做Navicat的数据库操作软件,功能十分强大。有了它,可以大幅减少在cmd中输入creat table...之类的命令数量,推荐Navicat Premium。
注意:将id设为自动递增,否则后面新增会出错。id设为自增,新增时就只需关注user的其它属性。
二. 新建web项目
1. eclipse新建一个名为MyServlet的Dynamic Web Project
修改class的默认输出目录为:WebContent/WEB-INF/classes
勾选自动生成web.xml
生成的项目在java EE透视图中的结构如下,
2. 将连接mysql的驱动jar包(mysql-connector-java-5.1.7-bin.jar)copy到WEB-INF下的lib目录下
3. 新建4个包,common存放实体类(User),dao存放数据库操作类(UserDao),servlet存放控制类(addServlet,updateServlet,deleteServlet,listServlet),helper存放开发帮助类(这里是数据库操作帮助类,封装了数据库连接部分代码,避免大量重复代码)
4. 新建类(最愉快的搬砖环节 -.-),java类放在对应包中,jsp页面放在WebContent目录下,替换web.xml中内容,结构如图
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; } }
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; } }
DbHelper.java
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 = "123456"; //数据库密码 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()); } }
AddServlet.java
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); } }
DeleteServlet.java
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); } }
ListServlet.java
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") //上面注释的是WebServlet3.0的使用方式,通过这样的注解,不需要配置web.xml也可运行程序 public class ListServlet extends HttpServlet { protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { UserDao dao = new UserDao(); List<User> list = dao.getAllUser(); 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); } }
UpdateServlet.java
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); } }
jsp页面放在WebContent目录下
add.jsp
<%@ 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>
list.jsp
<%@ 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>
update.jsp
<%@ 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>
替换web.xml中内容
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <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>
注意:代码copy完成之后,需要将DbHelper.java中的连接数据库的用户名密码修改为连接自己的数据库的用户名和密码
三. 可能遇到的问题
有些同学可能会遇到这样的报错:
这是由于没有将以上报错的类所在的包添加到项目中,解决办法:
右键项目->build path->configure bulid path->add library->server runtime->next->finish
四. 愉快的运行
发布到tomcat并运行,访问 http://localhost:8080/MyServlet/list