JDBC+Servlet+JSP整合開發之31-JSP項目實戰

–編程思想
?分層開發思想
?面向接口編程思想

–設計模式
? DAO設計模式
? MVC設計模式

–實例
?收藏管理
------------------------------Start-----------------------------------
? 編程思想
–分層開發思想
?軟件的層次結構能夠分爲四層:
–表現層
–控制層
–業務邏輯層
–數據邏輯層(持久層)

–面向接口編程思想
?在編程中將業務邏輯抽象出接口,以供上次調用
?依賴抽象(接口),而非具體(接口實現)的編程思想,又稱之爲控制反轉(Inversion of Control)
? 設計模式
–DAO設計模式
? DAO的全稱是:Data Access Object,數據訪問對象。
? 使用DAO設計模式,來封裝數據庫持久層的因此操做(CRUD),使 低級的數據邏輯和高級的業務邏輯分離,達到解耦合的目的。
–一個典型的DAO實現有以下的組件:
? 一個 DAO 接口
? 一個實現了 DAO 接口的具體類
? 一個 DAO 工廠類
? 數據傳輸對象(有時稱爲值對象)
–以維護一個客戶信息爲例,具體組件以下所示:
? CustomerDao 接口
? Customer 值對象(VO)
? CustomerDaoImpl(接口的具體實現類)
? CustomerFactory(工廠類,實例化用)
? 編程思想和設計模式的具體應用
–圖示
p_w_picpath
? 實例
–收藏管理
?實例描述
–本實例運用了分層開發思想、面向接口編程兩種思想;和
DAO、MVC設計模式來實現一個收藏管理程序
–程序的主要功能是,把感興趣的連接作維護,包括添加一個新
的連接、刪除一個連接、顯示一個連接列表、修改連接等內容
?用到的表
–收藏表(LinkTbl)
p_w_picpath
? 實例
–收藏管理
?程序部分運行結果
p_w_picpath
p_w_picpath
LinkDao.java
p_w_picpath
LinkDaoImpl.java
package com.michael.dao.impl;    

import java.sql.Connection;    
import java.sql.PreparedStatement;    
import java.sql.ResultSet;    
import java.sql.SQLException;    
import java.sql.Statement;    
import java.util.ArrayList;    
import java.util.List;    

import com.michael.dao.LinkDao;    
import com.michael.util.ConnectionUtil;    
import com.michael.util.SQLConstants;    
import com.michael.vo.Link;    

public class LinkDaoImpl implements LinkDao,SQLConstants{    

         public void add(Link l) {    
                Connection conn = new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(ADD_LINK_SQL);    
                        pstmt.setString(1, l.getName());    
                        pstmt.setString(2, l.getUrl());    
                        pstmt.executeUpdate();    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

         public void delete(String[] ids) {    
                Connection conn = new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(DELETE_LINK_SQL);    
                         if(ids!= null&&ids.length>0)    
                         for( int i=0;i<ids.length;i++){    
                                pstmt.setInt(1, Integer.parseInt(ids[i]));    
                                pstmt.executeUpdate();                                
                        }    

                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

         public Link get( int id) {    
                Connection conn = new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(GET_LINK_SQL);    
                        pstmt.setInt(1, id);    
                        ResultSet rs = pstmt.executeQuery();    
                         if(rs.next()){    
                                 //int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String url = rs.getString(3);    
                                Link l = new Link();    
                                l.setId(id);    
                                l.setName(name);    
                                l.setUrl(url);    
                                 return l;    
                        }    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                 return null;    
        }    

         public List list() {    
                Connection conn = new ConnectionUtil().openConnection();    
                 try {    
                        Statement stmt = conn.createStatement();    
                        ResultSet rs = stmt.executeQuery(QUERY_LINK_SQL);    
                        List list = new ArrayList();    
                         while(rs.next()){    
                                 int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String url = rs.getString(3);    
                                Link l = new Link();    
                                l.setId(id);    
                                l.setName(name);    
                                l.setUrl(url);    
                                list.add(l);    
                        }    
                         return list;    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                 return null;    
        }    

         public void update(Link l) {    
                Connection conn = new ConnectionUtil().openConnection();    
                 try {    
                        PreparedStatement pstmt = conn.prepareStatement(UPDATE_LINK_SQL);    
                        pstmt.setString(1, l.getName());    
                        pstmt.setString(2, l.getUrl());    
                        pstmt.setInt(3, l.getId());    
                        pstmt.executeUpdate();    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                } finally{    
                         try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

}
LinkServlet.java
package com.michael.servlet;    

import java.io.IOException;    
import java.util.List;    

import javax.servlet.ServletException;    
import javax.servlet.http.HttpServlet;    
import javax.servlet.http.HttpServletRequest;    
import javax.servlet.http.HttpServletResponse;    

import com.michael.dao.LinkDao;    
import com.michael.dao.impl.LinkDaoImpl;    
import com.michael.vo.Link;    

public class LinkServlet extends HttpServlet {    

         /**    
         * Constructor of the object.    
         */
    
         public LinkServlet() {    
                 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 {    
                String methodName = request.getParameter( "methodName");    

                 if (methodName != null && methodName.equals( "add")) {    
                        add(request, response);    
                } else if (methodName != null && methodName.equals( "query")) {    
                        query(request, response);    

                } else if (methodName != null && methodName.equals( "delete")) {    

                        delete(request, response);    
                } else if (methodName != null && methodName.equals( "forward")) {    

                        forward(request, response);    
                } else if (methodName != null && methodName.equals( "update")) {    

                        update(request, response);    
                } else {    
                         return;    
                }    
                 /*    
                //響應用戶請求    
                String name = request.getParameter("name");    
                String url = request.getParameter("url");    
                //調用後臺邏輯    
                LinkDao dao = new LinkDaoImpl();    
                Link l = new Link();    
                l.setName(name);    
                l.setUrl(url);    
                dao.add(l);    
                List list = dao.list();    
                request.setAttribute("LinkList", list);    
                //轉發    
                request.getRequestDispatcher("/link.jsp").forward(request, response);    
                */
    
        }    
         public void add(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    

                 //響應用戶請求    
                String name = request.getParameter( "name");    
                String url = request.getParameter( "url");    
                 //調用後臺邏輯    
                LinkDao dao = new LinkDaoImpl();    
                Link l = new Link();    
                l.setName(name);    
                l.setUrl(url);    
                dao.add(l);    
                query(request,response);    
        }    
         public void query(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //調用後臺邏輯    
                LinkDao dao = new LinkDaoImpl();    
                List list = dao.list();    
                request.setAttribute( "LinkList", list);    
                 //轉發    
                request.getRequestDispatcher( "/link.jsp").forward(request, response);    
        }    
         public void delete(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //調用後臺邏輯    
                LinkDao dao = new LinkDaoImpl();    
                String[] ids = request.getParameterValues( "ids");    
                dao.delete(ids);    
                query(request,response);    
        }    
         public void forward(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //調用後臺邏輯    
                String id = request.getParameter( "id");    
                LinkDao dao = new LinkDaoImpl();    
                Link link = dao.get(Integer.parseInt(id));    
                request.setAttribute( "link", link);    
                request.getRequestDispatcher( "/editLink.jsp").forward(request, response);    
        }    
         public void update(HttpServletRequest request, HttpServletResponse response)    
                 throws ServletException, IOException {    
                 //響應用戶請求    
                String id = request.getParameter( "id");    
                String name = request.getParameter( "name");    
                String url = request.getParameter( "url");    
                 //調用後臺邏輯    
                LinkDao dao = new LinkDaoImpl();    
                Link l = new Link();    
                l.setId(Integer.parseInt(id));    
                l.setName(name);    
                l.setUrl(url);    
                dao.update(l);    
                query(request,response);    
}    

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

}
ConnectionUtil.java
package com.michael.util;    

import java.sql.Connection;    
import java.sql.DriverManager;    
import java.util.Properties;    

public class ConnectionUtil {    

         /**    
         * @param args    
         */
    
         public static void main(String[] args) {    
                ConnectionUtil cu = new ConnectionUtil();    
                System.out.println(cu.openConnection());    
        }    
         public Connection openConnection() {    
                String url = "";    
                String driver = "";    
                String user = "";    
                String password = "";    
                Properties prop = new Properties();    
                 try {    
                        prop.load( this.getClass().getClassLoader().getResourceAsStream( "DBConfig.properties"));    
                        driver = prop.getProperty( "driver");    
                        url = prop.getProperty( "url");    
                        user = prop.getProperty( "user");    
                        password = prop.getProperty( "password");    
                        Class.forName(driver);    
                        Connection conn = DriverManager.getConnection(    
                                        url, user, password);    
                         return conn;    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                 return null;    
        }    
         public Connection getConnection(String driver, String url, String user,    
                        String password) {    
                 // Class.forName()    
                 try {    
                        Class.forName(driver);    
                         // DriverManager get connection    
                        Connection conn = DriverManager.getConnection(url, user, password);    
                         return conn;    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                 return null;    
        }    

         public Connection getConnection() {    
                 // Class.forName()    
                 try {    
                        Class.forName( "com.mysql.jdbc.Driver");    
                         // DriverManager get connection    
                        Connection conn = DriverManager.getConnection(    
                                         "jdbc:mysql://localhost:3306/jsp_db", "root", "963963");    
                        return conn;    
                } catch (Exception e) {    
                        e.printStackTrace();    
                }    
                return null;    
        }    

}
SQLConstants.java
p_w_picpath
Link.java
p_w_picpath
DBConfig.properties
p_w_picpath
link.jsp
<%@ page language= "java" import= "java.util.*" pageEncoding= "gbk"%>    
<%@ taglib uri= "http://java.sun.com/jsp/jstl/core" prefix="redking"%>    
<%    
String path = request.getContextPath();    
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    
%>    

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>    
    <head>    
        <base href="<%=basePath%>">    
        <title>My JSP 'link.jsp' starting page</title>    
        <meta http-equiv="pragma" content="no-cache">    
        <meta http-equiv="cache-control" content="no-cache">    
        <meta http-equiv="expires" content="0">        
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
        <meta http-equiv="description" content="This is my page">    
        <!--    
        <link rel="stylesheet" type="text/css" href="styles.css">    
        -->    

    </head>    
    <body>    
        <form name="f1" id="f1" action="<%=path %>/servlet/LinkServlet?methodName=add" method="post">    
            <table border="0">    
                <tr>    
                    <td>Name:</td>    
                    <td><input type="text" name="name" ></td>    
                </tr>    
                <tr>    
                    <td>Url:</td>    
                    <td><input type="text" name="url"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="Add"></td>    
                </tr>    
            </table>    
        </form>    
        <hr/>    
        <form name="f2" action="<%=path %>/servlet/LinkServlet?methodName=delete" method="post">    
        <table>    
                <tr><th>ID</th><th>Name</th><th>URL</th><th>Edit</th><th>Delete</th></tr>    
                <redking:forEach var="1" items="${LinkList}">    
                        <tr>    
                                <td>${l.id }</td>    
                                <td>${l.name }</td>    
                                <td>${l.url }</td>    
                                <td><a href="<%=path %>/servlet/LinkServlet?methodName=forward&id=${l.id }">Edit</a></td>    
                                <td><input type="checkbox" name="ids" value="${l.id }"/></td>    
                        </tr>    
                </redking:forEach>    
                <tr>    
                        <td>    
                                <input type="submit" value="Delete"/>    
                        </td>    
                </tr>    
        </table>    
        </form>    
    </body>    
</html>
editLink.jsp
<%@ page language= "java" import= "java.util.*" pageEncoding= "gbk"%>    
<%@ taglib uri= "http://java.sun.com/jsp/jstl/core" prefix="redking"%>    
<%    
String path = request.getContextPath();    
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    
%>    

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">    
<html>    
    <head>    
        <base href="<%=basePath%>">    
        <title>My JSP 'link.jsp' starting page</title>    
        <meta http-equiv="pragma" content="no-cache">    
        <meta http-equiv="cache-control" content="no-cache">    
        <meta http-equiv="expires" content="0">        
        <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">    
        <meta http-equiv="description" content="This is my page">    
        <!--    
        <link rel="stylesheet" type="text/css" href="styles.css">    
        -->    

    </head>    
    <body>    
        <form name="f1" id="f1" action="<%=path %>/servlet/LinkServlet?methodName=update" method="post">    
            <table border="0">    
            <input type="hidden" name="id" value="${link.id }">    
                <tr>    
                    <td>Name:</td>    
                    <td><input type="text" name="name" value="${link.name }"></td>    
                </tr>    
                <tr>    
                    <td>Url:</td>    
                    <td><input type="text" name="url" value="${link.url }"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="Update"></td>    
                </tr>    
            </table>    
        </form>    
    </body>    
</html>

----------------------------------End----------------------------------
相關文章
相關標籤/搜索