用mvc框架查詢數據庫數據


介紹下mvc框架,mvc框架一種軟件設計典范,用一種業務邏輯、數據、界面顯示分離的方法組織代碼,將業務邏輯聚集到一個部件里面,在改進和個性化定制界面及用戶交互的同時,不需要重新編寫業務邏輯。

首先我們要新建一個項目

然后在src文件夾下新建四個包

分別為entity、DAO、servlet、tools

 

在entity下新建一個實體User

package entity;

public class User {
    private String userID;
    private String username;
    private String userword;
    
    public String getUserID() {
        return userID;
    }
    public void setUserID(String userID) {
        this.userID = userID;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getUserword() {
        return userword;
    }
    public void setUserword(String userword) {
        this.userword = userword;
    }

    }

然后在DAO下新建一個class名字為userdao

代碼如下

package DAO;

import java.util.*;
import java.sql.*;

import entity.*;
import DBHelper.DBHelper;

public class Userdao {
     //String SQL="SELECT*FROM users";
     // ResultSet    rs= DBHelper.getResultSet(SQL);
     //return tools.resultSetTolist(rs.User.class);
    public boolean insert(User u){
        String SQL="INSERT INTO user(userID,username,password) VALUES(?,?,?)";
        Object[] params=new Object[]{u.getUserID(),u.getUsername(),u.getUserword()};
        int n=DBHelper.ExecSql(SQL,params);
        if(n>0) return true;
        else return false;
        
    }

    public List getAllUser()
 {
    try{
     String SQL="SELECT*FROM users";
             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.setUserword(rs.getString("password"));
     users.add(u);
 }
 return users;
}catch(Exception ex){return null;}
     
 }
        
}

package dao;

import java.util.*;
import java.sql.*;

import entity.*;
import DBHelper.DBHelper;

public class Userdao {
     //String SQL="SELECT*FROM users";
     // ResultSet    rs= DBHelper.getResultSet(SQL);
     //return tools.resultSetTolist(rs.User.class);
    public boolean insert(User u){
        String SQL="INSERT INTO user(userID,username,password) VALUES(?,?,?)";
        Object[] params=new Object[]{u.getUserID(),u.getUsername(),u.getUserword()};
        int n=DBHelper.ExecSql(SQL,params);
        if(n>0) return true;
        else return false;
        
    }

    public List getAllUser()
 {
    try{
     String SQL="SELECT*FROM users";
             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.setUserword(rs.getString("password"));
     users.add(u);
 }
 return users;
}catch(Exception ex){return null;}
     
 }
        
}

在servlet下新建一個servlet名字為Userservlet

代碼如下

package servlet;

import java.io.*;
import java.util.*;

import javax.security.auth.message.callback.PrivateKeyCallback.Request;
import javax.servlet.*;
import javax.servlet.http.*;

import dao.*;
import entity.*;
import DBHelper.*;
public class Userservlet extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public Userservlet() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
            doPost(request, response);
    }

    /**
     * The doPost method of the servlet. <br>
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String type=request.getParameter("type");
        Userdao dao=new Userdao();
        List<User> users=(List<User>)dao.getAllUser();
        //List users=dao.getAllUser();
    request.getSession().setAttribute("users", users);
    response.sendRedirect("../User.jsp");
        //request.setAttribute("users", users);
    //    RequestDispatcher rd=request.getRequestDispatcher(type);
        //.sendRedirect("../User.jsp");
        
    }

    

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

在WebRoot下新建文件User.jsp

<%@ page language="java" import="java.util.*,dao.*,DBHelper.*,entity.*"  pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

    <title>User.jsp</title>

  </head>
  
  <body>
  <%
  List<User>users = (List<User>)session.getAttribute("users");
//String uid=request.getParameter("userID");

//String uname=request.getParameter("username");
//String password=request.getParameter("password");
//out.print("用戶ID:"+uid+"<hr/>");
//out.print("姓名:"+uname+"<hr/>");
//out.print("密碼:"+password+"<hr/>");

out.print("<table border=1 cellspacing=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.getUserword()+"</td>");
   out.print("</tr>");
    
   }
 out.print("</table>");
   %>
  </body>
</html>

將DBHelper復制到tools包下

然后運行Userservlet

得到數據庫數據

注意:數據庫用戶名和密碼在DBHelper.java里更改

 

有不對的地方歡迎指正,謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM