posts - 35, comments - 0, trackbacks - 0, articles - 0
            BlogJava :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理

          String和StringBuffer的區別,網上資料可以說是數不勝數,但是看到這篇文章,感覺里面做的小例子很有代表性,所以轉一下,并自己做了一點總結。

          在java中有3個類來負責字符的操作。

          1.Character 是進行單個字符操作的,

          2.String 對一串字符進行操作。不可變類。

          3.StringBuffer 也是對一串字符進行操作,但是可變類。

          String:
          是對象不是原始類型.
          為不可變對象,一旦被創建,就不能修改它的值.
          對于已經存在的String對象的修改都是重新創建一個新的對象,然后把新的值保存進去.
          String 是final類,即不能被繼承.

          StringBuffer:
          是一個可變對象,當對他進行修改的時候不會像String那樣重新建立對象
          它只能通過構造函數來建立,
          StringBuffer sb = new StringBuffer();
          note:不能通過付值符號對他進行付值.
          sb = "welcome to here!";//error
          對象被建立以后,在內存中就會分配內存空間,并初始保存一個null.向StringBuffer
          中付值的時候可以通過它的append方法.
          sb.append("hello");

          字符串連接操作中StringBuffer的效率要比String高:

          String str = new String("welcome to ");
          str += "here";
          的處理步驟實際上是通過建立一個StringBuffer,讓侯調用append(),最后
          再將StringBuffer toSting();
          這樣的話String的連接操作就比StringBuffer多出了一些附加操作,當然效率上要打折扣.

          并且由于String 對象是不可變對象,每次操作Sting 都會重新建立新的對象來保存新的值.
          這樣原來的對象就沒用了,就要被垃圾回收.這也是要影響性能的.

          看看以下代碼:
          將26個英文字母重復加了5000次,

            String tempstr = "abcdefghijklmnopqrstuvwxyz";
            int times = 5000;
            long lstart1 = System.currentTimeMillis();
            String str = "";
            for (int i = 0; i < times; i++) {
            str += tempstr;
            }
            long lend1 = System.currentTimeMillis();
            long time = (lend1 - lstart1);
            System.out.println(time);
          可惜我的計算機不是超級計算機,得到的結果每次不一定一樣一般為 46687左右。
          也就是46秒。
          我們再看看以下代碼

            String tempstr = "abcdefghijklmnopqrstuvwxyz";
            int times = 5000;
            long lstart2 = System.currentTimeMillis();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < times; i++) {
            sb.append(tempstr);
            }
            long lend2 = System.currentTimeMillis();
            long time2 = (lend2 - lstart2);
            System.out.println(time2);
          得到的結果為 16 有時還是 0
          所以結論很明顯,StringBuffer 的速度幾乎是String 上萬倍。當然這個數據不是很準確。因為循環的次數在100000次的時候,差異更大。不信你試試。

          根據上面所說:

          str += "here";
          的處理步驟實際上是通過建立一個StringBuffer,讓侯調用append(),最后
          再將StringBuffer toSting();

          所以str += "here";可以等同于

          StringBuffer sb = new StringBuffer(str);

          sb.append("here");

          str = sb.toString();

          所以上面直接利用"+"來連接String的代碼可以基本等同于以下代碼

            String tempstr = "abcdefghijklmnopqrstuvwxyz";
            int times = 5000;
            long lstart2 = System.currentTimeMillis();
            String str = "";
            for (int i = 0; i < times; i++) {
            StringBuffer sb = new StringBuffer(str);
            sb.append(tempstr);
            str = sb.toString();
            }
            long lend2 = System.currentTimeMillis();
            long time2 = (lend2 - lstart2);
            System.out.println(time2);
          平均執行時間為46922左右,也就是46秒。

          本文來自CSDN博客,轉載請標明出處:http://blog.csdn.net/yirentianran/archive/2008/09/03/2871417.aspx

          StringBuffer維護了一個大小固定的字符串緩沖區,當字符串長度超過StringBuffer大小時會自動增加,主要使用Insert和append方法,對于運行期要進行字符串的組裝操作推薦使用,

            StringBuilder: jdk5以后有個和StringBuffer等價的StringBuider,區別在于StringBuffer是線程安全的,StringBuilder是單線程的,不提供同步,理論上效率更高。

            String是系統內置類型,而且是final的,定義一個字符串會產生一個實例和一個對該實例地址的引用。

            如果在編譯期間定義的字符串,例如 :

            String a = "name";
            a += "is";
            a += "good";

            盡管這種方法是不被推薦的,但在編譯期,編譯器會對該代碼進行優化,所以還是可以理解為:String a = "name is good";而如果在此時采用StringBuffer,反而會推遲到運行期才會被處理,相比之下,反而會比StringBuffer效率更高,靈活運 用。
          String 字符串常量
          StringBuffer 字符串變量(線程安全)
          StringBuilder 字符串變量(非線程安全)
           簡要的說, String 類型和 StringBuffer 類型的主要性能區別其實在于 String 是不可變的對象, 因此在每次對 String 類型進行改變的時候其實都等同于生成了一個新的 String 對象,然后將指針指向新的 String 對象,所以經常改變內容的字符串最好不要用 String ,因為每次生成對象都會對系統性能產生影響,特別當內存中無引用對象多了以后, JVM 的 GC 就會開始工作,那速度是一定會相當慢的。
           而如果是使用 StringBuffer 類則結果就不一樣了,每次結果都會對 StringBuffer 對象本身進行操作,而不是生成新的對象,再改變對象引用。所以在一般情況下我們推薦使用 StringBuffer ,特別是字符串對象經常改變的情況下。而在某些特別情況下, String 對象的字符串拼接其實是被 JVM 解釋成了 StringBuffer 對象的拼接,所以這些時候 String 對象的速度并不會比 StringBuffer 對象慢,而特別是以下的字符串對象生成中, String 效率是遠要比 StringBuffer 快的:
           String S1 = “This is only a” + “ simple” + “ test”;
           StringBuffer Sb = new StringBuilder(“This is only a”).append(“ simple”).append(“ test”);
           你會很驚訝的發現,生成 String S1 對象的速度簡直太快了,而這個時候 StringBuffer 居然速度上根本一點都不占優勢。其實這是 JVM 的一個把戲,在 JVM 眼里,這個
           String S1 = “This is only a” + “ simple” + “test”; 其實就是:
           String S1 = “This is only a simple test”; 所以當然不需要太多的時間了。但大家這里要注意的是,如果你的字符串是來自另外的 String 對象的話,速度就沒那么快了,譬如:
          String S2 = “This is only a”;
          String S3 = “ simple”;
          String S4 = “ test”;
          String S1 = S2 +S3 + S4;
          這時候 JVM 會規規矩矩的按照原來的方式去做

          在大部分情況下 StringBuffer > String
          StringBuffer
          Java.lang.StringBuffer線程安全的可變字符序列。一個類似于 String 的字符串緩沖區,但不能修改。雖然在任意時間點上它都包含某種特定的字符序列,但通過某些方法調用可以改變該序列的長度和內容。
          可將字符串緩沖區安全地用于多個線程。可以在必要時對這些方法進行同步,因此任意特定實例上的所有操作就好像是以串行順序發生的,該順序與所涉及的每個線程進行的方法調用順序一致。
          StringBuffer 上的主要操作是 append 和 insert 方法,可重載這些方法,以接受任意類型的數據。每個方法都能有效地將給定的數據轉換成字符串,然后將該字符串的字符追加或插入到字符串緩沖區中。 append 方法始終將這些字符添加到緩沖區的末端;而 insert 方法則在指定的點添加字符。
          例如,如果 z 引用一個當前內容是“start”的字符串緩沖區對象,則此方法調用 z.append("le") 會使字符串緩沖區包含“startle”,而 z.insert(4, "le") 將更改字符串緩沖區,使之包含“starlet”。
          在大部分情況下 StringBuilder > StringBuffer
          java.lang.StringBuilde
          java.lang.StringBuilder 一個可變的字符序列是5.0新增的。此類提供一個與 StringBuffer 兼容的 API,但不保證同步。該類被設計用作 StringBuffer 的一個簡易替換,用在字符串緩沖區被單個線程使用的時候(這種情況很普遍)。如果可能,建議優先采用該類,因為在大多數實現中,它比 StringBuffer 要快。兩者的方法基本相同。
          通過非官方試驗測試,StringBuilder和StringBuffer的測試總結如下:

          1. 為了獲得更好的性能,在構造 StirngBuffer 或 StirngBuilder 時應盡可能指定它的容量。當然,如果你操作的字符串長度不超過 16 個字符就不用了。

          2. 相同情況下使用 StirngBuilder 相比使用 StringBuffer 僅能獲得 10%~15% 左右的性能提升,但卻要冒多線程不安全的風險。而在現實的模塊化編程中,負責某一模塊的程序員不一定能清晰地判斷該模塊是否會放入多線程的環境中運行,因 此:除非你能確定你的系統的瓶頸是在 StringBuffer 上,并且確定你的模塊不會運行在多線程模式下,否則還是用 StringBuffer 吧 J

          3. 用好現有的類比引入新的類更重要。很多程序員在使用 StringBuffer 時是不指定其容量的(至少我見到的情況是這樣),如果這樣的習慣帶入 StringBuilder 的使用中,你將只能獲得 10 %左右的性能提升(不要忘了,你可要冒多線程的風險噢);但如果你使用指定容量的 StringBuffer ,你將馬上獲得 45% 左右的性能提升,甚至比不使用指定容量的 StirngBuilder 都快 30% 左右。

          posted @ 2012-06-05 17:04 timelyxyz 閱讀(121) | 評論 (0)編輯 收藏

          在原先的json數據中再新增數據

          Object.append(ajaxData,{arrAttach : xxx ... // 新的數據});

           

          擴展原先已經定義好的方法

          callFun.extend("bind",function(){...// 新的操作}) 

           

          這樣可以用于多個并列操作,但又存在微小差異的ajax請求的發送

                  var ajaxData = {
                          "type" : $sendObjDeal()
                      },callFun = function(json){
                          msgArea.appendHTML(json.html,"top");
                          send.fireEvent("afterCheckSubmit", send);
                          clearMsgInput();
                      },ajaxUrl;

                  if (flag === "0"){
                      ajaxUrl = ...;
                      Object.append(ajaxData,{content : eassyCont.val()});
                      callFun.extend("bind",function(){bindAfterSend(msgArea.getElement(".jsForIbtn"),1)})        
                  }else if (flag === "1") {
                      ajaxUrl = ContentItem.poll;
                      Object.append(ajaxData,{pollItemContentTexts:JSON.encode($$(".jsForPollOption").val()), 

                                              pollContentText : voteQuestion.val()

                                             });
                      callFun.extend("bind",function(){bindAfterSend(msgArea.getElement(".jsForIbtn"),4)})
                  } else if (flag === "2") {
                      ajaxUrl = ContentItem.assignment;
                      ...// 獨立的操作
                     
                  }
                  // 統一發送ajax請求
                  new AjaxPost(this,{
                      url : ajaxUrl,
                      data: ajaxData,
                      callback : function(json){
                          callFun(json);
                          callFun.bind()
                      }
                  }).send()

           

          posted @ 2012-06-04 14:22 timelyxyz 閱讀(111) | 評論 (0)編輯 收藏

              int result = session
                          .createSQLQuery(
                                  "update member set blockconnectionrequests = :blockval, onlyshowprofiletomyconnections = :onlyval  where username in ('icScholar', 'smsAdminer')")
                          .setParameter("blockval", false).setParameter("onlyval", false)
                          .executeUpdate();

          posted @ 2012-05-31 17:43 timelyxyz 閱讀(166) | 評論 (0)編輯 收藏

          <SCRIPT LANGUAGE="JavaScript">
          var myDate = new Date();
              myDate.getYear();       //獲取當前年份(2位)【注意:FireFox 的getYear返回的是“當前年份-1900”的值(傳說以前一直這樣處理),IE卻當Year>=2000】
              myDate.getFullYear();   //獲取完整的年份(4位,1970-????)
              myDate.getMonth();      //獲取當前月份(0-11,0代表1月)
              myDate.getDate();       //獲取當前日(1-31)
              myDate.getDay();        //獲取當前星期X(0-6,0代表星期天)
              myDate.getTime();       //獲取當前時間(從1970.1.1開始的毫秒數)
              myDate.getHours();      //獲取當前小時數(0-23)
              myDate.getMinutes();    //獲取當前分鐘數(0-59)
              myDate.getSeconds();    //獲取當前秒數(0-59)
              myDate.getMilliseconds();   //獲取當前毫秒數(0-999)
              myDate.toLocaleDateString();    //獲取當前日期
              var mytime=myDate.toLocaleTimeString();    //獲取當前時間
              myDate.toLocaleString( );       //獲取日期與時間

          if (mytime<"23:30:00")
          {
          alert(mytime);
          }
          </SCRIPT>

          posted @ 2012-05-21 23:29 timelyxyz 閱讀(109) | 評論 (0)編輯 收藏

          今天鏈接mysql的時候報了一個錯“error 2013:Lost connection to MySQL server during query”,進不去,應該是連接信息有誤,可是我輸入的賬號用戶名全部是正確的,原因不知道。

          后來重新啟動了mysql的服務,莫名的又能連接上了。

           

          網上查詢了下,原因大致是這樣子的:

          在向NFS上備份的時候,數據的流向是這樣的:MySQL Server端從數據文件中檢索出數據,然后分批將數據返回給mysqldump客戶端,然后mysqldump將數據寫入到NFS上。一般地,向NFS 上寫入數據的速度較之Server端檢索發送數據的速度要慢得多,這就會導致mysqldump無法及時的接受Server端發送過來的數據,Server端的數據就會積壓在內存中等待發送,這個等待不是無限期的,當Server的等待時間超過net_write_timeout(默認是60秒)時它就失去了耐心,mysqldump的連接會被斷開,同時拋出錯誤Got error: 2013: Lost connection。
           

           

          http://hi.baidu.com/ldtrain/blog/item/1c7f87be76c9020119d81f18.html
           

          posted @ 2012-05-21 23:24 timelyxyz 閱讀(5269) | 評論 (0)編輯 收藏

          ActionContext(Action上下文) 

          ActionContext介紹

          通過上面用戶注冊例子的學習,我們知道Xwork與Web無關性,我們的Action不用去依賴于任何Web容器,不用和那些JavaServlet復雜的請求(Request)、響應(Response)關聯在一起。對請求(Request)的參數(Param),可以使用攔截器框架自動調用一些get()和set()方法設置到對應的Action的字段中。但是,僅僅取得請求參數的值就能完全滿足我們的功能要求嗎?不,在Web應用程序開發中,除了將請求參數自動設置到Action的字段中,我們往往也需要在Action里直接獲取請求(Request)或會話(Session)的一些信息,甚至需要直接對JavaServlet Http的請求(HttpServletRequest)、響應(HttpServletResponse)操作。

          帶著這些問題,我們來看看下面的一個功能需求:

          我們需要在Action中取得request請求參數“username”的值:

          ActionContext context = ActionContext.getContext();

          Map params = context.getParameters();

          String username = (String) params.get(“username”);

          為了實現這個功能,我們用了三個步驟:

          1、取得我們當前的ActionContext對象context,ActionContext是個什么冬冬?

          2、從context對象里獲取我們所有的請求參數,取得的卻是一個Map對象params?

          3、居然可以從我們的Map對象params里獲取我們需要的request請求參數“username”的值。

          ActionContext(com.opensymphony.xwork.ActionContext)是Action執行時的上下文,上下文可以看作是一個容器(其實我們這里的容器就是一個Map而已),它存放放的是Action在執行時需要用到的對象,比如:在使用WebWork時,我們的上下文放有請求的參數(Parameter)、會話(Session)、Servlet上下文(ServletContext)、本地化(Locale)信息等。

          在每次執行Action之前都會創建新的ActionContext,ActionContext是線程安全的,也就是說在同一個線程里ActionContext里的屬性是唯一的,這樣我的Action就可以在多線程中使用。

          我們可以通過ActionContext的靜態方法:ActionContext.getContext()來取得當前的ActionContext對象,我們看看這段代碼:

          public static ActionContext getContext() {

          ActionContext context = (ActionContext) actionContext.get();


          if (context == null) {

          OgnlValueStack vs = new OgnlValueStack();

          context = new ActionContext(vs.getContext());

          setContext(context);

          }


          return context;

          }

          一般情況,我們的ActionContext都是通過:ActionContext context = (ActionContext) actionContext.get();來獲取的。我們再來看看這里的actionContext對象的創建:static ThreadLocal actionContext = new ActionContextThreadLocal();,ActionContextThreadLocal是實現ThreadLocal的一個內部類。ThreadLocal可以命名為“線程局部變量”,它為每一個使用該變量的線程都提供一個變量值的副本,使每一個線程都可以獨立地改變自己的副本,而不會和其它線程的副本沖突。這樣,我們ActionContext里的屬性只會在對應的當前請求線程中可見,從而保證它是線程安全的。

          下面我們看看怎么通過ActionContext取得我們的HttpSession:

          Map session = ActionContext.getContext().getSession();

          原來我們取得的session卻是Map類型的對象,這是為什么?原來,我們的WebWork框架將與Web相關的很多對象重新進行了包裝,比如這里就將HttpSession對象重新包裝成了一個Map對象,供我們的Action使用,而不用直接和底層的HttpSession打交道。也正是框架的包裝,讓我們的Actoion可以完全的和Web層解藕。

          如果我們的Action需要直接與JavaServlet的HttpSession、HttpServletRequest等一些對象進行操作,我們又該如何處理?請看下面的ServletActionContext。

          ServletActionContext

          ServletActionContext(com.opensymphony.webwork. ServletActionContext),這個類直接繼承了我們上面介紹的ActionContext,它提供了直接與JavaServlet相關對象訪問的功能,它可以取得的對象有:

          1、javax.servlet.http.HttpServletRequest:HTTPservlet請求對象

          2、javax.servlet.http.HttpServletResponse;:HTTPservlet相應對象

          3、javax.servlet.ServletContext:Servlet 上下文信息

          4、javax.servlet.ServletConfig:Servlet配置對象

          5、javax.servlet.jsp.PageContext:Http頁面上下文

          ServletActionContext除了提供了上面這些對象訪問,它當然也繼承了它父類ActionContex的很多功能,比如:對OgnlValueStack、Action名字等的訪問。

          下面我們看看幾個簡單的例子,讓我們了解如何從ServletActionContext里取得JavaServlet的相關對象:

          1、取得HttpServletRequest對象:

          HttpServletRequest request = ServletActionContext. getRequest();

          2、取得HttpSession對象:

          HttpSession session = ServletActionContext. getRequest().getSession();

          ServletActionContext和ActionContext有著一些重復的功能,在我們的Action中,該如何去抉擇呢?我們遵循的原則是:如果ActionContext能夠實現我們的功能,那最好就不要使用ServletActionContext,讓我們的Action盡量不要直接去訪問JavaServlet的相關對象。在使用ActionContext時有一點要注意:不要在Action的構造函數里使用ActionContext.getContext(),因為這個時候ActionContext里的一些值也許沒有設置,這時通過ActionContext取得的值也許是null。

           

          原文鏈接 http://space.itpub.net/14734416/viewspace-485659

           

          posted @ 2012-05-19 20:20 timelyxyz 閱讀(1099) | 評論 (0)編輯 收藏

            參考文獻:http://www.playframework.org/documentation/1.2.3/controllers

            當參數名和HTTP請求中的參數名(即界面中的name)相同時,后臺Controller可以直接獲取該變量的值。變量分兩大類:

            1. Simple types

            所有的基本數據類型和一些常用的Java類型可以被自動綁定

            int, long, boolean, char, byte, float, double, Integer, Long, Boolean, Char, Byte, Float, Double, String

            以上數據類型可以被自動綁定,當參數為丟失時,默認會將變量的值賦為:null或0。

            2. Date

            當時間對象以一下格式展現時,可以被自動綁定到后臺:

          • yyyy-MM-dd'T'hh:mm:ss'Z' //ISO8601 + timezone
          • yyyy-MM-dd'T'hh:mm:ss" //ISO8601
          • yyyy-MM-dd
          • yyyyMMdd'T'hhmmss
          • yyyyMMddhhmmss
          • dd'/'MM'/'yyyy
          • dd-MM-yyyy
          • ddMMyyyy
          • MMddyy
          • MM-dd-yy
          • MM'/'dd'/'yy

            引用@As 注釋,可以直接定義時間格式。for example:

            archives?from=21/12/1980

            public static void articlesSince(@As("dd/MM/yyyy") Date from) {

              List<Article> articles = Article.findBy("date >= ?", from);

              render(articles);

            }

            另外也可以根據語言來格式化時間。See as follows:

            public static void articlesSince(@As(lang={"fr,de","*"}, value={"dd-MM-yyyy","MM-dd-yyyy"}) Date from) {

              List<Article> articles = Article.findBy("date >= ?", from);

              render(articles);

            }

            在這個例子中,我們將French和German語言對應的時間格式設置為dd-MM-yyyy和MM-dd-yyyy。需要注意的是,語言必須用都好分隔開,value和lang的個數要匹配。

            如果@As注釋沒寫的話,時間會按照默認格式來轉化。

            3.Calendar

            Calendar跟Date類似,它使用的注釋是@Bind。

            4.Arrays or collections of supported types

            所有被支持的類型都可以作以Array的形式被綁定獲取到。for example:

            public static void show(Long[] id){...}

            public static void show(List<Long> id){...}

            public static void show(Set<Long> id){...}

            Play也支持像是Map<String, String>這樣子的特殊例子:

            public static void show(Map<String, String> client){...}

            在上面的這個例子中,傳入的語句如下:

            ?client.name=John&client.phone=111-1111&client.phone=222-222

            此時后臺獲取到一個map元素,第一個元素的key為name,值為John,第二個元素的key為phone,值為111-1111,222-2222.

            5.POJO object binding

            play同樣支持自動綁定任何model,只要該對象遵守相同的命名規則。for example:

            public static void create(Client client){

              client.save();

              show(client);

            }

            在頁面端,一個保存client的action需要規定如下:

            ?client.name=Zenexity&client.email=contact&zenexity.fr

            play可以創建一個Client對象,并且從HTTP請求中讀取相關的屬性值賦到Client對象上。一些不能解決/讀取的參數會被play安全的忽略掉,類型不匹配也會被自動忽略。

            參數綁定也可以遞歸的進行,只要你列出完整的參數列表:

            ?client.name=Zenexity

            &client.address.street=64+rue+taitbout

            &client.address.zip=75009

            &client.address.country=France

            有時候為了更新對象列表,會使用一個存放了對象id的數組。For example,假設我們已經有了一個Customer的對象列表,聲明List Customer customers,為了更新Customers,我們需要提供如下一串String:

            ?client.customers[0].id=123

            &client.customers[1].id=456

            &client.customers[2].id=789

             6.JPA object binding

             7.File

          File upload is easy with Play. Use a multipart/form-data encoded request to post files to the server, and then use the java.io.File type to retrieve the file object:

          public static void create(String comment, File attachment) { String s3Key = S3.post(attachment); Document doc = new Document(comment, s3Key); doc.save(); show(doc.id); } 

          The created file has the same name as the original file. It’s stored in a temporary directory and deleted at the end of the request. So you have to copy it in a safe directory or it will be lost.

          The uploaded file’s MIME type should normally be specified by the HTTP request’s Content-type header. However, when uploading files from a web browser, this might not happen for uncommon types. In this case, you can map the file name’s extension to a MIME type, using the play.libs.MimeTypes class.

          String mimeType = MimeTypes.getContentType(attachment.getName()); 

          The play.libs.MimeTypes class looks up the MIME type for the given file name’s extension in the file $PLAY_HOME/framework/src/play/libs/mime-types.properties

          You can also add your own types using the Custom MIME types configuration.

           

          ps:還沒寫完,以后再繼續。


          posted @ 2012-05-18 08:54 timelyxyz 閱讀(181) | 評論 (0)編輯 收藏

          本課題參考自《Spring in action》。并非應用系統中發生的所有事情都是由用戶的動作引起的。有時候,系統自己也需要發起一些動作。例如,集抄系統每天早上六點把抄表數據傳送 給營銷系統。我們有兩種選擇:或者是每天由用戶手動出發任務,或者讓應用系統中按照預定的計劃自動執行任務。
          在Spring中有兩種流行配置:Java的Timer類和OpenSymphony的Quartz來執行調度任務。下面以給商丘做的接口集抄900到中間庫的日凍結數據傳輸為例:
          1. Java Timer調度器
          首先定義一個定時器任務,繼承java.util.TimerTask類實現run方法
          import java.util.TimerTask;
          import xj.service.IJdbc1Service;
          import xj.service.IJdbc2Service;
          public class DayDataTimerTask extends TimerTask{
          private IJdbc2Service jdbc2Service=null;
          private IJdbc1Service jdbc1Service=null;
          public void run(){
          SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          System.out.println("日凍結轉接任務開始時間:"+df.format(Calendar.getInstance().getTime()));
          System.out.println("日凍結轉接任務結束時間:"+df.format(Calendar.getInstance().getTime()));
          }

          //通過set方法獲取service服務,如果沒有該方法,則為null
          public void setJdbc2Service(IJdbc2Service jdbc2Service) {
          this.jdbc2Service = jdbc2Service;
          }

          public void setJdbc1Service(IJdbc1Service jdbc1Service) {
          this.jdbc1Service = jdbc1Service;
          }
          }
          Run()方法定義了當任務運行時該做什么。jdbc1Service,jdbc2Service通過依賴注入的方式提供給DayDataTimerTask。如果該任務中沒有service服務的set方法,則取到的該service服務為null。
          其次,在Spring配置文件中聲明 dayDataTimerTask:
          <!-- 聲明定時器任務 -->
          <bean id="dayDataTimerJob" class="xj.action.DayDataTimerTask">
          <property name="jdbc1Service">
          <ref bean="jdbc1Service"/>
          </property>
          <property name="jdbc2Service">
          <ref bean="jdbc2Service"/>
          </property>
          </bean>
          該聲明將DayDataTimerTask放到應用上下文中,并在jdbc1Service、jdbc2Service屬性中分別裝配jdbc1Service、jdbc2Service。在調度它之前,它不會做任何事情。
          <!-- 調度定時器任務 -->
          <bean id="scheduledDayDataTimerJob" class="org.springframework.scheduling.timer.ScheduledTimerTask">
          <property name="timerTask">
          <ref bean="dayDataTimerJob"/>
          </property>
          <property name="delay">
          <value>3000</value>
          </property>
          <property name="period">
          <value>864000000</value>
          </property>
          </bean>
          屬性timerTask告訴ScheduledTimerTask運行哪個TimerTask。再次,該屬性裝配了指向 scheduledDayDataTimerJob的一個引用,它就是DayDataTimerTask。屬性period告訴 ScheduledTimerTask以怎樣的頻度調用TimerTask的run()方法。該屬性以毫秒作為單位,它被設置為864000000,指定 這個任務應該每24小時運行一次。屬性delay允許你指定當任務第一次運行之前應該等待多久。在此指定DayDataTimerTask的第一次運行相 對于應用程序的啟動時間延遲3秒鐘。
          <!-- 啟動定時器 -->
          <bean class="org.springframework.scheduling.timer.TimerFactoryBean">
          <property name="scheduledTimerTasks">
          <list>
          <ref bean="scheduledDayDataTimerJob"/>
          </list>
          </property>
          </bean>
          Spring的TimerFactoryBean負責啟動定時任務。屬性scheduledTimerTasks要求一個需要啟動的定時器任務的列表。在此只包含一個指向scheduledDayDataTimerJob的引用。
              Java Timer只能指定任務執行的頻度,但無法精確指定它何時運行,這是它的一個局限性。要想精確指定任務的啟動時間,就需要使用Quartz[kw?:ts]調度器。
          2.Quartz調度器
          Quartz調度器不僅可以定義每隔多少毫秒執行一個工作,還允許你調度一個工作在某個特定的時間或日期執行。
          首先創建一個工作,繼承QuartzJobBean類實現executeInternal方法
          import org.quartz.JobExecutionContext;
          import org.quartz.JobExecutionException;
          import org.springframework.dao.DataIntegrityViolationException;
          import org.springframework.scheduling.quartz.QuartzJobBean;

          import xj.service.IJdbc1Service;
          import xj.service.IJdbc2Service;
          public class DayDataQuartzTask extends QuartzJobBean{
          private IJdbc2Service jdbc2Service=null;
          private IJdbc1Service jdbc1Service=null;
          protected void executeInternal(JobExecutionContext context) throws JobExecutionException{
          SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
          System.out.println("日凍結轉接任務開始時間:"+df.format(Calendar.getInstance().getTime()));
          System.out.println("日凍結轉接任務結束時間:"+df.format(Calendar.getInstance().getTime()));
          }

          //通過set方法獲取service服務,如果沒有該方法,則為null
          public void setJdbc2Service(IJdbc2Service jdbc2Service) {
          this.jdbc2Service = jdbc2Service;
          }

          public void setJdbc1Service(IJdbc1Service jdbc1Service) {
          this.jdbc1Service = jdbc1Service;
          }

          }

          在Spring配置文件中按照以下方式聲明這個工作:
          <!-- 定時啟動任務 Quartz-->
          <!—聲明工作-->
          <bean id="dayDataJob" class="org.springframework.scheduling.quartz.JobDetailBean">
          <property name="jobClass">
          <value>xj.action.DayDataQuartzTask</value>
          </property>
          <property name="jobDataAsMap">
          <map>
          <entry key="jdbc1Service">
          <ref bean="jdbc1Service"/>
          </entry>
          <entry key="jdbc2Service">
          <ref bean="jdbc2Service"/>
          </entry>
          </map>
          </property>
          </bean>
          Quartz的org.quartz.Trigger類描述了何時及以怎樣的頻度運行一個Quartz工作。Spring提供了兩個觸發器 SimpleTriggerBean和CronTriggerBean。SimpleTriggerBean與scheduledTimerTasks類 似。指定工作的執行頻度,模仿scheduledTimerTasks配置。
          <!-- 調度Simple工作 -->
          <bean id="simpleDayDataJobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
          <property name="jobDetail">
          <ref bean="dayDataJob"/>
          </property>
          <property name="startDelay">
          <value>1000</value>
          </property>
          <property name="repeatInterval">
          <value>86400000</value>
          </property>
          </bean>
          <!—調度cron工作-->
          <bean id="dayDataJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
          <property name="jobDetail">
          <ref bean="dayDataJob"/>
          </property>
          <property name="cronExpression">
          <value>0 30 2 * * ?</value>
          </property>
          </bean>
          一個cron表達式有6個或7個由空格分隔的時間元素。從左至右,這些元素的定義如下:1、秒(0-59);2、分(0-59);3、小時 (0-23);4、月份中的日期(1-31);5、月份(1-12或JAN-DEC);6、星期中的日期(1-7或SUN-SAT);7、年份 (1970-2099)。
          每一個元素都可以顯式地規定一個值(如6),一個區間(如9-12),一個列表(如9,11,13)或一個通配符(如*)。“月份中的日期”和“星期中的日期”這兩個元素互斥,應該通過設置一個問號(?)來表明你不想設置的那個字段。

          corn表達式API具體見

          http://www.quartz-scheduler.org/documentation/quartz-1.x/tutorials/crontrigger

          我們在此定義該任務在每天凌晨兩點半開始啟動。
          <!—啟動工作-->
          <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
          <property name="triggers">
          <list>
          <ref bean="simpleDayDataJobTrigger"/>
          <ref bean="dayDataJobTrigger"/>
          </list>
          </property>
          </bean>
          屬性triggers接受一組觸發器,在此只裝配包含simpleDayDataJobTrigger bea和dayDataJobTrigger bean的一個引用列表。

          posted @ 2012-05-17 23:59 timelyxyz 閱讀(132) | 評論 (0)編輯 收藏

          題目:吸血鬼數字是指位數為偶數的數字,可以由一對數字相乘而得到,而對數字各包含乘積的一半數的數字,其中從最初的數字中選取的數字可以任意排序。以兩個0結尾的數字是不允許的,列如:
          1260=21*60;
          1827=21*87;
          2187=27*81;
          請寫出一個程序,找出所有的4位吸血鬼數字。
          解:反過來想,
          不從考慮某個數(1001到9999)是不是吸血鬼數,而是遍歷2位數相乘,看是否符合某種規則,符合的話,他們的積就是吸血鬼數

          package test1;

          import java.util.Arrays;
          import java.util.Scanner;

          /**
           * 吸血鬼數字:位數為偶數,可以由一對數字相乘而得,這對數字分別是吸血鬼數字的一半位數的,順序不規定<br>
           * 1260=12*60, 1827=21*87
           */
          public class Vampire {

              public static void main(String[] args) {
                  System.out.printf("Please enter the length of the num : ");
                  Scanner s = new Scanner(System.in);
                  int x = s.nextInt();
                  calVampire(x);
              }

              public static void calVampire(int n) {
                  if (n % 2 != 0)
                      return;
                  else {
                      int subLength = n / 2;
                      int total = 0;
                      int min = (int) Math.pow(10, subLength - 1);
                      int max = (int) Math.pow(10, subLength) - 1;
                      for (int p = min; p <= max; p++) {
                          for (int k = p + 1; k <= max; k++) {
                              int val = p * k;
                              if (val > 9999 || val < 1000)
                                  continue;
                              String[] s1 = String.valueOf(val).split("");
                              String[] s2 = (String.valueOf(p) + String.valueOf(k))
                                      .split("");
                              Arrays.sort(s1);
                              Arrays.sort(s2);
                              if (Arrays.equals(s1, s2)) {
                                  total++;
                                  System.out.println(p + " * " + k + "=" + val);
                              }
                          }
                      }
                      System.out.println("Total num is : " + total);
                  }
              }

          }

          posted @ 2012-05-15 09:53 timelyxyz 閱讀(138) | 評論 (0)編輯 收藏

          一、find(String queryString);

          示例:this.getHibernateTemplate().find(”from bean.User”);

          返回所有User對象

          二、find(String queryString , Object value);

          示例:this.getHibernateTemplate().find(”from bean.User u where u.name=?”, “test”);

          或模糊查詢:this.getHibernateTemplate().find(”from bean.User u where u.name like ?”, “%test%”);

          返回name屬性值為test的對象(模糊查詢,返回name屬性值包含test的對象)

          三、find(String queryString, Object[] values);

          示例:String hql= “from bean.User u where u.name=? and u.password=?”

          this.getHibernateTemplate().find(hql, new String[]{”test”, “123″});

          返回用戶名為test并且密碼為123的所有User對象

          ---------------------------------

          四、findByExample(Object exampleEntity)

          示例:

          User u=new User();

          u.setPassword(”123″);//必須符合的條件但是這兩個條件時并列的(象當于sql中的and)

          u.setName(”bb”);

          list=this.getHibernateTemplate().findByExample(u,start,max);

          返回:用戶名為bb密碼為123的對象

          五、findByExample(Object exampleEntity, int firstResult, int maxResults)

          示例:

          User u=new User();

          u.setPassword(”123″);//必須符合的條件但是這兩個條件時并列的(象當于sql中的and)

          u.setName(”bb”);

          list=this.getHibernateTemplate().findByExample(u,start,max);

          返回:滿足用戶名為bb密碼為123,自start起共max個User對象。(對象從0開始計數)

          —————————————————

          六、findByNamedParam(String queryString , String paramName , Object value)

          使用以下語句查詢:

          String queryString = “select count(*) from bean.User u where u.name=:myName”;

          String paramName= “myName”;

          String value= “xiyue”;

          this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);

          System.out.println(list.get(0));

          返回name為xiyue的User對象的條數

          七、findByNamedParam(String queryString , String[] paramName , Object[] value)

          示例:

          String queryString = “select count(*) from bean.User u where u.name=:myName and u.password=:myPassword”;

          String[] paramName= new String[]{”myName”, “myPassword”};

          String[] value= new String[]{”xiyue”, “123″};

          this.getHibernateTemplate().findByNamedParam(queryString, paramName, value);

          返回用戶名為xiyue密碼為123的User對象

          八、findByNamedQuery(String queryName)

          示例:

          1、首先需要在User.hbm.xml中定義命名查詢

          <hibernate-mapping>

          <class>……</class>

          <query name=”queryAllUser”><!–此查詢被調用的名字–>

          <![CDATA[

          from bean.User

          ]]>

          </query>

          </hibernate-mapping>

          2、如下使用查詢:

          this.getHibernateTemplate().findByNamedQuery(”queryAllUser”);

          九、findByNamedQuery(String queryName, Object value)

          示例:

          1、首先需要在User.hbm.xml中定義命名查詢

          <hibernate-mapping>

          <class>……</class>

          <query name=”queryByName”><!–此查詢被調用的名字–>

          <![CDATA[

          from bean.User u where u.name = ?

          ]]>

          </query>

          </hibernate-mapping>

          2、如下使用查詢:

          this.getHibernateTemplate().findByNamedQuery(”queryByName”, “test”);

          十、findByNamedQuery(String queryName, Object[] value)

          示例:

          1、首先需要在User.hbm.xml中定義命名查詢

          <hibernate-mapping>

          <class>……</class>

          <query name=”queryByNameAndPassword”><!–此查詢被調用的名字–>

          <![CDATA[

          from bean.User u where u.name =? and u.password =?

          ]]>

          </query>

          </hibernate-mapping>

          2、如下使用查詢:

          String[] values= new String[]{”test”, “123″};

          this.getHibernateTemplate().findByNamedQuery(”queryByNameAndPassword” , values);

          十一、findByNamedQueryAndNamedParam(String queryName, String paramName, Object value)

          示例:

          1、首先需要在User.hbm.xml中定義命名查詢

          <hibernate-mapping>

          <class>……</class>

          <query name=”queryByName”><!–此查詢被調用的名字–>

          <![CDATA[

          from bean.User u where u.name =:myName

          ]]>

          </query>

          </hibernate-mapping>

          2、如下使用查詢:

          this.getHibernateTemplate().findByNamedQuery(”queryByName” , “myName”, “test”);

          十二、findByNamedQueryAndNamedParam(String queryName, String[] paramName, Object[] value)

          示例:

          1、首先需要在User.hbm.xml中定義命名查詢

          <hibernate-mapping>

          <class>……</class>

          <query name=”queryByNameAndPassword”><!–此查詢被調用的名字–>

          <![CDATA[

          from bean.User u where u.name =:myName and u.password=:myPassword

          ]]>

          </query>

          </hibernate-mapping>

          2、如下使用查詢:

          String[] names= new String[]{”myName”, “myPassword”};

          String[] values= new String[]{”test”, “123″};

          this.getHibernateTemplate().findByNamedQuery(”queryByNameAndPassword” , names, values);

          十三、findByValueBean(String queryString , Object value);

          示例:

          1、定義一個ValueBean,屬性名必須和HSQL語句中的:后面的變量名同名,此處必須至少有兩個屬性,分別為myName和 myPassword,使用setter方法設置屬性值后

          ValueBean valueBean= new ValueBean();

          valueBean.setMyName(”test”);

          valueBean.setMyPasswrod(”123″);

          2、

          String queryString= “from bean.User u where u.name=:myName and u.password=:myPassword”;

          this.getHibernateTemplate().findByValueBean(queryString , valueBean);

          十四、findByNamedQueryAndValueBean(String queryName , Object value);

          示例:

          1、首先需要在User.hbm.xml中定義命名查詢

          <hibernate-mapping>

          <class>……</class>

          <query name=”queryByNameAndPassword”><!–此查詢被調用的名字–>

          <![CDATA[

          from bean.User u where u.name =:myName and u.password=:myPassword

          ]]>

          </query>

          </hibernate-mapping>

          2、定義一個ValueBean,屬性名必須和User.hbm.xml命名查詢語句中的:后面的變量名同名,此處必須至少有兩個屬性,分別為 myName和myPassword,使用setter方法設置屬性值后

          ValueBean valueBean= new ValueBean();

          valueBean.setMyName(”test”);

          valueBean.setMyPasswrod(”123″);

          3、

          String queryString= “from bean.User u where u.name=:myName and u.password=:myPassword”;

          this.getHibernateTemplate().findByNamedQueryAndValueBean(”queryByNameAndPassword”, valueBean);

           

          原文摘自http://holoblog.iteye.com/blog/1245768

          posted @ 2012-05-14 17:01 timelyxyz 閱讀(112) | 評論 (0)編輯 收藏

          僅列出標題
          共4頁: 上一頁 1 2 3 4 下一頁 
          主站蜘蛛池模板: 濮阳县| 信丰县| 金沙县| 白水县| 黑水县| 商水县| 五家渠市| 黔东| 龙泉市| 四会市| 荔浦县| 合川市| 望谟县| 弋阳县| 阜新市| 铜山县| 沧州市| 江川县| 德化县| 许昌县| 涿鹿县| 聂荣县| 江源县| 南华县| 肇州县| 延安市| 宜黄县| 玛曲县| 南昌市| 黄陵县| 柳林县| 永州市| 定西市| 顺昌县| 十堰市| 揭西县| 西安市| 仁怀市| 青神县| 富宁县| 自治县|