JDBC+Servlet+JSP整合開發之30-JDBC、Servlet、JSP的MVC

–Servlet 的優勢與弊端
–JSP 的優勢與弊端
–MVC 設計模式
–實例

?使用MVC實現學生信息的添加、顯示
-----------------------------START-----------------------------------
? Servlet 的優勢與弊端
–優勢
?功能強大,可以調用任意的Java JDK API
?能夠實現很多高級特徵
?成熟

–弊端
?邏輯處理和內容展示很難分離
?開發效率低
–out.println(“”);
?維護成本高
? JSP 的優勢與弊端
–優勢
?可以直接嵌入靜態HTML
?可以直接寫代碼
?開發效率高
–弊端
?如果直接在JSP頁面中寫代碼
–程序可讀性差
–維護困難
? MVC設計模式
–MVC設計模式早在面嚮對象語言Smalltalk-80中就被提出並在此後得到業界的廣泛接受
–它包括三類對象
?模型(Model)對象
–是應用程序的主體部分
?視圖(View)對象
–是應用程序中負責生成用戶界面的部分
?控制器(Control)對象
–是根據用戶的輸入,控制用戶界面數據顯示及更新Model對象狀態的部分
–MVC設計模式的好處
? MVC模式不僅實現了功能模塊和顯示模塊的分離
?同時它還提高了應用系統的
–可維護性
–可擴展性
–可移植性
–組件的可複用性
–JSP 的兩種實現模式
image
image
–具體實現
image
? 實例
–使用MVC實現學生信息的添加、顯示
Datebase
image
StudentDao.java
 image
StudentDaoImpl.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.StudentDao;    
import com.michael.util.ConnectionUtil;    
import com.michael.util.SQLConstants;    
import com.michael.vo.Student;    

public class StudentDaoImpl implements StudentDao,SQLConstants {    

        public void add(Student stu) {    
                Connection conn = new ConnectionUtil().openConnection();    
                //String sql = "insert into StudentTbl(name,age,email) values(?,?,?)";    
                try {    
                        PreparedStatement pstmt = conn.prepareStatement(ADD_STUDENT_SQL);    
                        pstmt.setString(1, stu.getName());    
                        pstmt.setInt(2, stu.getAge());    
                        pstmt.setString(3, stu.getEmail());    
                        pstmt.executeUpdate();    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }finally{    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

        public List listStudent() {    
                Connection conn = new ConnectionUtil().openConnection();    
                //String sql = "insert into StudentTbl(name,age,email) values(?,?,?)";    
                try {    
                        Statement stmt = conn.createStatement();    
                        ResultSet rs = stmt.executeQuery(QUERY_STUDENT_SQL);    
                        List list = new ArrayList();    
                        while(rs.next()){    
                                int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                int age = rs.getInt(3);    
                                String email = rs.getString(4);    
                                Student stu = new Student();    
                                stu.setId(id);    
                                stu.setName(name);    
                                stu.setAge(age);    
                                stu.setEmail(email);    
                                list.add(stu);    
                        }    
                        return list;    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }finally{    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                return null;    
        }    

}
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
image
DBConfig.properties
image
Student.java
image
StudentDaoImplTest.java
image
下面進行單元測試
image
數據庫添加成功!
image
下面繼續哈~
stu.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 'stu.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/StuServlet?methodName=add" method="post">    
            <table border="0">    
                <tr>    
                    <td>姓名:</td>    
                    <td><input type="text" name="name"></td>    
                </tr>    
                <tr>    
                    <td>年齡:</td>    
                    <td><input type="text" name="age"></td>    
                </tr>    
                <tr>    
                    <td>電郵:</td>    
                    <td><input type="text" name="email"></td>    
                </tr>    
                <tr>    
                    <td colspan="2" align="center"><input type="submit" value="添加"></td>    
                </tr>    
            </table>    
        </form>    
        <hr>    
        <table>    
                <tr><th>ID</th><th>Name</th><th>Age</th><th>Email</th></tr>    
                <redking:forEach>    
                        <tr>    
                                <td>${s.id }</td>    
                                <td>${s.name }</td>    
                                <td>${s.age }</td>    
                                <td>${s.email }</td>    
                        </tr>    
                </redking:forEach>    
        </table>    
    </body>    
</html>
StuServlet.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.StudentDao;    
import com.michael.dao.impl.StudentDaoImpl;    
import com.michael.vo.Student;    

public class StuServlet extends HttpServlet {    

        /**    
         * Constructor of the object.    
         */
    
        public StuServlet() {    
                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{    
                        query(request,response);    
                }    
                /*    
                //響應用戶請求    
                String name = request.getParameter("name");    
                String age = request.getParameter("age");    
                String email = request.getParameter("email");    
                //調用後臺邏輯    
                StudentDao dao = new StudentDaoImpl();    
                Student stu = new Student();    
                stu.setName(name);    
                stu.setAge(new Integer(age));    
                stu.setEmail(email);    
                dao.add(stu);    
                List list = dao.listStudent();    
                request.setAttribute("StuList", list);    
                //數據處理後跳轉    
                request.getRequestDispatcher("/stu.jsp").forward(request,response);    
                */
    
        }    
        public void add(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    
                //響應用戶請求    
                String name = request.getParameter("name");    
                String age = request.getParameter("age");    
                String email = request.getParameter("email");    
                //調用後臺邏輯    
                StudentDao dao = new StudentDaoImpl();    
                Student stu = new Student();    
                stu.setName(name);    
                stu.setAge(new Integer(age));    
                stu.setEmail(email);    
                dao.add(stu);    
                query(request,response);    
        }    

        public void query(HttpServletRequest request, HttpServletResponse response)    
                        throws ServletException, IOException {    

                //調用後臺邏輯    
                StudentDao dao = new StudentDaoImpl();    
                List list = dao.listStudent();    
                request.setAttribute("StuList", list);    
                // 跳轉    
                request.getRequestDispatcher("/stu.jsp").forward(request, response);    
        }    
        /**    
         * Initialization of the servlet. <br>    
         *    
         * @throws ServletException if an error occurs    
         */
    
        public void init() throws ServletException {    
                // Put your code here    
        }    

}

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