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

          2012年1月14日

          2012.09.19 office for mac 2011更新到14.2.4版本,最大的變化就是解決了office在pro retina中的顯示問題。

           

          檢查并安裝更新到14.2.4之后,我的retina中office的顯示完全OK了.

          這是office for mac team的官方聲明鏈接link

          這是網(wǎng)上關(guān)于升級到14.2.4之后仍然無效的解決方法的鏈接link2.

           

          posted @ 2012-10-13 09:53 timelyxyz 閱讀(233) | 評論 (0)編輯 收藏

          并集:Set1 union Set2

          交集:Set1 intersect Set2

          posted @ 2012-10-11 21:15 timelyxyz 閱讀(240) | 評論 (0)編輯 收藏

          正確語句
          1 update jytuser set userid=(select member.userid from member where member.id=jytuser.owner_id)

           

          有2個易錯點: 

          1)表自關(guān)聯(lián)好像行不通。我猜想會不會和查詢時建立的索引更改有關(guān)。

          2)這種寫法postgres不支持

          1 update jytuser,member set jytuser.userid=member.userid where jytuser.owner_id=jmember.id and jytuser.userid=0;

          報錯如下:

           

          posted @ 2012-10-10 11:36 timelyxyz 閱讀(203) | 評論 (0)編輯 收藏

          最近在做數(shù)據(jù)同步的項目,過程中接觸了spring+jdbc的開發(fā)模式(IDE: sts),然后開始使用maven管理項目。目前碰到的一個問題是在本地添加一個repository,加的是用于連接sqlserver的驅(qū)動包sqljdbc4.jar。我在很多maven倉庫里都沒找到這個jar,只能手動的下載來,然后添加到本地倉庫里。發(fā)現(xiàn)這個包好像很多人沒有添加成功,我在這里找到了解決方法http://claude.betancourt.us/add-microsoft-sql-jdbc-driver-to-maven/

          主要步驟如下:

          1. 本地下載sqljdbc4.jar

          2. 解壓到本地文件夾中,并找到sqljdbc4.jar路徑

          3. 打開命令窗口,執(zhí)行以下語句(前提:先配置好maven環(huán)境變量)

          1 C:\Users\nbxyz>mvn install:install-file -Dfile=e:\sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar

          4."BUILD SUCCESS"即添加成功



          生成的pom文件如下

          1 <?xml version="1.0" encoding="UTF-8"?>
          2 <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
          3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
          4   <modelVersion>4.0.0</modelVersion>
          5   <groupId>com.microsoft.sqlserver</groupId>
          6   <artifactId>sqljdbc4</artifactId>
          7   <version>4.0</version>
          8   <description>POM was created from install:install-file</description>
          9 </project>

           

          posted @ 2012-10-09 14:40 timelyxyz 閱讀(314) | 評論 (0)編輯 收藏

           1     private static Map<String, Long> getPictureHeightAndWidthMap(String picUrl) {
           2         Map<String, Long> map = new HashMap();
           3         try {
           4             URL url = new URL(picUrl);
           5             HttpURLConnection connection = (HttpURLConnection) url
           6                     .openConnection();
           7             DataInputStream in = new DataInputStream(
           8                     connection.getInputStream());
           9             BufferedImage image = ImageIO.read(in);
          10             map.put("w", image.getWidth() * 1L);
          11             map.put("h", image.getHeight() * 1L);
          12             connection.disconnect();
          13             in.close();
          14         } catch (IOException e) {
          15             e.printStackTrace();
          16         }
          17         return map;
          18     }
          19 
          20     public static Long getHeight(String picUrl) {
          21         Map<String, Long> map = getPictureHeightAndWidthMap(picUrl);
          22         return null == map.get("h") ? 0 : map.get("h");
          23     }
          24 
          25     public static Long getWidth(String picUrl) {
          26         Map<String, Long> map = getPictureHeightAndWidthMap(picUrl);
          27         return null == map.get("w") ? 0 : map.get("w");
          28     }

          posted @ 2012-09-26 09:34 timelyxyz 閱讀(418) | 評論 (0)編輯 收藏

          Do "Show package contents" on the Eclipse.app.  
          Edit Contents/Info.plist.  
          Just above   

          </dict>
          </plist>

          Place this:  

          <key>NSHighResolutionCapable</key> 
          <true/>

          Then, log out or make a copy of the app so that OSX will notice the change.  Now, the info window will not show "Open in Low Resolution" as checked.  Launch Eclipse and enjoy your new retina awesomeness.

          solution from https://bugs.eclipse.org/bugs/show_bug.cgi?id=382972

          同樣的方法也可以解決的軟件有:Spring tool suites.

          posted @ 2012-09-22 18:27 timelyxyz 閱讀(329) | 評論 (0)編輯 收藏

          1 首先查看PATH
          命令:$PATH  
           
          2 如何設(shè)置PATH
          命令:echo "export PATH=xxxxxx:$PATH" >> ~/.bash_profile
          解釋:把"export PATH=xxxxxx:$PATH"輸出打印到~/.bash_profile中去。
           
          3 Unix知識補充:~/.bash_profile介紹
          mac和linux終端一般用bash來進行解析。當(dāng)bash在讀完了整體環(huán)境變量的/etc/profile并借此調(diào)用其他配置文件后,接下來則是會讀取用戶自定義的個人配置文件。bash讀取的文件總共有三種:
          ~/.bash_profile   ~/.bash_login    ~/.profile
          其實bash再啟動是只讀上面文件的一個,而讀取的順序則是依照上面的順序。也就是說讀到bash_profile就不讀后面的了,如果bash_profile不存在,后面的才能有機會。
          讓我們來看看bash_profile里面有什么內(nèi)容:
          命令:cat ~/.bash_profile 
          最后重啟你的終端就會有剛才設(shè)置的全局變量了。 
           【2012.02.28更新】
          最直觀的方法是:
          cd ~
          open .bash_profile
          這時候就會直接用記事本程序打開這個配置文件,比在終端里那么設(shè)置要簡單直觀多了。
          要注意一點那就是配置文件里的變量是會覆蓋的,比如
          export PATH=1
          export PATH=2
          那么后面的2會把前面的1覆蓋的。

          posted @ 2012-09-22 17:14 timelyxyz 閱讀(487) | 評論 (0)編輯 收藏

          hibernate默認(rèn)的,以及網(wǎng)絡(luò)上的主流支持left join的表關(guān)系是one-to-many的,可以使用left join fetch(需要配置lazy="true" fetch="select"),也可以使用Criteria或者CriteriaQuery(link1 link2)來進行查詢。

           

          對于many-to-one,首先我們先建兩個model:

           

          @Entity
          public class ClassOne {
          public String id;
          public boolean isDeleted;  
          }

          @Entity

          public class ClassTwo {
          public String id; 
          @ManyToOne
          public ClassOne classOne; // 父表
          public boolean isDeleted;  
          }

           目前有兩個需求:

           

          (1)select a.id,b.id from ClassTwo as b left join b.classOne as a;【正確,獲取到了所有ClassOne表的數(shù)據(jù)項】

          (2)select a.id,count(b.id) from ClassTwo as b left join b.classOne as a where a.isDeleted=false and b.isDeleted=false group by a.id;【count結(jié)果中把0的濾去了,沒達(dá)到我的需求】 

          對于第二種,目前我還沒找到具體的解決方法,仍需研究。 

           

          posted @ 2012-09-18 13:47 timelyxyz 閱讀(222) | 評論 (0)編輯 收藏

          hi

          outer-join     fetch     lazy         主鍵表class     檢索策略         檢索方式
          true/false/auto     select     false         true/false     立即檢索(n+1次查詢)     所有
          -         -     no-proxy/proxy     true         延遲檢索         所有
          -         -     -         false         立即檢索(n+1次查詢)     所有
          -         join     false         true/false     inner join         QBC,get()/load()
          -         -     -         -         立即檢索(n+1次查詢)     HQL,NativeSQL
          -         join     no-proxy/proxy     false         inner join         QBC,get()/load()
          -         -     -         -         立即檢索(n+1次查詢)     HQL,NativeSQL
          -         -     -         true         inner join         QBC,get()/load()
          -         -     -         -         延遲檢索




          String hql = "select t,count(tp) from ContentTag_Post as tp     left join fetch tp.tag as t"
              + " where tp.tag=t and t.owner.id=? "
              + " and tp.isDeleted=false and t.isDeleted=false "
              + " group by t order by t.createTime desc ";


                  String hql = "select t,count(tp) from ContentTag as t left join ContentTag_Post as tp "
                          + " where t.owner.id=? and t=tp.tag "
                          + " and t.isDeleted=false and tp.isDeleted=false "
                          + " group by t order by t.createTime desc ";

           Path expected for join!
          2012-08-22 12:47:37 [ERROR]  Invalid path: 'tp.tag'
          right-hand operand of a binary operator was null
          <AST>:0:0: unexpected end of subtree
          left-hand operand of a binary operator was null


          select查詢 join查詢

          @LazyToOne用法
          http://docs.jboss.org/hibernate/annotations/3.4/reference/zh_cn/html/entity.html
          Java中的transient,volatile和strictfp關(guān)鍵字
          http://www.iteye.com/topic/52957
          transient
            Java語言的關(guān)鍵字,用來表示一個域不是該對象串行化的一部分。當(dāng)一個對象被串行化的時候,transient型變量的值不包括在串行化的表示中,然而非transient型的變量是被包括進去的


          class A implements Serializable {
           private String name;
           transient private String address;
          }

          那么你在串行化(IO流等)A類時 給它的name和address屬性賦值,那么你在提取A時,拿到了name屬性,但是卻拿不到address屬性。




          lazy是延時的意思,如果lazy=true,那么就是說數(shù)據(jù)庫中關(guān)聯(lián)子表的信息在hibernate容器啟動的時候不會加載,而是在你真正的訪問到字表非標(biāo)識字段的時候,才會去加載。
          反之,如果lazy=false的話,就是說,子表的信息會同主表信息同時加載。
          一般用只有完全用到子表信息的時候,才會lazy=false

          join 查詢的時候,是用以條語句查處所有記錄,包括關(guān)聯(lián)表記錄,select查出的是N+1條記錄,兩個都是差不多的,但是如果用了lazy=true,延遲加載的話,select在查詢時只會查出主表記錄,也就是1,如果其他地方也用到了數(shù)據(jù),此時就會自動在執(zhí)行查詢,查出N,可以降低內(nèi)存消耗 .還有,hibernate是的session是輕量級的,創(chuàng)建和銷毀都不花很多資源,查詢數(shù)據(jù)也很快,這里fetch主要起這個作用    

          Path expected for join! unexpected end of subtree

          posted @ 2012-09-04 10:55 timelyxyz 閱讀(154) | 評論 (0)編輯 收藏

          使用條件如下:

          a left join  b

          a must be b's parent

          posted @ 2012-07-24 11:37 timelyxyz 閱讀(390) | 評論 (0)編輯 收藏

          突然拋了一個concurrentModificationException錯誤,Iterator的一個基本概念沒有掌握導(dǎo)致的這個錯誤,就是在Iterator的實現(xiàn)類。比如Hashtable里面的內(nèi)部類
           private class Enumerator<T> implements Enumeration<T>, Iterator<T>

          會在next,或者remove的時候檢查當(dāng)前集合是否會在修改狀態(tài),如果是的話,就會拋出 ConcurrentModificationException,而他自己remove則是使用了同步的方法,而且同步了modCount;expectedModCount;

           1 public T next() {
           2      if (modCount != expectedModCount)
           3          throw new ConcurrentModificationException();
           4      return nextElement();
           5  }
           6 
           7 
           8 public void remove() {
           9      if (!iterator)
          10         throw new UnsupportedOperationException();
          11      if (lastReturned == null)
          12         throw new IllegalStateException("Hashtable Enumerator");
          13      if (modCount != expectedModCount)
          14         throw new ConcurrentModificationException();
          15 
          16      synchronized(Hashtable.this) {
          17         Entry[] tab = Hashtable.this.table;
          18         int index = (lastReturned.hash & 0x7FFFFFFF) % tab.length;
          19 
          20      for (Entry<K,V> e = tab[index], prev = null; e != null; prev = e, e = e.next) {
          22       if (e == lastReturned) {
          23          modCount++;
          24          expectedModCount++;
          25          if (prev == null)
          26             tab[index] = e.next;
          27          else
          28             prev.next = e.next;
          29          count--;
          30          lastReturned = null;
          31          return;
          32       }
          33      }
          34      throw new ConcurrentModificationException();
          35      }
          36     }
          37     }
          而自己在next的同時,修改了這個集合,導(dǎo)致了這個錯誤的出現(xiàn)

           

          在Map或者Collection的時候,不要用它們的API直接修改集合的內(nèi)容,如果要修改可以用Iterator的remove()方法,例如:
          1 public void setReparation( Reparation reparation ) {
          2         for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations為Collection
          3             Reparation repa = (Reparation)it.next();
          4             if (repa.getId() == reparation.getId()){
          5                 this.reparations.remove(repa);
          6                 this.reparations.add(reparation);
          7             }
          8         }
          9    }

           

          如上寫會在運行期報ConcurrentModificationException,可以如下修改:

           

           1  public void setReparation( Reparation reparation ) {
           2         boolean flag = false;
           3         for (Iterator it = this.reparations.iterator();it.hasNext();){    //reparations為Collection
           4             Reparation repa = (Reparation)it.next();
           5             if (repa.getId() == reparation.getId()){
           6                 it.remove();
           7                 flag = true;
           8                 break;
           9             }
          10         }
          11         if(flag){
          12           this.reparations.add(reparation);
          13         }
          14     }

           

           

          原文摘自 alreal 

           

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

          API語法:

          File(String pathname)
          通過將給定路徑名字符串轉(zhuǎn)換為抽象路徑名來創(chuàng)建一個新 File 實例。
          public static final String separator
          與系統(tǒng)有關(guān)的默認(rèn)名稱分隔符,為了方便,它被表示為一個字符串。此字符串只包含一個字符,即 separatorChar
          public static final char separatorChar
          與系統(tǒng)有關(guān)的默認(rèn)名稱分隔符。此字段被初始化為包含系統(tǒng)屬性 file.separator 值的第一個字符。在 UNIX 系統(tǒng)上,此字段的值為 '/';在 Microsoft Windows 系統(tǒng)上,它為 '\\'

          注意:

          路徑名字符串與抽象路徑名之間的轉(zhuǎn)換與系統(tǒng)有關(guān)。將抽象路徑名轉(zhuǎn)換為路徑名字符串時,每個名稱與下一個名稱之間用一個默認(rèn)分隔符 隔開。默認(rèn)名稱分隔符由系統(tǒng)屬性 file.separator 定義,可通過此類的公共靜態(tài)字段 separatorseparatorChar 使其可用。將路徑名字符串轉(zhuǎn)換為抽象路徑名時,可以使用默認(rèn)名稱分隔符或者底層系統(tǒng)支持的任何其他名稱分隔符來分隔其中的名稱。

           

          例如,我希望的文件絕對路徑是E:\dev\workspace\iclass_web/conf/filterconfig.xml(計作myPath),有兩種創(chuàng)建File的形式:

          1)new File(myPath)不會報錯;

          2)new File("E:\dev\workspace\iclass_web/conf/filterconfig.xm")報錯,應(yīng)修改為new File("E:\\dev\\workspace\\iclass_web/conf/filterconfig.xml"

           我的系統(tǒng)是windows32位,io.File的一個字段FileSystem是一個抽象類,F(xiàn)ileSystem被一個Win32FileSystem類繼承,從而實現(xiàn)里面的public abstract String normalize(String path);方法。

           Win32FileSystem部分源碼如下:

           1 private final char slash;  2     private final char altSlash;  3     private final char semicolon;  4
           5     public Win32FileSystem() {  6     slash = ((String) AccessController.doPrivileged(  7               new GetPropertyAction("file.separator"))).charAt(0);  8     semicolon = ((String) AccessController.doPrivileged(  9               new GetPropertyAction("path.separator"))).charAt(0); 10     altSlash = (this.slash == '\\') ? '/' : '\\'; 11     } 12 13     private boolean isSlash(char c) { 14     return (c == '\\') || (c == '/'); 15     } 16 17     private boolean isLetter(char c) { 18     return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z')); 19     } 20 21     private String slashify(String p) { 22     if ((p.length() > 0) && (p.charAt(0) != slash)) return slash + p; 23     else return p; 24     } 25    26     /* Check that the given pathname is normal.  If not, invoke the real 27        normalizer on the part of the pathname that requires normalization. 28        This way we iterate through the whole pathname string only once. */ 29     public String normalize(String path) { 30     int n = path.length(); 31     char slash = this.slash; 32     char altSlash = this.altSlash; 33     char prev = 0; 34     for (int i = 0; i < n; i++) { 35         char c = path.charAt(i); 36         if (c == altSlash) 37         return normalize(path, n, (prev == slash) ? i - 1 : i); 38         if ((c == slash) && (prev == slash) && (i > 1)) 39         return normalize(path, n, i - 1); 40         if ((c == ':') && (i > 1)) 41         return normalize(path, n, 0); 42         prev = c; 43     } 44     if (prev == slash) return normalize(path, n, n - 1); 45     return path; 46     }

           

          posted @ 2012-07-10 17:12 timelyxyz 閱讀(153) | 評論 (0)編輯 收藏

          Hibernate中使用COUNT DISTINCT關(guān)鍵字: Hibernate

          在Hibernate中, 計算某列非重復(fù)記錄的總數(shù), 使用COUNT + DISTINCT

          在MySQL中,可以使用

          sql 代碼
          1. select COUNT(DISTINCT(name)) from products  

          但在Hibernate中卻不能用如下格式

          1. select COUNT(DISTINCT(name)) from ProductDTO  

          需要把里面的括號去掉, 改成

          1. select COUNT(DISTINCT name ) from ProductDTO  

          在MySQL中也可以使用這種樣式.

          posted @ 2012-06-28 13:24 timelyxyz 閱讀(119) | 評論 (0)編輯 收藏

          報錯現(xiàn)象

          Oops: JPAQueryException
          An unexpected error occured caused by exception JPAQueryException: Error while executing query select t from TurnedIn t, Notification n  where n.itemId=t.id and n.type=? and n.receiver.id=? and n.isDeleted=false group by t order by t.createTime desc: org.hibernate.type.SerializationException: could not deserialize
          ...
          Caused by: java.io.InvalidClassException: models.member.Member; local class incompatible: stream classdesc serialVersionUID = 8996579512119659486, local class serialVersionUID = -7513555048418418149

          異常原因

          本地和遠(yuǎn)程的member序列化后的serialVersionUID不

          解決方法

          將本地的序列化的類中的版本號(serialVersionUID )改成和遠(yuǎn)程中一樣,在本地的序列化類里的private static final long serialVersionUID =  改成遠(yuǎn)程的就行了,如果沒有的話就加上這句。

           

          關(guān)于“org.hibernate.type.SerializationException: could not deserialize”,我查了很多的資料,大概有以下幾個原因:

          1.該類的序列版本號與從流中讀取的類描述符的版本號不匹配(jdk版本更換會造成這個問題)

          2.該類包含未知數(shù)據(jù)類型(hibernate配置文件中未指定數(shù)據(jù)類型)

          3.該類沒有可訪問的無參數(shù)構(gòu)造方法


           

           

           

          posted @ 2012-06-26 09:51 timelyxyz 閱讀(1086) | 評論 (0)編輯 收藏

          pgSql

          語法 to_number(text, text)

          例子 select to_number(trim(both 'ibs' from classname), '999999') as cn from bbs order by cn   /*trim(both 'ibs' from classname)去除classname字段中的'ibs'字符*/

          mySql

          語法 str*1 / str+1 / -str  /*str為varchar的數(shù)字,此處不一定是1,只要是數(shù)字即可*/

          hql

          語法 to_number(text, text)

           

          例子 select b from BBS b where b.isDeleted=false order by to_number(trim(both 'ibs' from b.className), '999999')


           

           

          pgSql數(shù)據(jù)類型格式化函數(shù) 

          posted @ 2012-06-14 15:43 timelyxyz 閱讀(581) | 評論 (0)編輯 收藏

          order by isTop desc


           

          默認(rèn)false在前;按desc,true在前

          posted @ 2012-06-13 15:00 timelyxyz 閱讀(730) | 評論 (0)編輯 收藏

                在push之前有時候會不放心是不是忘記加某些文件,或者是不是多刪了個什么東西,這時候希望能夠看看上次commit都做了些什么。

          一開始想到的是用git diff,但是git diff用于當(dāng)前修改尚未commit的時候較為方便,一旦commit后,需要指定上次節(jié)點的名稱(一個hash值),不方便。這種時候用git log更合適,因為commit的內(nèi)容會以log來記錄。

          下面記錄幾個常用的情境以及對應(yīng)的命令。

          僅僅想看最近誰有提交,以及提交的描述

          對應(yīng)命令 git log

          顯示Sample

           

          commit 6305aa81a265f9316b606d3564521c43f0d6c9a3
          Author: XXX
          Date:   Thu Nov 3 11:38:15 2011 +0800

              fill author information in the head of files and format some code

          commit 8e8a4a96e134dab8f045937efee35bd710006946
          Author: XXX
          Date:   Thu Nov 3 04:05:34 2011 +0800

              user management is mostly complete

              details:
              add support for account disable/enable
              rewrite most related views to suit the above need
              provide two decorators for access control (see README)
              fixed many errors in Milestone 1

          commit 2870cd564371d8ad043d0da426a5770d36412421
          Author: XXX
          Date:   Mon Oct 17 20:19:04 2011 -0400

              fix the bug of get_ori_url_from_shorturl().

          commit b6cdd881a19ecaff838d5825c3a6b7058fdd498a
          Author: XXX
          Date:   Mon Oct 17 20:17:37 2011 -0400

              fix the bug of get_article_from_short_url.

          僅僅想看最后一次的提交

          對應(yīng)命令參數(shù) -n 1

          顯示Sample

          commit 6305aa81a265f9316b606d3564521c43f0d6c9a3
          Author: XXX
          Date: Thu Nov 3 11:38:15 2011 +0800

          fill author information in the head of files and format some code

          想看到最近一次提交所有更改過的文件

          對應(yīng)命令 git log -n 1 --stat

          顯示Sample

          commit 6305aa81a265f9316b606d3564521c43f0d6c9a3
          Author: XXX
          Date:   Thu Nov 3 11:38:15 2011 +0800

              fill author information in the head of files and format some code

          Site/accounts/decorators.py                        |    2 +-
          Site/accounts/forms.py                             |    1 +
          Site/accounts/models.py                            |    1 +
          Site/accounts/readme                               |    3 ++-
          Site/accounts/templates/account_activate.html      |    1 +
          Site/accounts/templates/account_disabled.html      |    1 +

          28 files changed, 37 insertions(+), 8 deletions(-)

          想看到最近一次提交所有更改的細(xì)節(jié)

          對應(yīng)命令 git log -n 1 -p

          顯示Sample

          commit 6305aa81a265f9316b606d3564521c43f0d6c9a3
          Author: XXX
          Date:   Thu Nov 3 11:38:15 2011 +0800

              fill author information in the head of files and format some code

          diff --git a/Site/accounts/decorators.py b/Site/accounts/decorators.py
          index 22522bc..a6bb440 100755
          --- a/Site/accounts/decorators.py
          +++ b/Site/accounts/decorators.py
          @@ -1,9 +1,9 @@
          #!/usr/bin/env python
          # -*- coding: utf-8 -*-
          +# author: Rex Nov. 3, 2011
          from functools import wraps
          from django.core.urlresolvers import reverse
          from django.http import HttpResponseRedirect
          -from django.utils.decorators import available_attrs
          from Site.accounts.models import UserProfile

          def login_required(view_func):
          diff --git a/Site/accounts/forms.py b/Site/accounts/forms.py
          index 016710b..778d92a 100755
          --- a/Site/accounts/forms.py
          +++ b/Site/accounts/forms.py
          @@ -1,5 +1,6 @@
          #!/usr/bin/env python
          # -*- coding: utf-8 -*-
          +# author: Rex Nov. 3, 201

          有了這幾條命令,基本上對于想看最近更改的情境就可以應(yīng)付過去了。最后一條并不很常用,如果有visual的工具可能更直觀些。

           

          原文轉(zhuǎn)自git使用點滴

           

          posted @ 2012-06-13 12:24 timelyxyz 閱讀(215) | 評論 (0)編輯 收藏

                Onunload,onbeforeunload都是在刷新或關(guān)閉時調(diào)用,可以在<script>腳本中通過window.onunload 來指定或者在<body>里指定。區(qū)別在于onbeforeunload在onunload之前執(zhí)行,它還可以阻止onunload的執(zhí)行。

              Onbeforeunload也是在頁面刷新或關(guān)閉時調(diào)用,Onbeforeunload是正要去服務(wù)器讀取新的頁面時調(diào)用,此時還沒開始讀取;而 onunload則已經(jīng)從服務(wù)器上讀到了需要加載的新的頁面,在即將替換掉當(dāng)前頁面時調(diào)用。Onunload是無法阻止頁面的更新和關(guān)閉的。而 Onbeforeunload 可以做到。曾經(jīng)做一個考試系統(tǒng),涉及到防止用戶半途退出考試(有意或者無意),代碼如下:

           

          <body onbeforeunload=" checkLeave()">

           

          <script>
          function checkLeave(){
              event.returnValue="確定放棄考試?(考試作廢,不記錄成績)";
          }
          </script>

           

           

          這樣可以讓用戶確認(rèn)是否要退出考場,其實BLOGJAVA在用戶編寫B(tài)LOG時,如果不保存而跳轉(zhuǎn)到其他頁面,也會有一個確認(rèn)的提示(防止誤操作),也是用到Onbeforeunload。

             另外還可以用來在頁面關(guān)閉的時候關(guān)閉session,代碼如下(注:用window.screenLeft > 10000 來區(qū)分關(guān)閉和刷新操作):

          <body onbeforeunload=" closeSession()">

           

          <script>
          function closeSession (){
              //關(guān)閉(刷新的時候不關(guān)閉Session)
              if(window.screenLeft>10000){
                 //關(guān)閉Session的操作(可以運用AJAX)
              }
          }
          </script>

           

           

           

          文章摘自 blogJava

           

          posted @ 2012-06-11 16:11 timelyxyz 閱讀(138) | 評論 (0)編輯 收藏

          問題描述:firefox下js中動態(tài)組裝select時指定option的selected屬性的失效

           

          有問題的代碼如下:

           1                         // 加載select列表
           2                         var teaOption ='', ownerSel = $("ownerSel");
           3                         for(var i = 0; i < teaList.length; i ++){
           4                             var teacher = teaList[i];
           5                             if(teacher.isDeleted === false){
           6                                 var tid = teacher.id, tName = teacher.fullName, newOption;
           7                                 var flag = ((tid === formerOwnerId) ? 'selected="selected"' : '');
           9                                 teaOption += '<option value="'+tid+'" '+ flag +'>'+ tName +'</option>';
          10                             }
          11                         }
          12                         ownerSel.html(teaOption);

           此時selected屬性無效,ff中的select顯示的是option列表的最后一個。

          原因貌似是這樣子:
          selected這個屬性本身是沒有錯的,你在頁面開始加載的前寫好,然后瀏覽器加載的時候就會讀取這個dom,然后有selected這個效果。
          但是通過js動態(tài)組裝的select的html代碼,在ie下我剛剛試了下可行(我剛剛失敗的原因是三目運算符處少加了一個括號);firefox下,在請求加載的同時加載dom元素,但是ff內(nèi)核可能是為了追求速度,而省略了一些dom的屬性的加載,導(dǎo)致了selected這個屬性的失效。

          解決方法(我用的是mootools):在加載的時候?qū)ption元素通過如下解決

           1                         // 加載select列表
           2                         var ownerSel = $("ownerSel");
           3                         for(var i = 0; i < teaList.length; i ++){
           4                             var teacher = teaList[i];
           5                             if(teacher.isDeleted === false){
           6                                 var tid = teacher.id, tName = teacher.fullName, newOption;
           7                                 if(tid === formerOwnerId)
           8                                     newOption = new Element('option', {"value" : tid, "selected" : "selected"}).html(tName);
           9                                 else
          10                                     newOption = new Element('option', {"value" : tid}).html(tName);
          11                                 ownerSel.grab(newOption); // 將新的element插入到select中
          12                             }
          13                         }

           

          posted @ 2012-06-07 08:34 timelyxyz 閱讀(1560) | 評論 (0)編輯 收藏

          錯誤 org.hibernate.HibernateException: ordinal parameter mismatch 。

          我的錯誤是未將hql語句設(shè)置參數(shù)時的占位符去掉(粗糙流了下- -///)

          1 hql += " and bbs.id=? " + bbs.id;

           

           

          在這之前網(wǎng)上發(fā)現(xiàn)的另一種錯誤也很值得注意:在數(shù)據(jù)表中用了關(guān)鍵字“call” 作為數(shù)據(jù)字段,所以產(chǎn)生了這個問題。Hibernate報錯如下:

           

           org.hibernate.HibernateException: ordinal parameter mismatch
           at org.hibernate.engine.query.HQLQueryPlan.buildParameterMetadata(HQLQueryPlan.java:225)
           at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:95)
           at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:54)
           at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:71)
           at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
           at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
           at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1583)
            ......
           

           

           出錯的原因是在org.hibernate.engine.query.ParameterParser類中有下列一段代碼

           

          1 public static void parse(String sqlString, Recognizer recognizer) throws QueryException{
          2     boolean hasMainOutputParameter = sqlString.indexOf( "call" ) > 0 &&
          3                                    sqlString.indexOf( "?" ) < sqlString.indexOf( "call" ) &&
          4                                    sqlString.indexOf( "=" ) < sqlString.indexOf( "call" );
          5     ......
          6 }

           


          我們都知道hibernate3可以調(diào)用存儲過程或函數(shù),但是有一定的限制(具體可以查看hibernate官方手冊)。
          據(jù)我分析這段代碼應(yīng)該是用來分析字符串是否是調(diào)用存儲過程或函數(shù)的語句。
          解決方法:
          1.不要在表或列中,出現(xiàn)"call"字樣
          2.用Criteria來代替hql語句

           

          posted @ 2012-06-06 13:20 timelyxyz 閱讀(332) | 評論 (0)編輯 收藏

          String和StringBuffer的區(qū)別,網(wǎng)上資料可以說是數(shù)不勝數(shù),但是看到這篇文章,感覺里面做的小例子很有代表性,所以轉(zhuǎn)一下,并自己做了一點總結(jié)。

          在java中有3個類來負(fù)責(zé)字符的操作。

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

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

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

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

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

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

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

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

          看看以下代碼:
          將26個英文字母重復(fù)加了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);
          可惜我的計算機不是超級計算機,得到的結(jié)果每次不一定一樣一般為 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);
          得到的結(jié)果為 16 有時還是 0
          所以結(jié)論很明顯,StringBuffer 的速度幾乎是String 上萬倍。當(dāng)然這個數(shù)據(jù)不是很準(zhǔn)確。因為循環(huán)的次數(shù)在100000次的時候,差異更大。不信你試試。

          根據(jù)上面所說:

          str += "here";
          的處理步驟實際上是通過建立一個StringBuffer,讓侯調(diào)用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);
          平均執(zhí)行時間為46922左右,也就是46秒。

          本文來自CSDN博客,轉(zhuǎn)載請標(biāo)明出處:http://blog.csdn.net/yirentianran/archive/2008/09/03/2871417.aspx

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

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

            String是系統(tǒng)內(nèi)置類型,而且是final的,定義一個字符串會產(chǎn)生一個實例和一個對該實例地址的引用。

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

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

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

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

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

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

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

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

          在原先的json數(shù)據(jù)中再新增數(shù)據(jù)

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

           

          擴展原先已經(jīng)定義好的方法

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

           

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

                  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;
                      ...// 獨立的操作
                     
                  }
                  // 統(tǒng)一發(fā)送ajax請求
                  new AjaxPost(this,{
                      url : ajaxUrl,
                      data: ajaxData,
                      callback : function(json){
                          callFun(json);
                          callFun.bind()
                      }
                  }).send()

           

          posted @ 2012-06-04 14:22 timelyxyz 閱讀(110) | 評論 (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();       //獲取當(dāng)前年份(2位)【注意:FireFox 的getYear返回的是“當(dāng)前年份-1900”的值(傳說以前一直這樣處理),IE卻當(dāng)Year>=2000】
              myDate.getFullYear();   //獲取完整的年份(4位,1970-????)
              myDate.getMonth();      //獲取當(dāng)前月份(0-11,0代表1月)
              myDate.getDate();       //獲取當(dāng)前日(1-31)
              myDate.getDay();        //獲取當(dāng)前星期X(0-6,0代表星期天)
              myDate.getTime();       //獲取當(dāng)前時間(從1970.1.1開始的毫秒數(shù))
              myDate.getHours();      //獲取當(dāng)前小時數(shù)(0-23)
              myDate.getMinutes();    //獲取當(dāng)前分鐘數(shù)(0-59)
              myDate.getSeconds();    //獲取當(dāng)前秒數(shù)(0-59)
              myDate.getMilliseconds();   //獲取當(dāng)前毫秒數(shù)(0-999)
              myDate.toLocaleDateString();    //獲取當(dāng)前日期
              var mytime=myDate.toLocaleTimeString();    //獲取當(dāng)前時間
              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”,進不去,應(yīng)該是連接信息有誤,可是我輸入的賬號用戶名全部是正確的,原因不知道。

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

           

          網(wǎng)上查詢了下,原因大致是這樣子的:

          在向NFS上備份的時候,數(shù)據(jù)的流向是這樣的:MySQL Server端從數(shù)據(jù)文件中檢索出數(shù)據(jù),然后分批將數(shù)據(jù)返回給mysqldump客戶端,然后mysqldump將數(shù)據(jù)寫入到NFS上。一般地,向NFS 上寫入數(shù)據(jù)的速度較之Server端檢索發(fā)送數(shù)據(jù)的速度要慢得多,這就會導(dǎo)致mysqldump無法及時的接受Server端發(fā)送過來的數(shù)據(jù),Server端的數(shù)據(jù)就會積壓在內(nèi)存中等待發(fā)送,這個等待不是無限期的,當(dāng)Server的等待時間超過net_write_timeout(默認(rèn)是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介紹

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

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

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

          ActionContext context = ActionContext.getContext();

          Map params = context.getParameters();

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

          為了實現(xiàn)這個功能,我們用了三個步驟:

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

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

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

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

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

          我們可以通過ActionContext的靜態(tài)方法:ActionContext.getContext()來取得當(dāng)前的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對象的創(chuàng)建:static ThreadLocal actionContext = new ActionContextThreadLocal();,ActionContextThreadLocal是實現(xiàn)ThreadLocal的一個內(nèi)部類。ThreadLocal可以命名為“線程局部變量”,它為每一個使用該變量的線程都提供一個變量值的副本,使每一個線程都可以獨立地改變自己的副本,而不會和其它線程的副本沖突。這樣,我們ActionContext里的屬性只會在對應(yīng)的當(dāng)前請求線程中可見,從而保證它是線程安全的。

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

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

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

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

          ServletActionContext

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

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

          2、javax.servlet.http.HttpServletResponse;:HTTPservlet相應(yīng)對象

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

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

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

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

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

          1、取得HttpServletRequest對象:

          HttpServletRequest request = ServletActionContext. getRequest();

          2、取得HttpSession對象:

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

          ServletActionContext和ActionContext有著一些重復(fù)的功能,在我們的Action中,該如何去抉擇呢?我們遵循的原則是:如果ActionContext能夠?qū)崿F(xiàn)我們的功能,那最好就不要使用ServletActionContext,讓我們的Action盡量不要直接去訪問JavaServlet的相關(guān)對象。在使用ActionContext時有一點要注意:不要在Action的構(gòu)造函數(shù)里使用ActionContext.getContext(),因為這個時候ActionContext里的一些值也許沒有設(shè)置,這時通過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

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

            1. Simple types

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

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

            以上數(shù)據(jù)類型可以被自動綁定,當(dāng)參數(shù)為丟失時,默認(rèn)會將變量的值賦為:null或0。

            2. Date

            當(dāng)時間對象以一下格式展現(xiàn)時,可以被自動綁定到后臺:

          • 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);

            }

            另外也可以根據(jù)語言來格式化時間。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語言對應(yīng)的時間格式設(shè)置為dd-MM-yyyy和MM-dd-yyyy。需要注意的是,語言必須用都好分隔開,value和lang的個數(shù)要匹配。

            如果@As注釋沒寫的話,時間會按照默認(rèn)格式來轉(zhuǎn)化。

            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,只要該對象遵守相同的命名規(guī)則。for example:

            public static void create(Client client){

              client.save();

              show(client);

            }

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

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

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

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

            ?client.name=Zenexity

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

            &client.address.zip=75009

            &client.address.country=France

            有時候為了更新對象列表,會使用一個存放了對象id的數(shù)組。For example,假設(shè)我們已經(jīng)有了一個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:還沒寫完,以后再繼續(xù)。


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

          本課題參考自《Spring in action》。并非應(yīng)用系統(tǒng)中發(fā)生的所有事情都是由用戶的動作引起的。有時候,系統(tǒng)自己也需要發(fā)起一些動作。例如,集抄系統(tǒng)每天早上六點把抄表數(shù)據(jù)傳送 給營銷系統(tǒng)。我們有兩種選擇:或者是每天由用戶手動出發(fā)任務(wù),或者讓應(yīng)用系統(tǒng)中按照預(yù)定的計劃自動執(zhí)行任務(wù)。
          在Spring中有兩種流行配置:Java的Timer類和OpenSymphony的Quartz來執(zhí)行調(diào)度任務(wù)。下面以給商丘做的接口集抄900到中間庫的日凍結(jié)數(shù)據(jù)傳輸為例:
          1. Java Timer調(diào)度器
          首先定義一個定時器任務(wù),繼承java.util.TimerTask類實現(xiàn)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("日凍結(jié)轉(zhuǎn)接任務(wù)開始時間:"+df.format(Calendar.getInstance().getTime()));
          System.out.println("日凍結(jié)轉(zhuǎn)接任務(wù)結(jié)束時間:"+df.format(Calendar.getInstance().getTime()));
          }

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

          public void setJdbc1Service(IJdbc1Service jdbc1Service) {
          this.jdbc1Service = jdbc1Service;
          }
          }
          Run()方法定義了當(dāng)任務(wù)運行時該做什么。jdbc1Service,jdbc2Service通過依賴注入的方式提供給DayDataTimerTask。如果該任務(wù)中沒有service服務(wù)的set方法,則取到的該service服務(wù)為null。
          其次,在Spring配置文件中聲明 dayDataTimerTask:
          <!-- 聲明定時器任務(wù) -->
          <bean id="dayDataTimerJob" class="xj.action.DayDataTimerTask">
          <property name="jdbc1Service">
          <ref bean="jdbc1Service"/>
          </property>
          <property name="jdbc2Service">
          <ref bean="jdbc2Service"/>
          </property>
          </bean>
          該聲明將DayDataTimerTask放到應(yīng)用上下文中,并在jdbc1Service、jdbc2Service屬性中分別裝配jdbc1Service、jdbc2Service。在調(diào)度它之前,它不會做任何事情。
          <!-- 調(diào)度定時器任務(wù) -->
          <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以怎樣的頻度調(diào)用TimerTask的run()方法。該屬性以毫秒作為單位,它被設(shè)置為864000000,指定 這個任務(wù)應(yīng)該每24小時運行一次。屬性delay允許你指定當(dāng)任務(wù)第一次運行之前應(yīng)該等待多久。在此指定DayDataTimerTask的第一次運行相 對于應(yīng)用程序的啟動時間延遲3秒鐘。
          <!-- 啟動定時器 -->
          <bean class="org.springframework.scheduling.timer.TimerFactoryBean">
          <property name="scheduledTimerTasks">
          <list>
          <ref bean="scheduledDayDataTimerJob"/>
          </list>
          </property>
          </bean>
          Spring的TimerFactoryBean負(fù)責(zé)啟動定時任務(wù)。屬性scheduledTimerTasks要求一個需要啟動的定時器任務(wù)的列表。在此只包含一個指向scheduledDayDataTimerJob的引用。
              Java Timer只能指定任務(wù)執(zhí)行的頻度,但無法精確指定它何時運行,這是它的一個局限性。要想精確指定任務(wù)的啟動時間,就需要使用Quartz[kw?:ts]調(diào)度器。
          2.Quartz調(diào)度器
          Quartz調(diào)度器不僅可以定義每隔多少毫秒執(zhí)行一個工作,還允許你調(diào)度一個工作在某個特定的時間或日期執(zhí)行。
          首先創(chuàng)建一個工作,繼承QuartzJobBean類實現(xiàn)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("日凍結(jié)轉(zhuǎn)接任務(wù)開始時間:"+df.format(Calendar.getInstance().getTime()));
          System.out.println("日凍結(jié)轉(zhuǎn)接任務(wù)結(jié)束時間:"+df.format(Calendar.getInstance().getTime()));
          }

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

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

          }

          在Spring配置文件中按照以下方式聲明這個工作:
          <!-- 定時啟動任務(wù) 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提供了兩個觸發(fā)器 SimpleTriggerBean和CronTriggerBean。SimpleTriggerBean與scheduledTimerTasks類 似。指定工作的執(zhí)行頻度,模仿scheduledTimerTasks配置。
          <!-- 調(diào)度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>
          <!—調(diào)度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表達(dá)式有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)。
          每一個元素都可以顯式地規(guī)定一個值(如6),一個區(qū)間(如9-12),一個列表(如9,11,13)或一個通配符(如*)。“月份中的日期”和“星期中的日期”這兩個元素互斥,應(yīng)該通過設(shè)置一個問號(?)來表明你不想設(shè)置的那個字段。

          corn表達(dá)式API具體見

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

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

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

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

          package test1;

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

          /**
           * 吸血鬼數(shù)字:位數(shù)為偶數(shù),可以由一對數(shù)字相乘而得,這對數(shù)字分別是吸血鬼數(shù)字的一半位數(shù)的,順序不規(guī)定<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″);//必須符合的條件但是這兩個條件時并列的(象當(dāng)于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″);//必須符合的條件但是這兩個條件時并列的(象當(dāng)于sql中的and)

          u.setName(”bb”);

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

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

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

          六、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對象的條數(shù)

          七、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”><!–此查詢被調(diào)用的名字–>

          <![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”><!–此查詢被調(diào)用的名字–>

          <![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”><!–此查詢被調(diào)用的名字–>

          <![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”><!–此查詢被調(diào)用的名字–>

          <![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”><!–此查詢被調(diào)用的名字–>

          <![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方法設(shè)置屬性值后

          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”><!–此查詢被調(diào)用的名字–>

          <![CDATA[

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

          ]]>

          </query>

          </hibernate-mapping>

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

          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 閱讀(111) | 評論 (0)編輯 收藏

          1. 引言
          JUnit4提供的新斷言語法具有很多優(yōu)點且使用簡單,這已經(jīng)不再是新鮮事了,可發(fā)現(xiàn)在實際測試代碼中仍未被普及應(yīng)用,特發(fā)此文,以期更多的人能掌握運用。
          2. assertThat基本語法
          Hamcrest 是一個測試輔助工具,提供了一套通用的匹配符 Matcher,靈活使用這些匹配符定義的規(guī)則,程序員可以更加精確的表達(dá)自己的測試思想,指定所想設(shè)定的測試條件。
          Junit4結(jié)合Hamcrest提供了新的斷言語句-assertThat,只需一個assertThat語句,結(jié)合Hamcrest提供的匹配符,就可以表達(dá)全部的測試思想。
          assertThat的基本語法如下:

          assertThat(T actual, Matcher matcher)
          assertThat(String reason, T actual, Matcher matcher)

          actual 是接下來想要驗證的值;
          matcher是使用 Hamcrest 匹配符來表達(dá)的對前面變量所期望的值的聲明,如果 actual值與 matcher 所表達(dá)的期望值相符,則斷言成功,否則斷言失敗。
          reason是自定義的斷言失敗時顯示的信息。
          一個簡單的例子:
          // 如果測試的字符串testedString包含子字符串"taobao"則斷言成功
          assertThat( testedString, containsString( "taobao" ) );

          3. assertThat優(yōu)點

          • 統(tǒng)一

          只需一條assertThat語句即可替代舊有的其他語句(如 assertEquals,assertNotSame,assertFalse,assertTrue,assertNotNull,assertNull 等),使斷言變得簡單、代碼風(fēng)格統(tǒng)一,增強測試代碼的可讀性和可維護性。
          ?

          • 語法直觀易懂

          assertThat 不再像 assertEquals 那樣,使用比較難懂的“謂賓主”語法模式(如:assertEquals(3, x);)。相反,assertThat 使用了類似于“主謂賓”的易讀語法模式(如:assertThat(x,is(3));),使得代碼更加直觀、易讀,符合人類思維習(xí)慣。
          ?

          • 錯誤信息更具描述性

          舊的斷言語法如果斷言失敗,默認(rèn)不會有額外的提示信息,如
          assertTrue(testedString.indexOf(“taobao”) > -1);
          如果該斷言失敗,只會拋出無用的錯誤信息,如java.lang.AssertionError: ,除此之外不會有更多的提示信息。
          新的斷言語法會默認(rèn)自動提供一些可讀的描述信息,如
          assertThat(testedString, containsString(“taobao”));
          如果該斷言失敗,拋出的錯誤提示信息如下:
          java.lang.AssertionError:
          Expected: a string containing “taobao”
          got: “taoba”

          ?

          • 跟Matcher匹配符聯(lián)合使用更靈活強大

          Matcher提供了功能豐富的匹配符,assertThat結(jié)合這些匹配符使用可更靈活更準(zhǔn)確的表達(dá)測試思想。
          // 驗證字符串 s是否含有子字符串 "taobao" 或 "qa" 中間的一個
          // 舊的斷言,不直觀,需要分析代碼邏輯明白驗證意圖
          assertTrue(s.indexOf("taobao")>-1||s.indexOf("qa")>-1);
          // 新的斷言,直觀易懂,準(zhǔn)確表達(dá)測試思想
          assertThat(s,anyOf(containsString("taobao"),containsString("qa")));
          // anyOf滿足條件之一即成立,containsString包含字符串則成立

          4. assertThat使用
          要想發(fā)揮assetThat的威力,必須跟Hamcrest聯(lián)合使用,JUnit4本身包含了一些自帶了一些 Hamcrest 的匹配符 Matcher,但是只有有限的幾個。因此建議你將Hamcrest包加入項目。
          在pom里加入Hamcrest依賴。
          <dependency>
          <groupId>org.hamcrest</groupId>
          <artifactId>hamcrest-all</artifactId>
          <version>1.1</version>
          </dependency>

          在測試類里導(dǎo)入包
          import static org.junit.Assert.*;
          import static org.hamcrest.Matchers.*;

          通過例子學(xué)習(xí)是有效的學(xué)習(xí)方式之一,下面通過常用的示例演示如何使用assertThat,更詳細(xì)的用法請參考Hamcrest相關(guān)文檔。

          • 字符相關(guān)匹配符

          /**equalTo匹配符斷言被測的testedValue等于expectedValue,
          * equalTo可以斷言數(shù)值之間,字符串之間和對象之間是否相等,相當(dāng)于Object的equals方法
          */
          assertThat(testedValue, equalTo(expectedValue));

          /**equalToIgnoringCase匹配符斷言被測的字符串testedString
          *在忽略大小寫的情況下等于expectedString
          */
          assertThat(testedString, equalToIgnoringCase(expectedString));

          /**equalToIgnoringWhiteSpace匹配符斷言被測的字符串testedString
          *在忽略頭尾的任意個空格的情況下等于expectedString,
          *注意:字符串中的空格不能被忽略
          */
          assertThat(testedString, equalToIgnoringWhiteSpace(expectedString);

          /**containsString匹配符斷言被測的字符串testedString包含子字符串subString**/
          assertThat(testedString, containsString(subString) );

          /**endsWith匹配符斷言被測的字符串testedString以子字符串suffix結(jié)尾*/
          assertThat(testedString, endsWith(suffix));

          /**startsWith匹配符斷言被測的字符串testedString以子字符串prefix開始*/
          assertThat(testedString, startsWith(prefix));

          • 一般匹配符

          /**nullValue()匹配符斷言被測object的值為null*/
          assertThat(object,nullValue());

          /**notNullValue()匹配符斷言被測object的值不為null*/
          assertThat(object,notNullValue());

          /**is匹配符斷言被測的object等于后面給出匹配表達(dá)式*/
          assertThat(testedString, is(equalTo(expectedValue)));

          /**is匹配符簡寫應(yīng)用之一,is(equalTo(x))的簡寫,斷言testedValue等于expectedValue*/
          assertThat(testedValue, is(expectedValue));

          /**is匹配符簡寫應(yīng)用之二,is(instanceOf(SomeClass.class))的簡寫,
          *斷言testedObject為Cheddar的實例
          */
          assertThat(testedObject, is(Cheddar.class));

          /**not匹配符和is匹配符正好相反,斷言被測的object不等于后面給出的object*/
          assertThat(testedString, not(expectedString));

          /**allOf匹配符斷言符合所有條件,相當(dāng)于“與”(&&)*/
          assertThat(testedNumber, allOf( greaterThan(8), lessThan(16) ) );

          /**anyOf匹配符斷言符合條件之一,相當(dāng)于“或”(||)*/
          assertThat(testedNumber, anyOf( greaterThan(16), lessThan(8) ) );

          • 數(shù)值相關(guān)匹配符

          /**closeTo匹配符斷言被測的浮點型數(shù)testedDouble在20.0¡À0.5范圍之內(nèi)*/
          assertThat(testedDouble, closeTo( 20.0, 0.5 ));

          /**greaterThan匹配符斷言被測的數(shù)值testedNumber大于16.0*/
          assertThat(testedNumber, greaterThan(16.0));

          /** lessThan匹配符斷言被測的數(shù)值testedNumber小于16.0*/
          assertThat(testedNumber, lessThan (16.0));

          /** greaterThanOrEqualTo匹配符斷言被測的數(shù)值testedNumber大于等于16.0*/
          assertThat(testedNumber, greaterThanOrEqualTo (16.0));

          /** lessThanOrEqualTo匹配符斷言被測的testedNumber小于等于16.0*/
          assertThat(testedNumber, lessThanOrEqualTo (16.0));

          • 集合相關(guān)匹配符

          /**hasEntry匹配符斷言被測的Map對象mapObject含有一個鍵值為"key"對應(yīng)元素值為"value"的Entry項*/
          assertThat(mapObject, hasEntry("key", "value" ) );

          /**hasItem匹配符表明被測的迭代對象iterableObject含有元素element項則測試通過*/
          assertThat(iterableObject, hasItem (element));

          /** hasKey匹配符斷言被測的Map對象mapObject含有鍵值“key”*/
          assertThat(mapObject, hasKey ("key"));

          /** hasValue匹配符斷言被測的Map對象mapObject含有元素值value*/
          assertThat(mapObject, hasValue(value));

          轉(zhuǎn)載務(wù)必注明出處Taobao QA Team,原文地址:http://qa.taobao.com/?p=3541

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

            conf目錄包含了各種應(yīng)用配置文件,有必須的文件:application.conf和routes。

          • application.conf:應(yīng)用的主配置文件,包含了
          • routes:路由定義文件

            你也可以在application.conf中添加一些自己的應(yīng)用中的特殊的配置選項,配置可以在程序中通過Play.configuration.get("propertyName")來讀取。當(dāng)你需要新建一個新的應(yīng)用程序,可以使用play new命令來講一些默認(rèn)配置從$PLAY_HOME/resources/application-skel/conf這個目錄中復(fù)制一些相關(guān)的程序啟動的默認(rèn)配置,還有一些配置選項是被注釋的,皆是可以選擇相關(guān)的項目來用。

            任何一個類庫需要的配置文件,盡量將其放置到conf這個目錄中:這個目錄被配置在了Java的環(huán)境變量里了。

            當(dāng)然,你也可以在application.conf這個文件中引用其他的一些play配置,只要用@include.作為開頭即可。例如,你定義了一個附加的MIME類型在conf/mime-types.conf里:

          # Web fonts
          mimetype.eot = application/vnd.ms-fontobject
          mimetype.otf = application/octet-stream
          mimetype.ttf = application/octet-stream
          mimetype.woff = application/x-font-woff

            你可以通過如下命令講文件導(dǎo)入到application.conf中:

          @include.mime = mime-types.conf

           

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

          posted @ 2012-01-16 15:43 timelyxyz 閱讀(111) | 評論 (0)編輯 收藏

          • 數(shù)據(jù)源概念
          • 數(shù)據(jù)庫連接池 
          • jndi概念
          • 數(shù)據(jù)源與連接池關(guān)系
          • 數(shù)據(jù)源與jndi關(guān)系
          • jdbc基礎(chǔ)

          1.什么是數(shù)據(jù)源?

          答: 數(shù)據(jù)源定義的是連接到實際數(shù)據(jù)庫的一條路徑而已,數(shù)據(jù)源中并無真正的數(shù)據(jù),它僅僅記錄的是你連接到哪個數(shù)據(jù)庫,以及如何連接的,如odbc數(shù)據(jù)源。也就是 說數(shù)據(jù)源僅僅是數(shù)據(jù)庫的連接名稱,一個數(shù)據(jù)庫可以有多個數(shù)據(jù)源連 接。                                                                                                                              

                 在Java語言中,DataSource對象就是一個代表數(shù)據(jù)源實體的對象。一個數(shù)據(jù)源就是一個用來存儲數(shù)據(jù)的工具,它可以是復(fù)雜的大型企業(yè)級數(shù)據(jù)庫,也可以是簡單得只有行和列的文件。數(shù)據(jù)源可以位于在服務(wù)器端,也可以位于客服端。

          2.什么是數(shù)據(jù)庫連接池?

          答: 數(shù)據(jù)庫連接是負(fù)責(zé)分配、管理和釋放數(shù)據(jù)庫連接。使用數(shù)據(jù)庫連接池是因為數(shù)據(jù)庫連接是一種關(guān)鍵的有限的昂貴的資源,這一點在多用戶的網(wǎng)頁應(yīng)用程序中體現(xiàn)得尤 為突出。如weblogic、tomcat、WebSphere容器都實現(xiàn)了數(shù)據(jù)庫連接池,但是數(shù)據(jù)庫連接池是可以獨立出來自己編碼實現(xiàn)的。

                  數(shù)據(jù)庫連接池在系統(tǒng)啟動時初始化了一定量maxIdle=idlenum的數(shù)據(jù)庫連接,即沒有他的使用中的鏈接被釋放的情況下,連接池中保存的最大空閑鏈 接數(shù)。數(shù)據(jù)庫連接請求如果沒有超過idle的值則直接去連接池中獲取;如果超過了maxIdle的值則新建一個數(shù)據(jù)庫連接;但如果數(shù)據(jù)庫連接池中的連接總 數(shù)超過了maxActive=activenum則 (如下處理);

              
            1   直接拋錯  
            2   讓想要借出連接的線程等待一段時間,如果等不到,再拋錯  
            3   每隔一段檢查一次pool,直到有可用連接,否則一直等下去  
            4   永遠(yuǎn)可以拿到(視情況需要maxActive不設(shè)置或0或負(fù))  

          但當(dāng)沒有可以使用的數(shù)據(jù)庫鏈接的時候,連接池將要等待一個鏈接被返回的最長時間(毫秒)maxWait=waitnum,超過這個時間就要拋出異常。

          3.什么是jndi?

          答:jndi全稱是java naming and directory interface。簡單點就是你按命名規(guī)則給一個東西命名然后你就可以通過該名字在特定環(huán)境下直接查找到該東西了。

          JNDI 是用于向Java程序提供目錄和命名功能的API。可以簡單地把JNDI理解為一種將對象和名字綁定的技術(shù),對象工廠負(fù)責(zé)生產(chǎn)出對象,這些對象都和惟一的 名字綁定。外部程序可以通過名字來獲取對某個對象的引用。在一個文件系統(tǒng)中,文件名被綁定給文件。在DNS中,一個IP地址綁定一個URL。在目錄服務(wù) 中,一個對象名被綁定給一個對象實體。

          在Intranets(企業(yè)內(nèi)部網(wǎng))和Internates(互聯(lián)網(wǎng))中 目錄服務(wù)(Directory service)都非常重要,它規(guī)范了命名規(guī)則,讓人們?nèi)菀桌斫鈱嶓w及之間的關(guān)系。JNDI是Java平臺的一個標(biāo)準(zhǔn)擴展,提供了一組接口、類和關(guān)于命名 空間的概念。JNDI目前所支持的技術(shù)包括LDAP、CORBA Common Object Service(COS)名字服務(wù)、RMI、NDS、DNS、Windows注冊表等等。

          jndi被設(shè)計成獨立于特定的目錄服務(wù),所以各種各樣的目錄都可以通過相同的方式進行訪問。這樣使用jndi的java程序員不僅可以獲得統(tǒng)一規(guī)整的命名和目錄,而且可以通過多層的命名方案無縫訪問(seamless acess)目錄對象。

          4.數(shù)據(jù)源與數(shù)據(jù)庫連接池關(guān)系?

          答: 我們通過第三方工具來使用數(shù)據(jù)源來實現(xiàn)對數(shù)據(jù)庫數(shù)據(jù)操作。一個數(shù)據(jù)庫連接池可以給它創(chuàng)建多個數(shù)據(jù)源,如一個人有別名;如果單純使用jdbc連接數(shù)據(jù)庫是 web容器你要什么就去連什么。這樣做沒人看不耗內(nèi)存,量大了你就死機。可以這樣理解,數(shù)據(jù)源表示一個與數(shù)據(jù)庫的連接(傳統(tǒng))或者表示很多與數(shù)據(jù)庫的連接 (使用數(shù)據(jù)庫連接池)。數(shù)據(jù)源是用于訪問連接池或多池的JNDI對象,多池的主要目的是提高可用性和在一組連接池間實現(xiàn)負(fù)載均衡。

          5.數(shù)據(jù)源與jndi關(guān)系?

          答:數(shù)據(jù)源是在JDBC 2.0中引入的一個概念。 在JDBC 2.0擴展包中定義了javax.sql.DataSource接口來描述這個概念。如果用戶希望建立一個數(shù)據(jù)庫連接,通過查詢在JNDI服務(wù)中的數(shù)據(jù) 源,可以從數(shù)據(jù)源中獲取相應(yīng)的數(shù)據(jù)庫連接。這樣用戶就只需要提供一個邏輯名稱(Logic Name),而不是數(shù)據(jù)庫登錄的具體細(xì)節(jié)。即DataSource采用Java的JNDI技術(shù),來獲得DataSource對象的引用。當(dāng)然各種web容 器把DataSource作為一種可以配置的JNDI資源來處理如tomcat。生成DataSource對象的工廠為 org.apache.commons.dbcp.BasicDataSourceFactory。

          6.jdbc基礎(chǔ)

          答:java database connectivity standard 是一套規(guī)范的面向應(yīng)用程序的接口,通過它可以訪問各類關(guān)系數(shù)據(jù)庫。各個數(shù)據(jù)庫會實現(xiàn)該接口作為驅(qū)動如jtds.jar,當(dāng)然可以自己寫實現(xiàn)。

          jdbc 是低級api,提供訪問數(shù)據(jù)庫的接口,是構(gòu)建高級api的基礎(chǔ),利用純java編寫可以在任何操作系統(tǒng)任何java環(huán)境下工作。JDBC API 中定義了一些Java類分別用來表示與數(shù)據(jù)庫的連接(connections), SQL語句(SQL statements), 結(jié)果集(result sets)以及其它的數(shù)據(jù)庫對象, 使得Java程序能方便地與數(shù)據(jù)庫交互并處理所得的結(jié)果。

          使用JDBC, 所有Java程序(包括Java applications , applets和servlet)都能通過SQL語句或存儲在數(shù)據(jù)庫中的過程(stored procedures)來存取數(shù)據(jù)庫。要通過JDBC來存取某一特定的數(shù)據(jù)庫,必須有相應(yīng)的JDBC driver,它往往是由生產(chǎn)數(shù)據(jù)庫的廠家提供,是連接JDBC API與具體數(shù)據(jù)庫之間的橋梁。JDBC driver 是用于特定數(shù)據(jù)庫的一套實施了JDBC接口的類集。

          簡單的說,jdbc可以做三件事:與數(shù)據(jù)庫建立連接,發(fā)送sql語句,處理結(jié)果。jdbc可以理解為odbc的純java語言和面向?qū)ο蟮膶崿F(xiàn)。

          7.數(shù)據(jù)庫訪問方法?

          答:在ASP中可以通過三種方式訪問數(shù)據(jù)庫:
          1、IDC(Internet Database Connector)方式;
          2、ADO(ActiveX Data Objects)方式;
          3、RDS(Remote Data Service)方式。
                  在jsp中訪問數(shù)據(jù)庫常用:
          1、JDBC-ODBC橋接器;
          2、特定數(shù)據(jù)庫的jdbc驅(qū)動直接連接數(shù)據(jù)庫;
          3、經(jīng)過池化維護一定量的連接數(shù)目,用jndi去訪問數(shù)據(jù)源對應(yīng)池獲取連接;

           

          參考:http://www.diybl.com/course/7_databases/database_other/2008126/97740.html

          posted @ 2012-01-16 09:19 timelyxyz 閱讀(138) | 評論 (0)編輯 收藏

          1. 控制輸出時間
          <div>
              <p>this part is cached for 10 seconds. Note the timeout spec with invoke overrides CacheFor annotation. </p>
              `a controllers.more.Portlets.panel2(b), "10s"
          </div>
          <p>內(nèi)文字顯示十秒鐘然后進入panel2action

          2.log:log directives are used to print a line of information to the console. It can take an argument of String
          `log
          `log a + i
          `log "a message "
          log命令用來在控制臺輸出一行信息,后面可以添加參數(shù),輸出結(jié)果如下:
          japidviews/templates/log.html(line 5):
          japidviews/templates/log.html(line 14): a10
          japidviews/templates/log.html(line 18): a message

          3.stopwatch m 輸出render到模板所需的時間

          4.~i  直接輸出i的值

          5.`each posts | String p 與`for String p : posts等價,
          `for String p : posts
              <p>index: $_index, parity: $_parity, is odd? $_isOdd, is first? $_isFirst, is last? $_isLast, total size: $_size </p>
              call a tag:  `tag SampleTag p
          `
          輸出index: 6, parity: even, is odd? false, is first? false, is last? true, total size: 6
          另一種格式
          `for (final Post p : posts) {
              another notation for invoking actions:  
              `invoke Application.echoPost(p)
          `}

          6.if-else循環(huán)語法:
              `if expr            `if(asBoolean(expr)){
                  xxx                xxx    
              `else if expr        `} else if(asBoolean(expr)){
                  yyy                yyy
              `else            `} else {
                  zzz                zzz
              `            `

          7.` suppressNull on如果下面出現(xiàn)了null的意外,如
          ` a = null;
          safe to do a.something too: $a.length()
          輸出safe to do a.something too:

          8.dontRedirect();控制不跳轉(zhuǎn)頁面,即停留在原頁面。

          說明:

          ∵在play運行時,調(diào)用一個action必須出發(fā)一個Http重定向

          ∴如果不想重定向,必須調(diào)用JapidController.dontRedirect()來避免

          9.${a}, ~a, $a and ${escape(a)} and ~{a}這幾種表達(dá)式的值相等

          10.頁面讀取異常
              `for (Error e: errors()){
                  <p>$e.getKey() : $e</p>
              `}

          11.“Elvis操作符”是Java三目運算符的簡寫。一個便捷的用法是,如果表達(dá)式的值為false或者null,則返回一個合乎情理的默認(rèn)值。好吧,我所實現(xiàn)的Elvis操作符確實不像Java中的一樣:)我所添加的?:組合符號只在${}標(biāo)簽內(nèi)起作用。
          name ?: “empty”

          12.`doBody m:帶著參數(shù)回到原先界面。該命令中的參數(shù)列表必須與調(diào)用處的“|”之后的參數(shù)聲明匹配,doBody通過匹配的參數(shù)傳遞到模板。

          13.join(Strings, "|"):Strings是list,該方法為list中的每個元素見添加一個“|”,形成一個字符串。

          14.`invoke與`a觸發(fā)的action返回的結(jié)果直接插入到原先界面中,作為界面參數(shù)的一部分。注意:invoke出發(fā)的action不跳轉(zhuǎn)頁面。

          15.renderJapid(Object... Objects):帶著參數(shù)跳轉(zhuǎn)到原先界面

          16.renderJapidWith(String template, Object... args):帶著參數(shù)跳轉(zhuǎn)到指定模板,可以實現(xiàn)在一個action中渲染多種模板。

          posted @ 2012-01-14 15:40 timelyxyz 閱讀(298) | 評論 (0)編輯 收藏

          junit4使用時導(dǎo)入的主要包org.junit.Assert.*;

          1. setUp與tearDown:這兩個方法是junit framework中提供初始化和反初始化每個測試方法的。
          setUp是在每個測試方法調(diào)用前被調(diào)用,負(fù)責(zé)初始化測試方法所需要的測試環(huán)境;
          tearDown是在每個測試方法被調(diào)用后被調(diào)用,負(fù)責(zé)撤銷測試環(huán)境。
          基本測試步驟如下:
          測試開始 -> setUp -> testXXX -> tearDown -> 測試結(jié)束

          2. public static void fail(java.lang.String message)輸出錯誤信息

          3.TestSuite 組裝測試。可以講所有的TestCase的調(diào)用添加到TestSuite中,同樣,也可以添加另外的TestSuite到TestSuite中。

          4.靜態(tài)導(dǎo)入:就是在import關(guān)鍵字后面加上static,然后可以調(diào)用這個類中的方法就和調(diào)用自己的方法沒有什么區(qū)別,例如assertEqual(excepted, actual),這個函數(shù)可以直接調(diào)
          用,不需要加上類名或者實例對象等。

          5.@Test(arg ...)被該annotation修士的方法,在JUint終將會被自動執(zhí)行,該annotation只能修飾public void 方法。

          6.@Test參數(shù)timeout:規(guī)定該方法執(zhí)行的時間,如果設(shè)置參數(shù),則被修飾方法必須在該事件被執(zhí)行結(jié)束,否則會拋出異常。語法:@Test(timeout=1)// 時間的單位為毫秒

          7.@Test參數(shù)expected:規(guī)定該方法排除異常,如果設(shè)置該參數(shù),責(zé)備修飾方法在排除該參數(shù)規(guī)定的異常的情況下才可能通過測試,否則測試失敗。for example
          @Test(expected=ArithmeticException.class)
          public void testExceptedF(){
              int i = 1/0;
          }
          此時,testExceptionF拋出了ArithmeticException異常,所以測試通過;如果測試失敗,F(xiàn)ailure Trace面板中會列出錯誤軌跡。

          8.@After:被該annotation修飾的方法,將會在每個測試方法執(zhí)行之后執(zhí)行一次。該annotation只能修飾public void 方法。

          9.@Before:被該annotation修飾的方法,將會在每個測試方法執(zhí)行之前執(zhí)行一次。該annotation只能修飾public void 方法。

          10.@AfterClass:被該annotation修飾的方法,將會在所有測試方法執(zhí)行結(jié)束后執(zhí)行一次。該annotation只能修飾public static void 方法。

          11.@BeforeClass:被該annotation修飾的方法,將會在所有測試方法執(zhí)行前執(zhí)行一次。該annotation只能修飾public static void 方法。

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

          主站蜘蛛池模板: 沈阳市| 山东省| 彩票| 兴义市| 华安县| 苗栗县| 罗甸县| 杂多县| 德化县| 大田县| 明溪县| 潜山县| 信阳市| 德阳市| 黄大仙区| 巴彦淖尔市| 志丹县| 酉阳| 中宁县| 江川县| 咸丰县| 衡阳市| 彰武县| 固安县| 周至县| 永德县| 明光市| 商南县| 湖州市| 丁青县| 姜堰市| 新田县| 安西县| 安福县| 都江堰市| 余干县| 高唐县| 威远县| 兴城市| 三亚市| 五家渠市|