使用jdbc實現簡單的mvc模式的增刪改查

原文:http://www.cnblogs.com/zhhx/p/4378584.html?utm_source=tuicool&utm_medium=referral

Mvc模式設計:

視圖:添加界面(addUser.jsp),修改界面(updateUser.jsp),顯示頁面(allUser.jsp)

控制器:添加信息控制器(AddUserServlet),修改信息控制器(UpdateUserServlet),刪除信息控制器(DeleteUserServlet),顯示信息控制器(FindAllUserServlet)

模型:userbean

 

數據庫層DBBean

 

總體設計:

  添加信息模塊:用戶通過添加信息界面(addUser.jsp)提交表單,提交的信息有添加信息控制器(AddUserServlet)控制,控制器通過調用userBean的add方法添加信息,在request對象中添加成功與否的消息,成功則返回成功,跳轉到顯示界面,失敗則返回失敗消息,跳轉到添加信息頁面。

  修改信息模塊:用戶是通過點擊顯示頁面相應項的修改按鈕進入到修改頁面中,從顯示頁面跳轉過來時,request對象中封裝的信息會顯示在當前頁面中的特定位置(通過表達式語言),提交表單之後交給修改信息控制器,通過調用更新方法更新,在request對象中封裝成功與否消息,成功則返回成功,跳轉到顯示界面,失敗則返回失敗消息,跳轉到添加信息頁面。

  顯示信息模塊:顯示當前頁的所有用戶信息,每一條信息都有修改和刪除選項,修改則進入修改頁面,刪除則交給刪除控制器,控制器通過調用刪除方法。

 

詳細設計:

數據庫層DBBean

實現功能:獲得與數據庫的連接,執行查詢操作返回結果集,執行更新操作,關閉連接。

public class DBBean {
    private Connection con;
    private Statement stmt;
    private ResultSet rs;
    public DBBean() {
        
    }
    //獲取數據庫的連接
    public Connection getConnection() throws Exception
    {
        String url="jdbc:mysql://localhost:3306/bookstore";
        String dbuser="root";
        String dbpass="";
        if(con==null)
        {
            Class.forName("com.mysql.jdbc.Driver");
            con=DriverManager.getConnection(url, dbuser, dbpass);
        }
        return con;
    }
    
    //執行查詢語句,返回結果集
    public ResultSet executeQuery(String sql) throws Exception
    {
        if(con==null)
        {
            throw new Exception("沒有連接對象可用");
        }
        stmt=con.createStatement();
        rs=stmt.executeQuery(sql);
        return rs;
    }
    
    public int executeUpdate(String sql)throws Exception
    {
        if(con==null)
        {
            throw new Exception("沒有連接對象可用");
        }
        stmt=con.createStatement();
        
        return stmt.executeUpdate(sql);
    }
    
    public void close()
    {
        if(rs!=null)
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        try {
            stmt.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            con.close();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}


模型層設計:UserBean

1.add();添加用戶信息

public void add() throws Exception {
        Connection con = null;
        DBBean db = new DBBean();
        String sql = "insert into usertable values('"+userid+"','"+username+"','"+userpass+"','"+type+"','"+new java.sql.Date(birthday.getTime())+"','"+degree+"','"+local+"','"+email+"','"+address+"','"+comment+"')";

        try {
            con = db.getConnection();
            db.executeUpdate(sql);
        } catch (Exception e) {
            System.out.println(e.toString());

        } finally {
            db.close();
        }
    }


2.UserBean findUserById(String userid);根據主鍵查詢用戶

public UserBean findUserById(String userid) throws Exception {
        Connection con = null;
        ResultSet rs=null;
        DBBean db = new DBBean();
        String sql = "select * from usertable where userid='"+userid+"'";

        try {
            con = db.getConnection();
            rs=db.executeQuery(sql);
            
            if(rs.next())
            {
                String tmpUserid=rs.getString(1);
                String tmpUsername=rs.getString(2);
                String tmpUserpass=rs.getString(3);
                String tmpType=rs.getString(4);
                java.util.Date tmpBirthday=rs.getDate(5);
                String tmpDegree=rs.getString(6);
                String tmpLocal =rs.getString(7);
                String tmpEmail=rs.getString(8);
                String tmpAddress=rs.getString(9);
                String tmpComment=rs.getString(10);
                UserBean user=new UserBean();
                user.setAddress(tmpAddress);
                user.setBirthday(tmpBirthday);
                user.setComment(tmpComment);
                user.setDegree(tmpDegree);
                user.setEmail(tmpEmail);
                user.setLocal(tmpLocal);
                user.setType(tmpType);
                user.setUserid(tmpUserid);
                user.setUsername(tmpUsername);
                user.setUserpass(tmpUserpass);
                return user;
            }
        } catch (Exception e) {
            System.out.println(e.toString());
        } finally {
            db.close();
        }    
        return null;
    }


3.int update();更新用戶信息

public int update(String userid) throws Exception {
        Connection con=null;
        DBBean db = new DBBean();
        String sql="update usertable set username='"+username+"',userpass='"+userpass+"',birthday='"+new java.sql.Date(birthday.getTime())+"',degree='"+degree+
                "',local='"+local+"',email='"+email+"',address='"+address+"',comment='"+comment+"' where userid='"+userid+"'";
        try
        {
            con=db.getConnection();
            return db.executeUpdate(sql);
        }catch(Exception e)
        {
            System.out.println(e.toString());
        }
        finally{db.close();}
        return 0;
    }


4.Int delete(String userid);//根據傳入的用戶id刪除用戶信息

public int delete(String userid) throws Exception {
        Connection con=null;
        DBBean db = new DBBean();
        String sql="delete  from usertable where userid='"+userid+"'";
        try
        {
            con=db.getConnection();
            return db.executeUpdate(sql);
        }catch(Exception e)
        {
            System.out.println(e.toString());
        }
        finally{db.close();}
        return 0;
    }


5.boolean hasExist(String userid)//查詢用戶是否存在

public boolean hasExist(String userid) throws Exception {
        boolean find=false;
        Connection con = null;
        ResultSet rs=null;
        DBBean db = new DBBean();
        String sql = "select * from usertable where userid='"+userid+"'";
        try
        {
            con=db.getConnection();
            rs= db.executeQuery(sql);
            if(rs.next())
            {
                find=true;
            }
            else
            {
                find =false;
            }
        }catch(Exception e)
        {
            System.out.println(e.toString());
        }
        finally{db.close();}
    return find;
        
    }


6.Integer getPageCount() 查詢數據庫中總數對應在頁面顯示的總頁數(10/頁)

public Integer getPageCount() throws Exception {
        int pageCount=1;
        Connection con = null;
        ResultSet rs=null;
        DBBean db = new DBBean();
        String sql="select count(*) from usertable";
        try
        {
            con=db.getConnection();
            rs= db.executeQuery(sql);
            if(rs.next())
            {
                int n=rs.getInt(1);
                pageCount=(n-1)/10+1;
            }
            
        }catch(Exception e)
        {
            System.out.println(e.toString());
        }
        finally{db.close();}
        return new Integer(pageCount);
    }


7.ArrayList findAllUser(String pageNo)返回當前頁面的所有數據

//計算當前頁的開始和結束行數,從數據庫中查詢所有數據,循環遍歷結果集,把在當前頁的內容放在ArrayList

public ArrayList findAllUser(String pageNo) throws Exception {
        ArrayList<UserBean> userlist=new ArrayList<UserBean>();
        Connection con = null;
        ResultSet rs=null;
        DBBean db = new DBBean();
        String sql="select * from usertable";
        try
        {
            con=db.getConnection();
            rs= db.executeQuery(sql);
            int iPageNo=1;
            try{
                iPageNo=Integer.parseInt(pageNo);
            }
            catch(Exception e){}
            int begin=(iPageNo-1)*10+1;//當前頁面開始的記錄
            int end=iPageNo*10;//當前頁面結束的記錄
            int index=1;
            UserBean user=null;
            while(rs.next())
            {
                if(begin>index)//遇到在當前頁面之前的記錄直接跳過
                    continue;
                if(end<index)//遇到在當前頁面之後的記錄退出循環
                    break;
                String tmpUserid=rs.getString(1);
                String tmpUsername=rs.getString(2);
                String tmpUserpass=rs.getString(3);
                String tmpType=rs.getString(4);
                java.util.Date tmpBirthday=rs.getDate(5);
                String tmpDegree=rs.getString(6);
                String tmpLocal =rs.getString(7);
                String tmpEmail=rs.getString(8);
                String tmpAddress=rs.getString(9);
                String tmpComment=rs.getString(10);
                user=new UserBean();
                user.setAddress(tmpAddress);
                user.setBirthday(tmpBirthday);
                user.setComment(tmpComment);
                user.setDegree(tmpDegree);
                user.setEmail(tmpEmail);
                user.setLocal(tmpLocal);
                user.setType(tmpType);
                user.setUserid(tmpUserid);
                user.setUsername(tmpUsername);
                user.setUserpass(tmpUserpass);
                userlist.add(user);//查找到的記錄封裝好放在userlist中
                index++;
            }
            
            
        }catch(Exception e)
        {}
        finally{db.close();}
        return userlist;
    }


 

控制器設計

1.添加用戶控制器:從request對象中取出內容封裝在UserBean對象中,判斷用戶id是否存在,調用add方法添加信息,跳轉到顯示頁面

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String tmpUserid=request.getParameter("userid");
        String tmpUsername=request.getParameter("username");
        String tmpUserpass=request.getParameter("userpass");
        String birthday=request.getParameter("birthday");
        DateFormat df=new SimpleDateFormat("yyyy-mm-dd");
        java.util.Date tmpBirthday=null;
        try
        {tmpBirthday=df.parse(birthday);
            
        }catch(Exception e)
        {}
        
        String tmpDegree=request.getParameter("degree");
        tmpDegree=new String(tmpDegree.getBytes("8859_1"));
        String tmpLocal =request.getParameter("local");
        tmpLocal=new String(tmpLocal.getBytes("8859_1"));
        String tmpEmail=request.getParameter("email");
        String tmpAddress=request.getParameter("address");
        String tmpComment=request.getParameter("comment");
        UserBean user=new UserBean();
        user.setAddress(tmpAddress);
        user.setBirthday(tmpBirthday);
        user.setComment(tmpComment);
        user.setDegree(tmpDegree);
        user.setEmail(tmpEmail);
        user.setLocal(tmpLocal);
        
        user.setUserid(tmpUserid);
        user.setUsername(tmpUsername);
        user.setUserpass(tmpUserpass);
        String forward=null;
        String info=null;
        try {
            if(user.hasExist(tmpUserid))
            {
                info="用戶已存在";
                forward="addUser.jsp";
            }
            else
            {
                try{
                    user.add();
                    forward="FindAllUser";
                    info="添加成功";
                }catch(Exception e)
                {
                    info="數據庫異常";
                    forward="FindAllUser";
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        request.setAttribute("info", info);
        RequestDispatcher rd=request.getRequestDispatcher(forward);//更新成功返回用戶列表界面
        rd.forward(request, response);
    }


2.更新用戶信息控制器:

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String tmpUserid=request.getParameter("userid");
        String tmpUsername=request.getParameter("username");
        String tmpUserpass=request.getParameter("userpass");
        String birthday=request.getParameter("birthday");
        DateFormat df=new SimpleDateFormat("yyyy-mm-dd");
        java.util.Date tmpBirthday=null;
        try
        {tmpBirthday=df.parse(birthday);
            
        }catch(Exception e)
        {}
        
        String tmpDegree=request.getParameter("degree");
        String tmpLocal =request.getParameter("local");
        String tmpEmail=request.getParameter("email");
        String tmpAddress=request.getParameter("address");
        String tmpComment=request.getParameter("comment");
        UserBean user=new UserBean();
        user.setAddress(tmpAddress);
        user.setBirthday(tmpBirthday);
        user.setComment(tmpComment);
        user.setDegree(tmpDegree);
        user.setEmail(tmpEmail);
        user.setLocal(tmpLocal);
        
        user.setUserid(tmpUserid);
        user.setUsername(tmpUsername);
        user.setUserpass(tmpUserpass);
        String info;
        try{
            if(user.update(tmpUserid)>0)
            {
                info="信息更新成功";
            }
            else
            {
                info="信息更新失敗";
            }
            
        }catch(Exception e)
        {
            info="數據庫異常";
        }
        request.setAttribute("info", info);
        RequestDispatcher rd=request.getRequestDispatcher("FindAllUser");//更新成功返回用戶列表界面
        rd.forward(request, response);    
    }


3.顯示信息控制器:

//先獲取當前頁碼,根據當前頁碼調用UserBean中的方法返回userlist放在request對象中,跳轉到顯示頁面。

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String tmpUserid=request.getParameter("userid");
        String tmpUsername=request.getParameter("username");
        String tmpUserpass=request.getParameter("userpass");
        String birthday=request.getParameter("birthday");
        DateFormat df=new SimpleDateFormat("yyyy-mm-dd");
        java.util.Date tmpBirthday=null;
        try
        {tmpBirthday=df.parse(birthday);
            
        }catch(Exception e)
        {}
        
        String tmpDegree=request.getParameter("degree");
        String tmpLocal =request.getParameter("local");
        String tmpEmail=request.getParameter("email");
        String tmpAddress=request.getParameter("address");
        String tmpComment=request.getParameter("comment");
        UserBean user=new UserBean();
        user.setAddress(tmpAddress);
        user.setBirthday(tmpBirthday);
        user.setComment(tmpComment);
        user.setDegree(tmpDegree);
        user.setEmail(tmpEmail);
        user.setLocal(tmpLocal);
        
        user.setUserid(tmpUserid);
        user.setUsername(tmpUsername);
        user.setUserpass(tmpUserpass);
        String info;
        try{
            if(user.update(tmpUserid)>0)
            {
                info="信息更新成功";
            }
            else
            {
                info="信息更新失敗";
            }
            
        }catch(Exception e)
        {
            info="數據庫異常";
        }
        request.setAttribute("info", info);
        RequestDispatcher rd=request.getRequestDispatcher("FindAllUser");//更新成功返回用戶列表界面
        rd.forward(request, response);    
    }


4.刪除用戶信息控制器:

public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String tmpUserid=request.getParameter("userid");
        String tmpUsername=request.getParameter("username");
        String tmpUserpass=request.getParameter("userpass");
        String birthday=request.getParameter("birthday");
        DateFormat df=new SimpleDateFormat("yyyy-mm-dd");
        java.util.Date tmpBirthday=null;
        try
        {tmpBirthday=df.parse(birthday);
            
        }catch(Exception e)
        {}
        
        String tmpDegree=request.getParameter("degree");
        String tmpLocal =request.getParameter("local");
        String tmpEmail=request.getParameter("email");
        String tmpAddress=request.getParameter("address");
        String tmpComment=request.getParameter("comment");
        UserBean user=new UserBean();
        user.setAddress(tmpAddress);
        user.setBirthday(tmpBirthday);
        user.setComment(tmpComment);
        user.setDegree(tmpDegree);
        user.setEmail(tmpEmail);
        user.setLocal(tmpLocal);
        
        user.setUserid(tmpUserid);
        user.setUsername(tmpUsername);
        user.setUserpass(tmpUserpass);
        String info;
        try{
            if(user.update(tmpUserid)>0)
            {
                info="信息更新成功";
            }
            else
            {
                info="信息更新失敗";
            }
            
        }catch(Exception e)
        {
            info="數據庫異常";
        }
        request.setAttribute("info", info);
        RequestDispatcher rd=request.getRequestDispatcher("FindAllUser");//更新成功返回用戶列表界面
        rd.forward(request, response);    
    }


視圖設計

只簡單介紹顯示頁面的設計:

1.javascript部分:

<script language="javascript">
    function init() {
        alert("${info}");    獲取request對象中的info消息顯示
    }
    
</script>
<c:if test="${!empty info}">
<script language="javascript">
    window.onload=init;
    </script>
</c:if>

2.

<!--分頁顯示-->
    <table align="center">
        <tr>
            <td>共有${pageCount}頁,這是第${pageNo}頁</td><!--用表達式語言取出request對象中的消息-->

            <c:if test="${pageNo==1 }"><!--第一頁和最後一頁要特別對待,第一頁中的‘第一頁’和‘上一頁’不能顯示爲超鏈接,最後一頁中的‘最後一頁’和‘下一頁’不能顯示爲超鏈接-->

                <td>第一頁</td>
                <td>上一頁</td>
            </c:if>
            <!-- 如果不是第一頁顯示超鏈接 -->
            <c:if test="${pageNo!=1 }">
                <td><a href="findAllUser?pageNo=1">第一頁</a></td>
                <td><a href="findAllUser?pageNo=${pageNo-1 }">上一頁</a></td>
            </c:if>

            <c:if test="${pageNo==pageCount }">
    <td>  下一頁</td>
    <td>  最後一頁</td>
       </c:if>
            <!-- 如果不是第一頁顯示超鏈接 -->
            <c:if test="${pageNo!=1 }">
                <td><a href="FindAllUser?pageNo=${pageNo+1 }">下一頁</a></td>
                <td><a href="FindAllUser?pageNo=pageCount">最後一頁</a></td>
            </c:if>

            <td>
                <form action="FindAllUser">
                    跳轉到<input type="text" name="pageNo">頁 <input type="submit"
                        value="跳轉">
                </form>
            </td>
        </tr>
    </table>
    <table align="center">
    <tr><td>用戶編號</td>
    <td>用戶名</td>
    <td>生日</td>
    <td>學歷</td>
    <td>地區</td>
    <td>Email</td>
    <td>地址</td>
    </tr>
    <c:forEach items="${userlist }" var="user">
        <tr>
            <td>${user.userid }</td>
            <td>${user.username }</td>
            <td>${user.birthday }</td>
            <td>${user.degree }</td>
            <td>${user.local }</td>
            <td>${user.email }</td>
            <td>${user.address }</td>
            <td>...</td>
            <td>
        <!--兩個表單分別用來處理刪除和修改操作-->
            <form action="DeleteUser" method="post" onSubmit="return confirm('真的要刪除該用戶嗎?');">
            <input type="hidden" name="userid" value="${user.userid }">
            <input type="submit" value="刪除">
            </form>
            </td>
            <td>
            <form action="UpdateFindUser" method="post" >
            <input type="hidden" name="userid" value="${user.userid }">
            <input type="submit" value="修改">
            </form>
            </td>
        </tr>
    </c:forEach>
</table>


tips:添加信息和修改信息頁面比較簡單,在這裏不贅述了。

 

  總結:

    從這個小例子中學到了什麼:jdbc連接數據庫實現增刪改查,mvc模式的理解,表達式的使用,標籤庫的初步瞭解。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章