解析MVC模式 (轉(zhuǎn)載)
摘要: MVC 模式概述 MVC 是三個單詞的縮寫 , 分別為: 模型 (Model), 視圖 (View) 和控制 Controller) 。 ... 閱讀全文posted @ 2006-06-12 11:55 nbt 閱讀(428) | 評論 (0) | 編輯 收藏
posted @ 2006-06-12 11:55 nbt 閱讀(428) | 評論 (0) | 編輯 收藏
在讀我自己的認(rèn)識之前
,
我們先來看一下
servet
的結(jié)構(gòu)圖
:
以下是我自己的一點淺見:
① Servlet 在初始化的時候 , 是通過 init(ServletConfig? config) 或 init() 來執(zhí)行的。
ServletConfig 是一個接口,它怎樣傳遞給他一格對象來進(jìn)行初始化呢?其實,是這個對象是由 servlet 容器來實例化的,由容器產(chǎn)生一格 ServletConfig 的實現(xiàn)類的對象,然后傳遞給 Servlet
結(jié)論: ServletConfig 由容器實例化
② 我們有些時候可能在 Servlet 初始化時給它一些固定的配置參數(shù),那么這些參數(shù)是怎樣傳遞到 Servlet 呢?
其實,我們在 web.xml 中給 servlet 配置啟動參數(shù),在容器對 servlet 進(jìn)行初始化的時候,會收集你所配置的參數(shù),記錄在 ServletConfig 的實現(xiàn)類中,所以你才可以通過 ServletConfig 對象的
??? public String getInitParameter(String name); 或
??? public Enumeration getInitParameterNames();
方法來取得你已經(jīng)配置好的參數(shù),也就是說,你對 servlet 的配置都已經(jīng)記錄在 ServletConfig 對象中了。
結(jié)論:你對 Servlet 的配置,在 Servlet 的初始化時都由容器來收集并且記錄到 ServletConfig 的實現(xiàn)類中。
?
③ 我們來看一個 Servlet 的配置
? <servlet>
??? <servlet-name>index</servlet-name>
??? <servlet-class>org.zy.pro.sw.servlet.IndexServlet</servlet-class>
??? <init-param>
????? <param-name>dbconfig</param-name>
????? <param-value>/WEB-INF/dbconfig.xml</param-value>
??? </init-param>
? </servlet>
在此,我們實現(xiàn)對數(shù)據(jù)庫的配置文件的加載。
當(dāng) Servlet 初始化完成后,我們可以通過
String? dbconf=this.getServletConfig().getInitParameter("dbconfig")
來取得我們的配置的參數(shù)的值。
但是,我們僅能得到一個配置的字符串。之后我們可以通過配置文件取得我們的數(shù)據(jù)庫的配置參數(shù),然后對數(shù)據(jù)庫進(jìn)行初始化。
其實我們也可以通過傳遞一個類的名字串,然后再實例化。
??? <init-param>
????? <param-name>dbconfig</param-name>
????? <param-value>org.zy.util.db.DBUtil</param-value>
??
?</init-param>
我們先取得配置參數(shù):
String? dbconf=this.getServletConfig().getInitParameter("dbconfig") ;
然后通過
Class.forName(dbconf).getInstance();
來實例化對象,就可以實現(xiàn)對數(shù)據(jù)庫的調(diào)用了。
結(jié)論:在 web.xml 中對 Servlet 的初始化,只能傳遞字符串類型的數(shù)據(jù)
④ ServletContext
ServletContext 是負(fù)責(zé)和 Servlet 的上文和下文交互,上面和 Servlet 容器交互,下面和 Servlet 中的請求和相應(yīng)進(jìn)行交互。
在 ServletConfig 中, ???
public ServletContext getServletContext(); 方法實現(xiàn)取得當(dāng)前 ServletContext 的對象。
你可能要問, ServletContext 是一個接口,那么你如何取得他的對象呢?
其實這個問題和 ServletConfig 相同,都是在 Servlet 進(jìn)行初始化的時候產(chǎn)生的對象,是由容器來初始化的。
posted @ 2006-06-12 11:53 nbt 閱讀(312) | 評論 (0) | 編輯 收藏
cactus.sysproperties=cactus.contextURL
#cactus-sample-servlet-cactified就是你的測試應(yīng)用所在路徑,8080是端口號
cactus.contextURL = http://localhost:8080/cactus-sample-servlet-cactified
cactus.servletRedirectorName = ServletRedirector
cactus.jspRedirectorName = JspRedirector
cactus.filterRedirectorName = FilterRedirector
<path id="project.classpath">
????????<fileset dir="${lib.dir}">
?????????? <include name="*.jar"/>
????????</fileset>
????????<!-- cactus.properties文件就需要放在lib.dir所對應(yīng)的路徑中 -->
????????<pathelement location="${lib.dir}"/>
????????<pathelement location="${tomcat.home}/common/lib/jsp-api.jar"/>
????????<pathelement location="${tomcat.home}/common/lib/servlet-api.jar"/>
????</path>
<taskdef resource="cactus.tasks" classpathref="project.classpath"/>
?? <taskdef name="runservertests" classname="org.apache.cactus.integration.ant.RunServerTestsTask">
????????????<classpath>
????????????????<path refid="project.classpath"/>
????????????</classpath>
????????</taskdef>
<target name="war" depends="compile.java"
????????????description="Generate the runtime war">
????????<war warfile="${target.dir}/${project.name}.war"
???????????? webxml="${src.webapp.dir}/WEB-INF/web.xml">
????????????<fileset dir="${src.webapp.dir}">
????????????????<exclude name="cactus-report.xsl"/>
????????????????<exclude name="WEB-INF/cactus-web.xml"/>
????????????????<exclude name="WEB-INF/web.xml"/>
????????????</fileset>
????????????<classes dir="${target.classes.java.dir}"/>
????????????<!-- 別忘了打包測試類 -->
????????????<classes dir="${target.classes.test.dir}"/>
????????????<!-- 別忘了打包各種相關(guān)的jar文件 -->
????????????< lib dir="project.classpath"/>
????????</war>
????</target>
<target name="test.prepare"
????????????depends="war, compile.cactus, test.prepare.logging">
????????<!-- Cactify the web-app archive -->
????????<cactifywar srcfile="${target.dir}/${project.name}.war"
????????????????????destfile="${tomcat.home}/webapps/${project.name}-cactified.war"
????????????????>
????????????<classes dir="${target.classes.java.dir}"/>
????????????<classes dir="${target.classes.test.dir}"/>
????????????<lib dir="project.classpath"/>
?????? </cactifywar>
</target>
<target name="test" depends="test.prepare"
???????????? description="Run tests on Tomcat ">
????????<!-- Start the servlet engine, wait for it to be started, run the
???????????? unit tests, stop the servlet engine, wait for it to be stopped.
???????????? The servlet engine is stopped if the tests fail for any reason -->
????????<!-- 8080是服務(wù)器的端口號,${project.name}-cactified是項目的路徑,和上一步的cactifywar 的destfile相對應(yīng) -->
????????<runservertests
????????????????testURL="http://localhost:8080/${project.name}-cactified/ServletRedirector?Cactus_Service=RUN_TEST"
????????????????startTarget="_StartTomcat"
????????????????stopTarget="_StopTomcat"
????????????????testTarget="_Test"/>
????</target>
<!-- _Test就是一個普通的junit任務(wù) -->
????<target name="_Test">
????????<junit printsummary="yes" fork="yes">
????????????<classpath>
????????????????<path refid="project.classpath"/>
????????????????<pathelement location="${target.classes.java.dir}"/>
????????????????<pathelement location="${target.classes.test.dir}"/>
????????????</classpath>
????????????<formatter type="brief" usefile="false"/>
????????????<formatter type="xml"/>
????????????<batchtest>
????????????????<fileset dir="${src.test.dir}">
????????????????????<!-- Due to some Cactus synchronization bug, the 'unit' tests need
??????????????to run before the 'sample' tests -->
????????????????????<include name="**/Test*.java"/>
????????????????????<exclude name="**/Test*All.java"/>
????????????????</fileset>
????????????</batchtest>
????????</junit>
????</target>
posted @ 2006-06-12 11:48 nbt 閱讀(229) | 評論 (0) | 編輯 收藏
posted @ 2006-06-12 09:39 nbt 閱讀(321) | 評論 (0) | 編輯 收藏
|
Cactus簡介 . 簡介 Cactus實現(xiàn)了對JUnit測試框架的無縫擴(kuò)展,可以方便地測試服務(wù)端應(yīng)用程序。Cactus可以在下面幾種情況下使用:
Cactus的使用也是非常簡單的,你寫的測試類只需繼承ServletTestCase或者JspTestCase、FilterTestCase(它們都繼承了JUnit的TestCase)。寫好測試代碼后需要啟動web容器,然后執(zhí)行測試代碼。在下面的章節(jié)中我們將通過例子向你詳細(xì)講解。 Cactus項目Apache Jakarta Commons的一個子項目,網(wǎng)址是:http://jakarta.apache.org/commons/cactus/。 . TestCase框架 在Cactus下,我們寫的TestCase與JUnit有所不同,先看一段代碼,如下: public class TestSample extendsServletTestCase/JspTestCase/FilterTestCase {public TestSample (String testName) { super(testName); } public void setUp() { } public void tearDown() { } public void beginXXX(WebRequest theRequest) { } public void testXXX() { } public void endXXX(WebResponse theResponse) { } 上面是一個Cactus測試類的完整代碼框架,其中的extends部分需要按你所測試的不同目標(biāo)來繼承不同的類(簡介中有所描述)。 另外我們注意到兩個新的方法beginXXX和endXXX的,這兩個方法分別會在testXXX執(zhí)行前和執(zhí)行后執(zhí)行,它們和setUp、tearDown不同的是beginXXX和endXXX會在相應(yīng)的testXXX前執(zhí)行,而setUp和tearDown則在每個testXXX方法前都會執(zhí)行。另外beginXXX和endXXX是客戶端代碼,所以在這兩個方法里是無法使用request這樣的服務(wù)端對象的。 對于endXXX方法需要另加說明的是,在Cactus v1.1前(包括v1.1),它的形式是這樣的public void endXXX(HttpURLConnection theConnection),而在Cactus v1.2開始它的形式有兩種可能:
可以看到區(qū)別在于引用的包不同,為什么會這樣的呢?因為在v1.2開始Cactus集成了HttpUnit這個組件。如果你熟悉HttpUnit這個組件,我想應(yīng)該明白為什么要集成HttpUnit。下面我們來看一段代碼開比較一下兩者的區(qū)別: public void endXXX(org.apache.cactus.WebResponse theResponse) { String content = theResponse.getText(); assertEquals(content, "<html><body><h1>Hello world!</h1></body></html>"); } public void endXXX(com.meterware.httpunit.WebResponse theResponse) { WebTable table = theResponse.getTables()[0]; assertEquals("rows", 4, table.getRowCount()); assertEquals("columns", 3, table.getColumnCount()); assertEquals("links", 1, table.getTableCell(0, 2).getLinks().length); } 當(dāng)然,在實際應(yīng)用中你需要根據(jù)不同的需要來選擇不同的endXXX。兩個WebResponse的差別可以參見兩者各自的API Doc,這里就不再多說了。 如何在Cactus里寫測試 . 寫測試代碼 首先,我們給出被測類的代碼,是一個Servlet: public class SampleServlet extends HttpServlet { public void doGet(HttpServletRequest theRequest, HttpServletResponse theResponse) throws IOException { PrintWriter pw = theResponse.getWriter(); theResponse.setContentType("text/html"); pw.print("<html><head/><body>"); pw.print("A GET request"); pw.print("</body></html>"); } public String checkMethod(HttpServletRequest theRequest) { return theRequest.getMethod(); } } Cactus中的測試類框架已經(jīng)在上面給出。下面來看一下例子,例子是從中Cactus自帶的實例中抽取的一部分,如下: public class TestSampleServlet extends ServletTestCase { public void testReadServletOutputStream() throws IOException { SampleServlet servlet = new SampleServlet(); servlet.doGet(request, response); } public void endReadServletOutputStream(WebResponse theResponse) throws IOException { String expected = "<html><head/><body>A GET request</body></html>"; String result = theResponse.getText(); assertEquals(expected, result); } public void beginPostMethod(WebRequest theRequest) { theRequest.addParameter("param", "value", WebRequest.POST_METHOD); } public void testPostMethod() { SampleServlet servlet = new SampleServlet(); assertEquals("POST", servlet.checkMethod(request)); assertEquals("value", request.getParameter("param")); } } 第一個方法testReadServletOutputStream,調(diào)用doGet,相當(dāng)于在客戶端提交請求,然后在Servlet處理后會產(chǎn)生一個回饋,所以,在endReadServletOutputStream方法里,我們通過調(diào)用response的相應(yīng)方法判斷回饋是否符合預(yù)期結(jié)果。 第二個方法testPostMethod,在這之前有一個beginPostMethod,在這個方法里我們以POST方式往request里增加一個表單數(shù)據(jù)param,值為”value”。下面在testPostMethod我們就要驗證表單數(shù)據(jù)是否以POST方式提交到了服務(wù)端的Servlet里,所以,我們看到了兩個assertEquals,分別進(jìn)行了判斷。在這里我們要注意到beginPostMethod方法中的theRequest和testPostMethod中的request的區(qū)別,在前面我們已經(jīng)提到過,beginPostMethod是在客戶端執(zhí)行的,所以它方法內(nèi)的所有操作事實上是模擬頁面操作的,比如上面的設(shè)置表單數(shù)據(jù),而testPostMethod是服務(wù)端執(zhí)行的,其中的request也是服務(wù)端的。 配置cactus.properties和web.xmlcactus.properties
這個屬性是必須的,它指定了web應(yīng)用的訪問地址 例:cactus.contextURL = http://localhost:8080/test
可選,當(dāng)測試類繼承ServletTestCase時用于指定Cactus Servlet Redirector的映射名稱。默認(rèn):ServletRedirector 例:cactus.servletRedirectorName = ServletRedirector
可選,當(dāng)測試類繼承ServletTestCase時用于指定Cactus Jsp Redirector的映射名稱。默認(rèn):ServletRedirector 例:cactus.jspRedirectorName = JspRedirector
可選,當(dāng)測試類繼承ServletTestCase時用于指定Cactus Filter Redirector的映射名稱。默認(rèn):ServletRedirector 例:cactus.filterRedirectorName = FilterRedirector Cactus.properties你可以放置在WEB-INF/classes/下。 web.xml 在web.xml里要為相應(yīng)的測試類指定相應(yīng)的Cactus Redirector。 ServletTestCase對應(yīng)org.apache.cactus.server.ServletTestRedirector JspTestCase對應(yīng)/jspRedirector.jsp FilterTestCase對應(yīng)org.apache.cactus.server.FilterTestRedirector <web-app> <filter> <filter-name>FilterRedirector</filter-name> <filter-class>org.apache.cactus.server.FilterTestRedirector</filter-class> </filter> <filter-mapping> <filter-name>FilterRedirector</filter-name> <url-pattern>/FilterRedirector</url-pattern> </filter-mapping> <servlet> <servlet-name>ServletRedirector</servlet-name> <servlet-class>org.apache.cactus.server.ServletTestRedirector</servlet-class> </servlet> <servlet> <servlet-name>JspRedirector</servlet-name> <jsp-file>/jspRedirector.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>ServletRedirector</servlet-name> <url-pattern>/ServletRedirector</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>JspRedirector</servlet-name> <url-pattern>/JspRedirector</url-pattern> </servlet-mapping> </web-app> 如果你的測試類繼承了JspTestCase則需要將jspRedirector.jsp文件放置到你在web.xml中指定的路徑里。 安裝說明
如下:
junit.jar servlet.jar cactus.jar httpclient.jar commons-logging.jar httpunit.jar,Tidy.jar,xerces.jar(可選,如果你集成了httpunit的話就需要,也就是在endXXX中使用了httpunit)
cactus.jar junit.jar aspectjrt.jar commons-logging.jar
|
posted @ 2006-06-12 09:34 nbt 閱讀(273) | 評論 (0) | 編輯 收藏
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance(); String url="jdbc:oracle:thin:@localhost:1521:orcl"; //orcl為數(shù)據(jù)庫的SID String user="test"; String password="test"; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance(); String url="jdbc:db2://localhost:5000/sample"; //sample為你的數(shù)據(jù)庫名 String user="admin"; String password=""; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance(); String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=mydb"; //mydb為數(shù)據(jù)庫 String user="sa"; String password=""; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("com.sybase.jdbc.SybDriver").newInstance(); String url =" jdbc:sybase:Tds:localhost:5007/myDB";//myDB為你的數(shù)據(jù)庫名 Properties sysProps = System.getProperties(); SysProps.put("user","userid"); SysProps.put("password","user_password"); Connection conn= DriverManager.getConnection(url, SysProps); |
Class.forName("com.informix.jdbc.IfxDriver").newInstance(); String url = "jdbc:informix-sqli://123.45.67.89:1533/myDB:INFORMIXSERVER=myserver; user=testuser;password=testpassword"; //myDB為數(shù)據(jù)庫名 Connection conn= DriverManager.getConnection(url); |
Class.forName("org.gjt.mm.mysql.Driver").newInstance(); String url ="jdbc:mysql://localhost/myDB?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1" //myDB為數(shù)據(jù)庫名 Connection conn= DriverManager.getConnection(url); |
Class.forName("org.postgresql.Driver").newInstance(); String url ="jdbc:postgresql://localhost/myDB" //myDB為數(shù)據(jù)庫名 String user="myuser"; String password="mypassword"; Connection conn= DriverManager.getConnection(url,user,password); |
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver") ; String url="jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ="+application.getRealPath("/Data/ReportDemo.mdb"); Connection conn = DriverManager.getConnection(url,"",""); Statement stmtNew=conn.createStatement() ; |
try{ Class.forName(com.mysql.jdbc.Driver); System.out.println(Success loading Mysql Driver!); }catch(Exception e) { System.out.println(Error loading Mysql Driver!); e.printStackTrace(); } |
jdbc:mysql://localhost/databasename[?pa=va][&pa=va] |
PreparedStatement pstmt3D null; try { ((OraclePreparedStatement)pstmt).setExecuteBatch(30); ... pstmt.executeUpdate(); } |
posted @ 2006-06-12 09:11 nbt 閱讀(330) | 評論 (0) | 編輯 收藏
<?xml version="1.0" encoding="utf-8"?>
<project name="利用工具開發(fā)Hibernate" default="help" basedir=".">
?<!-- ******? 環(huán)境設(shè)置,可以根據(jù)自己的實際配置自行更改 ***** -->
?<!-- ******? http://blog.csdn.net/fasttalk??? ***** -->
?<!-- ******? http://www.aygfsteel.com/asktalk? ***** -->
?<!-- 源文件目錄, 可以通過 項目->屬性->Java構(gòu)建路徑 更改 -->
?<property name="src.dir" value="./src" />
?<!-- 輸出的class文件目錄,可以通過 項目->屬性->Java構(gòu)建路徑 更改 -->
?<property name="class.dir" value="./bin" />
?<!-- 庫文件目錄? -->
?<property name="lib.dir" value="E:/workspace/java/hibernate3" />
?<!-- 定義類路徑 -->
?<path id="project.class.path">
??<fileset dir="${lib.dir}">
???<include name="*.jar"/>
??</fileset>
??<pathelement location="${class.dir}" />
?</path>
?<!-- ************************************************************** -->
?<!-- 使用說明 -->
?<!-- ************************************************************** -->
?<target name="help">
??<echo message="利用工具開發(fā)Hibernate" />
??<echo message="-----------------------------------" />
??<echo message="" />
??<echo message="提供以下任務(wù):" />
??<echo message="" />
??<echo message="generate-hbm???? --> 運行HibernateDoclet,生成 Hibernate 類的映射文件" />
??<echo message="schemaexport???? --> 運行SchemaExport,利用 hbm.xml 文件生成數(shù)據(jù)表" />
??<echo message="" />
?</target>
?<!-- ************************************************************** -->
?<!-- Hbm2Java 任務(wù) 在hibernate3中無法實現(xiàn) -->
?<!-- ************************************************************** -->
?<target name="generate-code" >
??<echo message="運行 Hbm2Java 任務(wù), 利用 hbm.xml 文件生成Java類文件"/>
??<taskdef name="hbm2java"
?????? classname="org.hibernate.tool.instrument.InstrumentTask"
????????? classpathref="project.class.path">
??</taskdef>
??<hbm2java output="${src.dir}">
???<fileset dir="${src.dir}">
????<include name="**/*.hbm.xml"/>
???</fileset>
??</hbm2java>
?</target>
?<!-- ************************************************************** -->
?<!-- HibernateDoclet 任務(wù) -->
?<!-- ************************************************************** -->
?<target name="generate-hbm" >
??<echo message="運行HibernateDoclet,生成 Hibernate 類的映射文件"/>
??<taskdef name="hibernatedoclet"
???classname="xdoclet.modules.hibernate.HibernateDocletTask"
???classpathref="project.class.path">
??</taskdef>
??????? <!--
??????? destdir???????? 輸出目錄;
??????? force,????????? 每次都強(qiáng)行執(zhí)行,覆蓋原有文件;
??????? -->
??<hibernatedoclet destdir="${src.dir}"
???excludedtags="@version,@author,@todo" force="true" encoding="GBK"
???verbose="true">
???<fileset dir="${src.dir}">
????<include name="**/*.java"/>
???</fileset>
???<hibernate version="3.0" xmlencoding="utf-8" />
??</hibernatedoclet>
?</target>
?<!-- ************************************************************** -->
?<!-- SchemaExport 任務(wù) -->
?<!-- ************************************************************** -->
?<target name="schemaexport">
??<echo message="運行SchemaExport,利用 hbm.xml 文件生成數(shù)據(jù)表"/>
??<taskdef name="schemaexport"
???classname="org.hibernate.tool.hbm2ddl.SchemaExportTask"
???classpathref="project.class.path">
??</taskdef>
????? <!--
????? quiet=true?????????????????????? 不要把腳本輸出到stdout;
????? drop=true??????????????????????? 只進(jìn)行drop tables的步驟 ;
????? text=true??????????????????????? 不執(zhí)行在數(shù)據(jù)庫中運行的步驟 ;
????? output=my_schema.ddl???????????? 把輸出的ddl腳本輸出到一個文件 ;
????? config=hibernate.cfg.xml???????? 從XML文件讀入Hibernate配置 ;
????? properties=hibernate.properties? 從文件讀入數(shù)據(jù)庫屬性 ;
????? format=true????????????????????? 把腳本中的SQL語句對齊和美化 ;
????? delimiter=x????????????????????? 為腳本設(shè)置行結(jié)束符
????? -->
??<schemaexport properties="src/hibernate.properties"
? quiet="no"?text="no" drop="no"? output="schema-export.sql" >
???????? <fileset dir="${src.dir}">
???????????? <include name="**/*.hbm.xml"/>?
???????? </fileset>
??</schemaexport>
?</target>
</project>
posted @ 2006-06-12 08:59 nbt 閱讀(475) | 評論 (0) | 編輯 收藏
?? Ajax目前是社區(qū)內(nèi)最熱門的話題之一了,最近在我們的項目中用了大量的Ajax,現(xiàn)在把我們的使用方法在這兒寫出來,希望大家能指教。
因為要用到Ajax就肯定要用到XMLHttpRequest對象,但由于不同的瀏覽器版本,相應(yīng)的生成它的方法也有所不同,所以我們不得不對瀏覽器的版本進(jìn)行判斷,試想,如果我們要在很多地方都要寫那些繁瑣的代碼會覺的很麻煩,代碼的重用也很低,所以我們寫一個Ajax的對象。代碼如下:
//*********************************************************
// 目的:??? AJAX類
// 輸入:??? 無
// 返回:??? 返回XMLHttp對象
// 例子:??? var myConn = new XHConn();
//
//?????????? if (!myConn) alert("XMLHTTP not available. Try a newer/better browser.");
//
//?????????? var fnWhenDone = function (oXML) { alert(oXML.responseText); };
//
//?????????? myConn.connect("mypage.php", "POST", "foo=bar&baz=qux", fnWhenDone);
//
//*********************************************************
function XHConn()
{
? var xmlhttp = false, bComplete = false;
? try
? {
? ?xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
? }
? catch (e)
? {
? ?try
? ?{
? ??xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
? ?}
??? catch (e)
??? {
? ??try
? ??{
? ???xmlhttp = new XMLHttpRequest();
? ??}
? ??catch (e)
? ??{
? ???xmlhttp = false;
? ??}
? ?}
? }
? if (!xmlhttp) return null;
? this.connect = function(sURL, sMethod, sVars, fnDone)
? {
??? if (!xmlhttp) return false;
??? bComplete = false;
??? sVars = (sVars == '') ? Math.random() : sVars + "&" + Math.random();
??? sMethod = sMethod.toUpperCase();
??? try
??? {
????? if (sMethod == "GET")
????? {
??????? xmlhttp.open(sMethod, sURL+"?"+sVars, true);
??????? xmlhttp.setRequestHeader("Content-Type", "text/html;charset=GB2312");
??????? sVars = "";
????? }
????? else
????? {
??????? xmlhttp.open(sMethod, sURL, true);
??????? xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
??????? xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
????? }
????? xmlhttp.onreadystatechange = function()
????? {
??????? if (xmlhttp.readyState == 4 && !bComplete)
??????? {
????????? bComplete = true;
????????? fnDone(xmlhttp);
??????? }
????? };
?????
????? xmlhttp.send(sVars);
??? }
??? catch(z)
??? {
??? ?return false;
??? }
??? return true;
? };
?
? return this;
}
通過這個對象,我們把那些繁瑣的代碼都封裝到里面,這樣大大提高了代碼的重用性,每次要用Ajax時我們只需要在我們的頁面上 new一個XHConn()對象就行了,然后通過調(diào)用它的方法connect(sURL, sMethod, sVars, fnDone)就可以和服務(wù)器進(jìn)行異步交互了。
posted @ 2006-06-09 16:50 nbt 閱讀(291) | 評論 (0) | 編輯 收藏
Java虛擬機(jī)(JVM)是可運行Java代碼的假想計算機(jī)。只要根據(jù)JVM規(guī)格描述將解釋器移植到特定的計算機(jī)上,就能保證經(jīng)過編譯的任何Java代碼能夠在該系統(tǒng)上運行。本文首先簡要介紹從Java文件的編譯到最終執(zhí)行的過程,隨后對JVM規(guī)格描述作一說明。
一.Java源文件的編譯、下載、解釋和執(zhí)行 二.JVM規(guī)格描述 對比分析:如果把Java原程序想象成我們的C++原程序,Java原程序編譯后生成的字節(jié)碼就相當(dāng)于C++原程序編譯后的80x86的機(jī)器碼(二進(jìn)制程序文件),JVM虛擬機(jī)相當(dāng)于80x86計算機(jī)系統(tǒng),Java解釋器相當(dāng)于80x86CPU。在80x86CPU上運行的是機(jī)器碼,在Java解釋器上運行的是Java字節(jié)碼。 |
posted @ 2006-06-09 16:25 nbt 閱讀(225) | 評論 (0) | 編輯 收藏
Java 語言的Calendar(日歷),Date(日期), 和DateFormat(日期格式)組成了Java標(biāo)準(zhǔn)的一個基本但是非常重要的部分. 日期是商業(yè)邏輯計算一個關(guān)鍵的部分. 所有的開發(fā)者都應(yīng)該能夠計算未來的日期, 定制日期的顯示格式, 并將文本數(shù)據(jù)解析成日期對象. 我們寫了兩篇文章, 這是第一篇, 我們將大概的學(xué)習(xí)日期, 日期格式, 日期的解析和日期的計算.
我們將討論下面的類:
1、具體類(和抽象類相對)java.util.Date
2、抽象類java.text.DateFormat 和它的一個具體子類,java.text.SimpleDateFormat
3、抽象類java.util.Calendar 和它的一個具體子類,java.util.GregorianCalendar
具體類可以被實例化, 但是抽象類卻不能. 你首先必須實現(xiàn)抽象類的一個具體子類.
Date 類從Java 開發(fā)包(JDK) 1.0 就開始進(jìn)化, 當(dāng)時它只包含了幾個取得或者設(shè)置一個日期數(shù)據(jù)的各個部分的方法, 比如說月, 日, 和年. 這些方法現(xiàn)在遭到了批評并且已經(jīng)被轉(zhuǎn)移到了Calendar類里去了, 我們將在本文中進(jìn)一步討論它. 這種改進(jìn)旨在更好的處理日期數(shù)據(jù)的國際化格式. 就象在JDK 1.1中一樣, Date 類實際上只是一個包裹類, 它包含的是一個長整型數(shù)據(jù), 表示的是從GMT(格林尼治標(biāo)準(zhǔn)時間)1970年, 1 月 1日00:00:00這一刻之前或者是之后經(jīng)歷的毫秒數(shù).
一、創(chuàng)建一個日期對象
讓我們看一個使用系統(tǒng)的當(dāng)前日期和時間創(chuàng)建一個日期對象并返回一個長整數(shù)的簡單例子. 這個時間通常被稱為Java 虛擬機(jī)(JVM)主機(jī)環(huán)境的系統(tǒng)時間.
//------------------------------------------------------
import java.util.Date;
public class DateExample1
{
public static void main(String[] args)
{
// Get the system date/time
Date date = new Date();
System.out.println(date.getTime());
}
}
//------------------------------------------------------
在星期六, 2001年9月29日, 下午大約是6:50的樣子, 上面的例子在系統(tǒng)輸出設(shè)備上顯示的結(jié)果是 1001803809710. 在這個例子中,值得注意的是我們使用了Date 構(gòu)造函數(shù)創(chuàng)建一個日期對象, 這個構(gòu)造函數(shù)沒有接受任何參數(shù). 而這個構(gòu)造函數(shù)在內(nèi)部使用了System.currentTimeMillis() 方法來從系統(tǒng)獲取日期.
那么, 現(xiàn)在我們已經(jīng)知道了如何獲取從1970年1月1日開始經(jīng)歷的毫秒數(shù)了. 我們?nèi)绾尾拍芤砸环N用戶明白的格式來顯示這個日期呢? 在這里類java.text.SimpleDateFormat 和它的抽象基類 java.text.DateFormat 就派得上用場了.
二、日期數(shù)據(jù)的定制格式
假如我們希望定制日期數(shù)據(jù)的格式, 比方星期六-9月-29日-2001年. 下面的例子展示了如何完成這個工作:
//------------------------------------------------------
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample2
{
public static void main(String[] args)
{
SimpleDateFormat bartDateFormat =
new SimpleDateFormat("EEEE-MMMM-dd-yyyy");
Date date = new Date();
System.out.println(bartDateFormat.format(date));
}
}
//------------------------------------------------------
只要通過向SimpleDateFormat 的構(gòu)造函數(shù)傳遞格式字符串"EEE-MMMM-dd-yyyy", 我們就能夠指明自己想要的格式. 你應(yīng)該可以看見, 格式字符串中的ASCII 字符告訴格式化函數(shù)下面顯示日期數(shù)據(jù)的哪一個部分. EEEE是星期, MMMM是月, dd是日, yyyy是年. 字符的個數(shù)決定了日期是如何格式化的.傳遞"EE-MM-dd-yy"會顯示 Sat-09-29-01. 請察看Sun 公司的Web 站點獲取日期格式化選項的完整的指示.
三、將文本數(shù)據(jù)解析成日期對象
假設(shè)我們有一個文本字符串包含了一個格式化了的日期對象, 而我們希望解析這個字符串并從文本日期數(shù)據(jù)創(chuàng)建一個日期對象. 我們將再次以格式化字符串"MM-dd-yyyy" 調(diào)用SimpleDateFormat類, 但是這一次, 我們使用格式化解析而不是生成一個文本日期數(shù)據(jù). 我們的例子, 顯示在下面, 將解析文本字符串"9-29-2001"并創(chuàng)建一個值為001736000000 的日期對象.
//------------------------------------------------------
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateExample3
{
public static void main(String[] args)
{
// Create a date formatter that can parse dates of
// the form MM-dd-yyyy.
SimpleDateFormat bartDateFormat =
new SimpleDateFormat("MM-dd-yyyy");
// Create a string containing a text date to be parsed.
String dateStringToParse = "9-29-2001";
try {
// Parse the text version of the date.
// We have to perform the parse method in a
// try-catch construct in case dateStringToParse
// does not contain a date in the format we are expecting.
Date date = bartDateFormat.parse(dateStringToParse);
// Now send the parsed date as a long value
// to the system output.
System.out.println(date.getTime());
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
//------------------------------------------------------
四、使用標(biāo)準(zhǔn)的日期格式化過程
既然我們已經(jīng)可以生成和解析定制的日期格式了, 讓我們來看一看如何使用內(nèi)建的格式化過程. 方法 DateFormat.getDateTimeInstance() 讓我們得以用幾種不同的方法獲得標(biāo)準(zhǔn)的日期格式化過程. 在下面的例子中, 我們獲取了四個內(nèi)建的日期格式化過程. 它們包括一個短的, 中等的, 長的, 和完整的日期格式.
//------------------------------------------------------
import java.text.DateFormat;
import java.util.Date;
public class DateExample4
{
public static void main(String[] args)
{
Date date = new Date();
DateFormat shortDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.SHORT,
DateFormat.SHORT);
DateFormat mediumDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.MEDIUM);
DateFormat longDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.LONG,
DateFormat.LONG);
DateFormat fullDateFormat =
DateFormat.getDateTimeInstance(
DateFormat.FULL,
DateFormat.FULL);
System.out.println(shortDateFormat.format(date));
System.out.println(mediumDateFormat.format(date));
System.out.println(longDateFormat.format(date));
System.out.println(fullDateFormat.format(date));
}
}
//------------------------------------------------------
注意我們在對 getDateTimeInstance的每次調(diào)用中都傳遞了兩個值. 第一個參數(shù)是日期風(fēng)格, 而第二個參數(shù)是時間風(fēng)格. 它們都是基本數(shù)據(jù)類型int(整型). 考慮到可讀性, 我們使用了DateFormat 類提供的常量: SHORT, MEDIUM, LONG, 和 FULL. 要知道獲取時間和日期格式化過程的更多的方法和選項, 請看Sun 公司W(wǎng)eb 站點上的解釋.
運行我們的例子程序的時候, 它將向標(biāo)準(zhǔn)輸出設(shè)備輸出下面的內(nèi)容:
9/29/01 8:44 PM
Sep 29, 2001 8:44:45 PM
September 29, 2001 8:44:45 PM EDT
Saturday, September 29, 2001 8:44:45 PM EDT
五、Calendar 類
我們現(xiàn)在已經(jīng)能夠格式化并創(chuàng)建一個日期對象了, 但是我們?nèi)绾尾拍茉O(shè)置和獲取日期數(shù)據(jù)的特定部分呢, 比如說小時, 日, 或者分鐘? 我們又如何在日期的這些部分加上或者減去值呢? 答案是使用Calendar 類. 就如我們前面提到的那樣, Calendar 類中的方法替代了Date 類中被人唾罵的方法.
假設(shè)你想要設(shè)置, 獲取, 和操縱一個日期對象的各個部分, 比方一個月的一天或者是一個星期的一天. 為了演示這個過程, 我們將使用具體的子類 java.util.GregorianCalendar. 考慮下面的例子, 它計算得到下面的第十個星期五是13號.
//------------------------------------------------------
import java.util.GregorianCalendar;
import java.util.Date;
import java.text.DateFormat;
public class DateExample5
{
public static void main(String[] args)
{
DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL);
// Create our Gregorian Calendar.
GregorianCalendar cal = new GregorianCalendar();
// Set the date and time of our calendar
// to the system&s date and time
cal.setTime(new Date());
System.out.println("System Date: " +
dateFormat.format(cal.getTime()));
System.out.println("Befor Setting Day of Week to Friday: " +
dateFormat.format(cal.getTime())); ?
// Set the day of week to FRIDAY
cal.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.FRIDAY);
System.out.println("After Setting Day of Week to Friday: " +
dateFormat.format(cal.getTime()));
int friday13Counter = 0;
while (friday13Counter <= 10)
{
// Go to the next Friday by adding 7 days.
cal.add(GregorianCalendar.DAY_OF_MONTH, 7);
// If the day of month is 13 we have
// another Friday the 13th.
if (cal.get(GregorianCalendar.DAY_OF_MONTH) == 13)
{
friday13Counter++;
System.out.println(dateFormat.format(cal.getTime()));
}
}
}
}
//------------------------------------------------------
在這個例子中我們作了有趣的函數(shù)調(diào)用:
cal.set(GregorianCalendar.DAY_OF_WEEK,
GregorianCalendar.FRIDAY);
和:
cal.add(GregorianCalendar.DAY_OF_MONTH, 7);
set 方法能夠讓我們通過簡單的設(shè)置星期中的哪一天這個域來將我們的時間調(diào)整為星期五. 注意到這里我們使用了常量 DAY_OF_WEEK 和 FRIDAY來增強(qiáng)代碼的可讀性. add 方法讓我們能夠在日期上加上數(shù)值. 潤年的所有復(fù)雜的計算都由這個方法自動處理.
我們這個例子的輸出結(jié)果是:
System Date: Saturday, September 29, 2001
當(dāng)我們將它設(shè)置成星期五以后就成了: Friday, September 28, 2001
Friday, September 13, 2002
Friday, December 13, 2002
Friday, June 13, 2003
Friday, February 13, 2004
Friday, August 13, 2004
Friday, May 13, 2005
Friday, January 13, 2006
Friday, October 13, 2006
Friday, April 13, 2007
Friday, July 13, 2007
Friday, June 13, 2008
六、時間掌握在你的手里
有了這些Date 和Calendar 類的例子, 你應(yīng)該能夠使用 java.util.Date, java.text.SimpleDateFormat, 和 java.util.GregorianCalendar 創(chuàng)建許多方法了.
posted @ 2006-06-09 16:00 nbt 閱讀(474) | 評論 (1) | 編輯 收藏