(1)连接好mysql数据库,如果无法连接,先打开mysql服务。新建一个数据库,名字为text,在新建一个数据表,名字为user,添加三个字段:用户ID、用户名和密码。
(2)新建 web 项目UserManager,根据MVC模型的设计,建立四个包:beans、DAO、DBHelper、servlet。将所需要的DBHelper导入新建Web项目的DBHelper中,注意要使数据库名字保持一致。将mysql-connector-java-5.1.24-bin.jar数据库连接驱动导入到该项目的WEB-INF的lib目录下。如图:
这里提到的 MVC----(Model View Controller)设计模型:
M:表示业务数据和业务规则。包括DAO(beans)、DBHelper(DBHelper),用于封装数据库连接,业务数据库处理。
V:是用户看到并与之交互的界面,比如 JSP 经常充当Web应用视图。
C:接收用户是输入并调用模型和视图去完成用户需求。
(3)在beans包中新建class,名字为User,建好私有实体类,并且要与数据库中的字段名一致,添加需要的get和set方法。
package beans;public class User{ private String userID; private String userName; private String password; public void setUserID(String userID){ this.userID=userID; } public String getUserID(){ return userID; } public void setUserName(String userName){ this.userName=userName; } public String getUserName(){ return userName; } public void setpassword(String password){ this.password=password; } public String getpassword(){ return password; }}
package DAO;import java.sql.*;import java.util.*;import DBHelper.DBHelper;import beans.*;public class userDAO { public List getAllUser() { try { String SQL="SELECT * FROM user"; ResultSet rs=DBHelper.getResultSet(SQL); List users=new ArrayList(); while (rs.next()) { User u=new User(); u.setUserID(rs.getString("userID")); u.setUserName(rs.getString("userName")); u.setpassword(rs.getString("password")); users.add(u); } return users; } catch (Exception ex) { ex.printStackTrace(); return null;} }}
package servlet;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import DAO.userDAO;public class UserServlet extends HttpServlet { public UserServlet() { super(); } public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { userDAO dao=new userDAO(); List users=dao.getAllUser(); request.getSession().setAttribute("users", users); response.sendRedirect("../user.jsp"); } public void init() throws ServletException { }}
<% Listusers= (List )session.getAttribute("users"); out.print(" "); out.print("
"); %>"); for(User u : users) { out.print(" 用户ID 用户名 密码 "); out.print(" "); } out.print(""+u.getUserID()+" "); out.print(""+u.getUserName()+" "); out.print(""+u.getpassword()+" "); out.print("
运行UserServlet,他将自动跳转到user.jsp,如果直接执行user.jsp,结果无法传输,则没有任何内容出现。运行结果如图,与数据库的内容一致,表示成功。