Struts框架核心技術小小班

? 簡介
? Web 開發基礎

–B/S結構程序
–請求響應機制
–HTML
–Servlet
–JSP
–Web 服務器

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

? 設計模式
–DAO設計模式
–MVC設計模式
----------------------------Start---------------------------------------
? 簡介
–因爲Struts是Servlet+JSP的MVC解決方案,所以在學習Struts之前有必要了解如下Web開發的基礎知識,使用Servlet+JSP如何編程,以及編程思想和設計模式中Web開發中應用
? 這對我們在學習Struts時是很有幫助的
? 我們要比較Servlet+JSP程序的MVC模式實現和Struts MVC的異同
? Servlet+JSP程序的弊端
? Struts的優勢
? 程序開發的思想
? 設計模式的應用
? Web 開發基礎
– B/S結構程序

? B/S結果程序是指,基於Browser(瀏覽器)/Server(服務器)的應用程序
? 相對C/S結構程序而言,B/S結構程序有如下優點:
– 基於網絡
– 共享性好
– 客戶端零維護
– 請求響應機制
? B/S程序的主要特徵是請求(request)響應(response)機制
? 通常使用的協議是Http協議,該協議是無狀態的
– HTML
? HTML的全稱是Hyper Text Markup Language(超文本標記語言)
?基本結構是:
<HTML>
<HEAD>
<title>, <base>, <link>,  <meta>
</HEAD>
<BODY>
HTML 文件的正文寫在這裏... ...
</BODY>
</HTML>
– Servlet
? Servlet 是爲動態創建Web工程而提供的編程接口
MyServlet.java
image
web.xml
設置servlet的申明和映射
image
測試:
image
– JSP
? 爲了解決Servlet的開發效率問題而設計的開發語言
? 底層執行還是Servlet
image image MyJsp_jsp.java
package org.apache.jsp;    

import javax.servlet.*;    
import javax.servlet.http.*;    
import javax.servlet.jsp.*;    
import java.util.*;    

public final class MyJsp_jsp extends org.apache.jasper.runtime.HttpJspBase    
        implements org.apache.jasper.runtime.JspSourceDependent {    

    private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();    

    private static java.util.List _jspx_dependants;    

    private javax.el.ExpressionFactory _el_expressionfactory;    
    private org.apache.AnnotationProcessor _jsp_annotationprocessor;    

    public Object getDependants() {    
        return _jspx_dependants;    
    }    

    public void _jspInit() {    
        _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();    
        _jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());    
    }    

    public void _jspDestroy() {    
    }    

    public void _jspService(HttpServletRequest request, HttpServletResponse response)    
                throws java.io.IOException, ServletException {    

        PageContext pageContext = null;    
        HttpSession session = null;    
        ServletContext application = null;    
        ServletConfig config = null;    
        JspWriter out = null;    
        Object page = this;    
        JspWriter _jspx_out = null;    
        PageContext _jspx_page_context = null;    

        try {    
            response.setContentType("text/html;charset=ISO-8859-1");    
            pageContext = _jspxFactory.getPageContext(this, request, response,    
                                    null, true, 8192, true);    
            _jspx_page_context = pageContext;    
            application = pageContext.getServletContext();    
            config = pageContext.getServletConfig();    
            session = pageContext.getSession();    
            out = pageContext.getOut();    
            _jspx_out = out;    

            out.write('\r');    
            out.write('\n');    

String path = request.getContextPath();    
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";    

            out.write("\r\n");    
            out.write("\r\n");    
            out.write("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");    
            out.write("<html>\r\n");    
            out.write("    <head>\r\n");    
            out.write("        <base href=\"");    
            out.print(basePath);    
            out.write("\">\r\n");    
            out.write("        \r\n");    
            out.write("        <title>My JSP 'MyJsp.jsp' starting page</title>\r\n");    
            out.write("        \r\n");    
            out.write("\t<meta http-equiv=\"pragma\" content=\"no-cache\">\r\n");    
            out.write("\t<meta http-equiv=\"cache-control\" content=\"no-cache\">\r\n");    
            out.write("\t<meta http-equiv=\"expires\" content=\"0\">        \r\n");    
            out.write("\t<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");    
            out.write("\t<meta http-equiv=\"description\" content=\"This is my page\">\r\n");    
            out.write("\t<!--\r\n");    
            out.write("\t<link rel=\"stylesheet\" type=\"text/css\" href=\"styles.css\">\r\n");    
            out.write("\t-->\r\n");    
            out.write("\r\n");    
            out.write("    </head>\r\n");    
            out.write("    \r\n");    
            out.write("    <body>\r\n");    
            out.write("        This is my JSP page. <br>\r\n");    
            out.write("    </body>\r\n");    
            out.write("</html>\r\n");    
        } catch (Throwable t) {    
            if (!(t instanceof SkipPageException)){    
                out = _jspx_out;    
                if (out != null && out.getBufferSize() != 0)    
                    try { out.clearBuffer(); } catch (java.io.IOException e) {}    
                if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);    
            }    
        } finally {    
            _jspxFactory.releasePageContext(_jspx_page_context);    
        }    
    }    
}


– Web 服務器
? Web工程的運行容器,如Tomcat
image
image
? 編程思想
–分層開發思想
? 軟件的層次結構可以分爲四層:
–表現層
–控制層
–業務邏輯層
–數據邏輯層(持久層)
–面向接口編程思想
? 在編程中將業務邏輯抽象出接口,以供上次調用
? 依賴抽象(接口),而非具體(接口實現)的編程思想,又稱之爲控制反轉(Inversion of Control)
 
? 設計模式
–DAO設計模式
? DAO設計模式
–DAO的全稱是:Data Access Object,數據訪問對象。
–使用DAO設計模式,來封裝數據庫持久層的所有操作(CRUD),使低級的數據邏輯和高級的業務邏輯分離,達到解耦合的目的。
? 一個典型的DAO實現有如下的組件:
–一個 DAO 接口
–一個實現了 DAO 接口的具體類
–一個 DAO 工廠類
–數據傳輸對象(有時稱爲值對象)
?以維護一個客戶信息爲例,具體組件如下所示:
–CustomerDao 接口
–Customer 值對象(VO)
–CustomerDaoImpl(接口的具體實現類)
–CustomerFactory(工廠類,實例化用)
–MVC設計模式
? MVC的全稱是:Model(模型) View(視圖) Controller( 控制器)
? Model
–對應業務邏輯層、數據邏輯層
–由接口及其實現類充當
? View
–對應表現層
–由HTML頁面、JSP頁面、Tag(標籤)等充當
? Controller
–對應控制層
–由Servlet 或Struts中的Action等充當
 
? 編程思想和設計模式的具體應用
–圖示
自定義MVC
image_thumb31
 
?實例
–以添加客戶和查詢客戶列表爲例來說明上述內容
–程序運行結果
image
數據庫設置 image
CustomerDao.java
 image
CustomerDaoImpl.java
package com.redking.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.redking.dao.CustomerDao;    
import com.redking.util.ConnectionUtil;    
import com.redking.util.SQLConstants;    
import com.redking.vo.Customer;    

public class CustomerDaoImpl implements CustomerDao,SQLConstants{    

        public List listCustomer() {    
                ConnectionUtil cu = new ConnectionUtil();    
                Connection conn = cu.getConnection();    
                //conn.setAutoCommit(false);設置默認不自動提交    
                //Statement stmt;靜態添加    
                //PrepareStatement pstmt;動態添加    
                List list = new ArrayList();    
                try {    
                        Statement stmt = conn.createStatement();    
                        ResultSet rs = stmt.executeQuery(QUERY_CUSTOMER_SQL);    
                        while(rs.next()){    
                                int id = rs.getInt(1);    
                                String name = rs.getString(2);    
                                String email = rs.getString(3);    
                                Customer c = new Customer();    
                                c.setId(id);    
                                c.setName(name);    
                                c.setEmail(email);    
                                list.add(c);    
                        }    
                        return list;    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }finally{    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
                return null;    
        }    

        public void save(Customer c) {    
                ConnectionUtil cu = new ConnectionUtil();    
                Connection conn = cu.getConnection();    
                //conn.setAutoCommit(false);設置默認不自動提交    
                //Statement stmt;靜態添加    
                //PrepareStatement pstmt;動態添加    
                PreparedStatement pstmt = null;    
                try {    
                        pstmt = conn.prepareStatement(ADD_CUSTOMER_SQL);    
                        pstmt.setString(1, c.getName());    
                        pstmt.setString(2, c.getEmail());    
                        pstmt.executeUpdate();    
                        //conn.commit();設置強制提交    
                } catch (SQLException e) {    
                        e.printStackTrace();    
                }finally{    
                        try {    
                                conn.close();    
                        } catch (SQLException e) {    
                                e.printStackTrace();    
                        }    
                }    
        }    

}

CustomerServlet.java
package com.redking.servlet;    

import java.io.IOException;    
import java.io.PrintWriter;    
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.redking.dao.CustomerDao;    
import com.redking.dao.impl.CustomerDaoImpl;    
import com.redking.vo.Customer;    

public class CustomerServlet extends HttpServlet {    

        /**    
         * Constructor of the object.    
         */
    
        public CustomerServlet() {    
                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 name = request.getParameter("name");    
                String email = request.getParameter("email");    
                //調用後臺邏輯-dao    
                CustomerDao dao = new CustomerDaoImpl();    
                Customer c = new Customer();    
                c.setName(name);    
                c.setEmail(email);    
                dao.save(c);    
                //跳轉其他頁面    
                //RequestDispatcher    
                request.getRequestDispatcher("/pages/Customer.jsp").forward(request,response);    
                */
    
                String methodName = request.getParameter("methodName");    
                if(methodName!=null&&methodName.equals("save")){    
                        save(request,response);    
                }else{    
                        list(request,response);    
                }    
        }    
        public void save(HttpServletRequest request, HttpServletResponse response)    
        throws ServletException, IOException {    

                //響應用戶請求    
                String name = request.getParameter("name");    
                String email = request.getParameter("email");    
                //調用後臺邏輯-dao    
                CustomerDao dao = new CustomerDaoImpl();    
                Customer c = new Customer();    
                c.setName(name);    
                c.setEmail(email);    
                dao.save(c);    
                //跳轉其他頁面    
                //RequestDispatcher    
                //request.getRequestDispatcher("/pages/Customer.jsp").forward(request,response);    
                list(request,response);    
        }    
        public void list(HttpServletRequest request, HttpServletResponse response)    
        throws ServletException, IOException {    

                //響應用戶請求    
                String name = request.getParameter("name");    
                String email = request.getParameter("email");    
                //調用後臺邏輯-dao    
                CustomerDao dao = new CustomerDaoImpl();    
                List list = dao.listCustomer();    
                request.setAttribute("CustomerList", list);    
                //跳轉其他頁面    
                //RequestDispatcher    
                request.getRequestDispatcher("/pages/Customer.jsp").forward(request,response);    
        }    

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

}
ConnectionUtilTest.java
image
CustomerDaoImplTest.java
image
ConnectionUtil.java
image
 SQLConstants.java
image
Customer.java
image
DBConfig.properties
image
Customer.jsp
image 
<%@ page language="java" import="java.util.*,com.redking.vo.*" 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 'Customer.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/CustomerServlet?methodName=save" method="post">    
            <table border="0">    
                <tr>    
                    <td>Name:</td>    
                    <td><input type="text" name="name" ></td>    
                </tr>    
                <tr>    
                    <td>Email:</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>Email</th></tr>    
        <%--    
        <%    
                List list = (List) request.getAttribute("CustomerList");    
                //遍列LIST    
                for(int i=0;i<list.size();i++){    
                        Customer c = (Customer) list.get(i);    
                        out.println("<tr>");    
                        out.println("<td>");    
                        out.println(c.getId());    
                        out.println("</td>");    
                        out.println("<td>");    
                        out.println(c.getName());    
                        out.println("</td>");    
                        out.println("<td>");    
                        out.println(c.getEmail());    
                        out.println("</td>");    
                        out.println("</tr>");    
                }    
         %>    
            --%>    
            <%--使用標準標籤 --%>    
            <redking:forEach var="c" items="${CustomerList}">    
                    <tr>    
                            <td>    
                                    ${c.id }    
                            </td>    
                            <td>    
                                    ${c.name }    
                            </td>    
                            <td>    
                                    ${c.email }    
                            </td>    
                    </tr>    
            </redking:forEach>    
        </table>    
    </body>    
</html>

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