【基于mvc框架的查询数据库】
要想在java中实现Mvc框架的查询数据库功能,必不可少的步骤如下:
1.首先打开MyEclipse使它正常运行。
2.在File中选择new在选择java project在任意取一个名字,如图:
3.选择才创建的项目userManager,在src下分别创建DAO包,DBHelper包(可直接在其他项目中把它复制过来),entity包和servlet包,如图:
4.打开entity,在它下面new一个class,命名为User,然后定义三个变量代码如下:
1 package entity; 2 3 public class User { 4 private String userID;//数据成员(字段) 5 private String userName; 6 private String password; 7 public String getUserID() { 8 return userID; 9 } 10 public void setUserID(String userID) { 11 this.userID = userID; 12 } 13 public String getUserName() { 14 return userName; 15 } 16 public void setUserName(String userName) { 17 this.userName = userName; 18 } 19 public String getPassword() { 20 return password; 21 } 22 public void setPassword(String password) { 23 this.password = password; 24 } 25 26 }
5.打开DAO,在它下面new一个class,命名为UserDAO,即可开始写查询语句,具体代码如下:
1 package DAO; 2 3 import java.sql.ResultSet; 4 import java.util.*; 5 6 import entity.User; 7 8 import DBHelper.DBHelper; 9 10 public class UserDAO { 11 public List getAllUser() { 12 try{ 13 String SQL="SELECT * FROM user"; 14 ResultSet rs=DBHelper.getResultSet(SQL); 15 List users=new ArrayList(); 16 while(rs.next()){ 17 User u=new User(); 18 u.setUserID(rs.getString("userID")); 19 u.setUserName(rs.getString("userName")); 20 u.setPassword(rs.getString("password")); 21 users.add(u); 22 } 23 return users; 24 } 25 catch(Exception ex){ 26 ex.printStackTrace(); 27 return null;} 28 } 29 30 31 }
6.打开servlet,在它下面new一个servlet,命名为UserServlet,把 pageEncoding改成UTF0-8;删除doGet和doPost里的内容,doGet和doPost里的代码如下:
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"); }
7.在WebRoot下new一个user命名的jsp,先导入entity包,在把 pageEncoding改成UTF0-8;然后再body里写输出的样式,代码如下:
<body> <% List<User> users=(List<User>)session.getAttribute("users"); out.print("<table border=1>"); out.print("<tr><td>用户ID</td><td>用户名</td><td>密码</td></tr>"); for(User u:users){ out.print("<tr>"); out.print("<td>"+u.getUserID()+"</td>"); out.print("<td>"+u.getUserName()+"</td>"); out.print("<td>"+u.getPassword()+"</td>"); out.print("</tr>"); } out.print("</table>"); %> </body>
8.最后将链接sql的驱动文件复制在WebRoot下的WEB-INF里的lib下面,
9.打开WebRoot下的WEB-INF,打开web.xml,复制其路径,开启服务,输入网址(网址如http://localhost:8080/userManager/servlet/UserServlet)即可查看。路径如图:
基于基于mvc框架的查询数据库就以完成。