水仁博客

          上善若水,仁恕載物
          隨筆 - 11, 文章 - 0, 評論 - 4, 引用 - 0
          數據加載中……

          2008年9月27日

          SpringMVC 2.5 的HelloWorld

          首先,寫一個Bean

          package springmvc.one.web;

          import org.springframework.beans.factory.annotation.Autowired;
          import org.springframework.stereotype.Controller;
          import org.springframework.ui.Model;
          import org.springframework.ui.ModelMap;
          import org.springframework.validation.BindingResult;
          import org.springframework.web.bind.annotation.RequestMapping;
          import org.springframework.web.bind.annotation.RequestMethod;

          @Controller
          @RequestMapping("/hellOne.act")
          public class HelloOneAction { 

          @RequestMapping
          public String handleRequest(String user,Model model) { 
          System.out.println("用戶名:"+user); //GET/POST的入參
          model.addAttribute("user", user); //通過Session返回到界面的出參
          model.addAttribute("helloWord", "Hello");

          return "hellouser";

          }


          再寫一個JSP頁面hellouser.jsp,此頁面放在 WEB-INF/jsp 目錄下,代碼如下:

          <html> 
          <head><title>HelloPage</title></head> 
          <body> 
          Test this sample!
          <H1> ${helloWord}, ${user}!</H2> 
          </body>
          </html>


          接著看看web.xml的配置

          <?xml version="1.0" encoding="ISO-8859-1"?> 

          <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

          <description>Spring 2.5 App</description> 
          <display-name>Spring App Examples</display-name> 

          <servlet> 
          <servlet-name>annomvc</servlet-name> 
          <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
          <load-on-startup>2</load-on-startup> 
          </servlet> 

          <servlet-mapping> 
          <servlet-name>annomvc</servlet-name> 
          <url-pattern>*.act</url-pattern> 
          </servlet-mapping> 

          </web-app>


          最后就是,annomvc.xml 文件了。

          <?xml version="1.0" encoding="UTF-8"?>
          <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
          xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

          <context:component-scan base-package="springmvc.one.web"/>

          <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

          <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp"/>

          </beans>


          好了,見一個Tomcat工程,在 tomcat 中運行,訪問下面連接,就可以運行了。

          http://localhost:8080/TOMCAT-PROJECT/hellOne.act?user=gjhuai

          posted @ 2008-09-27 14:31 水仁圭 閱讀(3477) | 評論 (1)編輯 收藏

          2008年6月8日

          [專業]JS一些知識-0806081757


          JS的日期加減函數:

          function dateAdd(date,dayNum){
          var a = date.valueOf();
          a = a + dayNum * 24 * 60 * 60 * 1000;
          a = new Date(a);
          return a;
          }


          JS把字符串裝載到DOM對象:
          var doc = new ActiveXObject("MSxml2.DOMDocument");
          doc.loadXML( xmlStr);


          當JS的正則表達式的pattern需要動態構造時,需要使用RegExp類:
          patt=new RegExp(today.replace(/\-/g,"\\-")+"((.|\n|\r|\t)+)"+yesterday.replace(/\-/g,"\\-"),"gm");
          //patt=new RegExp("2008\-5\-26((.|\n)+)2008\-5\-25","gm");
          h = h.replace(patt,yesterday);
          而不能使用/dd/gm之類簡單的pattern




          posted @ 2008-06-08 17:58 水仁圭 閱讀(232) | 評論 (0)編輯 收藏

          2008年6月7日

          [專業]Python讀gbk編碼的xml問題-0806072220


          Python讀xml時,如果編碼不是utf-8或utf-16,就出錯,如下:


          ...

          解析這個xml文件代碼如下:
          from xml.dom import minidom
          f = minidom.parse('f:\\temp\\protocol.xml')
          print f.toxml()

          出現這個錯誤:
          xml.parsers.expat.ExpatError: unknown encoding:


          解決辦法:

          由于xml協會規定,所有xml解析器均需要支持utf-8和utf-16兩種編碼而不要求別的編碼,所以我估計python提供的xml處理模塊就是不支持gb2312的。而windows下的文件,大部分均為gb2312編碼的,因此處理的時候,就會帶來不方便的地方。

          解1:利用UltraEdit等工具,將xml文件轉換成UTF-8的,然后encoding="utf-8"即可
          轉換工具如果沒有,用python可以簡單寫一個,比如
          (以下代碼轉自 http://tenyears.cn/?cat=6 )
          ----------
          # -*- coding: mbcs -*-
          import codecs
          f = codecs.open(‘D:\\normal.txt’, ‘rb’, ‘mbcs’)
          text = f.read().encode(‘utf-8′)
          f.close
          f = open(‘d:\\utf8.txt’, ‘wb’)
          f.write(text)
          f.close()
          print text.decode(‘utf-8′).encode(‘gb2312′)
          -----------------

          解2:xml文件里面不要寫入encoding,保持為gb2312本地編碼,然后程序解析的時候,采用語句
          unicode(file('f:\\temp\\a.txt', 'r', 'gb2312').read(),'gb2312').encode('utf-8')
          將整個文件轉成utf-8的 String 來處理,處理結束后,利用
          unicode(string,'utf-8').encode('gb2312')
          換成本地的gb碼,再將結果寫回文件。

          另外,python2.4的普通函數處理字符串的時候,好像已經支持各種編碼了。


          posted @ 2008-06-07 22:22 水仁圭 閱讀(3169) | 評論 (0)編輯 收藏

          [專業]代碼閱讀的經驗-0806072109


          由于工作上的原因,我不得不看大量別人寫的代碼,這是一件很痛苦的事,尤其是看既少文檔注釋,又無良好命名和結構的代碼.

          有本書叫Code Reading,中文譯作代碼閱讀方法與實踐, 簡單瀏覽了一遍電子文檔, 感覺還是隔靴搔癢, 對提高代碼閱讀效率并無太大的幫助. 自己感覺還是以下方法有些幫助:
          1. 把對代碼閱讀的認識用筆或wiki記下來, 最好根據功能結構分類,可畫些輔助理解的框圖或思維導圖
          2. 利用UML工具反向生成些類圖,包圖, 還可自己動手畫一些流程圖,時序圖和協作圖
          3. 利用調試工具,通過設斷點,單步調試,設觀察哨等手段看看到底它是怎么運行的
          4. 寫一些簡單的測試程序,通過斷言,日志來驗證自己的判斷
          5. 如有可能,和代碼的原作者或其他維護者一起做Code Review


          posted @ 2008-06-07 21:11 水仁圭 閱讀(238) | 評論 (0)編輯 收藏

          2008年1月13日

          Spring 集成測試

          8.3.1. Context管理和緩存


          Spring 中的包 spring-mock.jar 為集成測試提供了一流的支持。所有相關的API在包 org.springframework.test 中,它們不依賴于任何應用服務器或者其他部署環境。

          test包里的各種抽象類提供了如下的功能:
          • 各測試案例執行期間的Spring IoC容器緩存。
          • 測試fixture自身的依賴注入。
          • 適合集成測試的事務管理。
          • 繼承而來的對測試有用的各種實例變量。

          test包對加載的Context提供緩存,緩存功能是通過 AbstractDependencyInjectionSpringContextTests 類的一個方法(如下)實現的,此方法提供contexts xml的位置,且實現這個方法的類必須提供一個包含XML配置文件位置數組。缺省情況下,一旦加載后,這些配置將被所有的測試案例重用。

          protected abstract String[] getConfigLocations();

          當配置環境受到破壞,AbstractDependencyInjectionSpringContextTests 的 setDirty() 方法可以用來重新加載配置,并在執行下一個測試案例前重建application context。

          8.3.2. 測試fixture的依賴注入

          AbstractDependencyInjectionSpringContextTests 類將從getConfigLocations()方法指定的配置文件中自動查找你要測試的類, 并通過Setter注入該類的實例。

          簡單例子

          public class HibernateTitleDaoTests extends AbstractDependencyInjectionSpringContextTests {

          // 被測試類的實例將被(自動的)依賴注入
          private HibernateTitleDao titleDao;

          // 一個用來實現'titleDao'實例變量依賴注入的setter方法
          public void setTitleDao (HibernateTitleDao titleDao) {
          this.titleDao = titleDao;
          }

          public void testLoadTitle() throws Exception {
          Title title = this.titleDao.loadTitle(new Long10));
          assertNotNull(title);
          }

          //指定Spring配置文件加載這個fixture
          protected String[] getConfigLocations() {
          return new String[] { "classpath:com/foo/daos.xml" };
          }

          }

          getConfigLocations() 使用的是 根據類型的自動裝配(autowire byType)來注入的,所以如果你有多個bean都定義為一個類型,則對這些bean你不能用這個方法。在這種情況下你要使用 applicationContext 實例變量,并且使用 getBean() 來進行顯式查找。

          如果你的測試案例不使用依賴注入,只要不定義任何setters方法即可; 或者你可以繼承 org.springframework.test.AbstractSpringContextTests 類,它只包括用來加載Spring Context的便利方法,并且在測試fixture中不進行依賴注入。

          8.3.3. 事務管理

          測試對持久存儲的數據會有改動。類 AbstractTransactionalDataSourceSpringContextTests 在缺省情況下,對每一個測試案例,他們創建并且回滾一個事務。所以使用這個類就不用擔心數據被修改;它依賴于Application Context中定義的一個bean PlatformTransactionManager。

          如果你確實想在測試時修改數據,可以用這個類的 setComplete() 方法,這將提交而不是回滾事務。另外, endTransaction() 方法可以在測試結束前中止事務。

          8.3.4. 方便的變量

          AbstractDependencyInjectionSpringContextTests 類提供了兩個保護屬性性實例變量:

          • applicationContext (a ConfigurableApplicationContext): 可以利用它進行顯式bean查找,或者作為一個整體來測試這個Context的狀態。
          • jdbcTemplate : 對確定數據狀態的查詢很有用。

          8.3.5. 示例

          Spring的PetClinic實例展示了這些測試超類的用法

          public abstract class AbstractClinicTests extends AbstractTransactionalDataSourceSpringContextTests {

          protected Clinic clinic;

          public void setClinic(Clinic clinic) {
          this.clinic = clinic;
          }

          public void testGetVets() {
          Collection vets = this.clinic.getVets();
          assertEquals('JDBC query must show the same number of vets',
          jdbcTemplate.queryForInt('SELECT COUNT(0) FROM VETS'),
          vets.size());
          Vet v1 = (Vet) EntityUtils.getById(vets, Vet.class, 2);
          assertEquals('Leary', v1.getLastName());
          assertEquals(1, v1.getNrOfSpecialties());
          assertEquals('radiology', ((Specialty) v1.getSpecialties().get(0)).getName());
          Vet v2 = (Vet) EntityUtils.getById(vets, Vet.class, 3);
          assertEquals('Douglas', v2.getLastName());
          assertEquals(2, v2.getNrOfSpecialties());
          assertEquals('dentistry', ((Specialty) v2.getSpecialties().get(0)).getName());
          assertEquals('surgery', ((Specialty) v2.getSpecialties().get(1)).getName());
          }

          JdbcTemplate 變量用于驗證被測試的代碼是否正確。JdbcTemplate 讓測試更嚴密,且減少了對測試數據的依賴。例如,可以在不中止測試的情況下在數據庫里增加額外的數據行。

          PetClinic應用支持四種數據訪問技術--JDBC、Hibernate、TopLink和JPA ,因此 AbstractClinicTests 類不指定Context位置,這個操作在子類中實現:

          例如,用Hibernate實現的PetClinic測試包含如下方法:

          public class HibernateClinicTests extends AbstractClinicTests {

          protected String[] getConfigLocations() {
          return new String[] {
          '/org/springframework/samples/petclinic/hibernate/applicationContext-hibernate.xml'
          };
          }
          }

          8.3.6. 運行集成測試

          集成測試比單元測試更依賴于測試環境,它是測試的一個補充,而不是代替單元測試的。這種依賴主要指完整數據模型的數據庫。也可以通過DbUnit或者數據庫工具來導入測試數據。

          posted @ 2008-01-13 21:57 水仁圭 閱讀(1450) | 評論 (0)編輯 收藏

          2008年1月7日

          Sentences01

          (1) 最高級 + 名詞 + that + 主詞 + have ever seen /known /heard /had /read)
          Helen is the most beautiful girl that I have ever seen.
          海倫是我所看過最美麗的女孩。
          Mr. Zhang is the kindest teacher that I have ever had.
          張老師是我曾經遇到最仁慈的教師。

          (2) Nothing is + 比較級 than to + V
          Nothing is more important than to receive education.
          沒有比接受教育更重要的事。

          (3) ... cannot emphasize the importance of ... too much.(再怎么強調...的重要性也不為過。)
          We cannot emphasize the importance of protecting our eyes too much.
          我們再怎么強調保護眼睛的重要性也不為過。

          (4) There is no denying /doubt that從句 (不可否認的.../毫無疑問的...)
          There is no denying that the qualities of our living have gone from bad to worse.
          不可否認的,我們的生活品質已經每況愈下。
          There is no doubt that our educational system leaves something to be desired.
          毫無疑問的我們的教育制度令人不滿意。

          (5) It is universally acknowledged that從句 (全世界都知道...)
          It is universally acknowledged that trees are indispensable to us.
          全世界都知道樹木對我們是不可或缺的。

          (6)、An advantage of ... is that從句 (...的優點是...)
          An advantage of using the solar energy is that it won't create (produce) any pollution.
          使用太陽能的優點是它不會制造任何污染。

          (7) The reason why定語從句 ... is that + 句子 (...的原因是...)
          The reason why we have to grow trees is that they can provide us with fresh air.
          The reason why we have to grow trees is that they can supply fresh air for us.
          我們必須種樹的原因是它們能供應我們新鮮的空氣。

          (8) So + 形容詞 + be + 主詞 + that從句 (如此...以致于...)
          So precious is time that we can't afford to waste it.
          時間是如此珍貴,我們經不起浪費它。

          (9) Adj. + as + 主詞 + be, S + V ... (雖然...)
          Rich as our country is, the qualities of our living are by no means satisfactory.
          {by no means = in no way = on no account 一點也不}
          雖然我們的國家富有,我們的生活品質絕對令人不滿意。

          (10) 比較級 + S + V, 比較級 + S + V
          The harder you work, the more progress you make.
          你愈努力,你愈進步。
          The more books we read,the more learned we become.
          我們書讀愈多,我們愈有學問。

          (11) By +Ving, ... can ... (借著.. , ..能夠..)
          By taking exercise, we can always stay healthy.
          借著做運動,我們能夠始終保持健康。

          (12) ... enable + 受詞 + to + V (..使..能夠..)
          Listening to music enable us to feel relaxed.
          聽音樂使我們能夠感覺輕松。

          (13) On no account can we + V ... (我們絕對不能...)
          On no account can we ignore the value of knowledge.
          我們絕對不能忽略知識的價值。

          (14) It is time + S + 過去式 (該是...的時候了)
          It is time the authorities concerned took proper steps to solve the traffic problems.
          該是有關當局采取適當的措施來解決交通問題的時候了。


          (15) Those who ... (...的人...)
          Those who violate traffic regulations should be punished.
          違反交通規定的人應該受處罰。

          (16) There is no one but ... (沒有人不...)
          There is no one but longs to go to college.
          沒有人不渴望上大學。{long v.渴望}

          (17) be + forced /compelled /obliged + to do (不得不...)
          Since the examination is around the corner, I am compelled to give up doing sports.
          既然考試迫在眉睫,我不得不放棄做運動。

          (18) It is conceivable /obvious /apparent that從句 (可想而知的 /明顯的 /顯然的)
          It is conceivable that knowledge plays an important role in our life.
          可想而知,知識在我們的一生中扮演一個重要的角色。

          (19) That is the reason why ... (那就是...的原因)
          Summer is sultry. That is the reason why I don't like it.
          夏天很燠熱。那就是我不喜歡它的原因。

          (20) For the past + 時間,S + 現在完成式.. (過去...年來,...一直...)
          For the past two years, I have been busy preparing for the examination.
          過去兩年來,我一直忙著準備考試。

          (21) Since + S + 過去式,S + 現在完成式。
          Since he went to senior high school, he has worked very hard.
          自從他上高中,他一直很用功。

          (22) It pays to + V ... (...是值得的。)
          It pays to help others.
          幫助別人是值得的。

          (23) be based on (以...為基礎)
          The progress of thee society is based on harmony.
          社會的進步是以和諧為基礎的。

          (24) Spare no effort to + V (不遺余力的)
          We should spare no effort to beautify our environment.
          我們應該不遺余力的美化我們的環境。

          (25) bring home to + 人 + 事 (讓...明白...事)
          We should bring home to people the value of working hard.
          我們應該讓人們明白努力的價值。

          (26) be closely related to ... (與...息息相關)
          Taking exercise is closely related to health.
          做運動與健康息息相關。

          (27) Get into the habit of + Ving = make it a rule to + V (養成...的習慣)
          We should get into the habit of keeping good hours.
          我們應該養成早睡早起的習慣。

          (28) [Due to | Owing to | Thanks to] + N/Ving, ... (因為...)
          Thanks to his encouragement, I finally realized my dream.
          因為他的鼓勵,我終于實現我的夢想。

          (29) [What a + adj. + sth. | How + adj. + sth.] + it is to do sth.(多么...!)
          What an important thing it is to keep our promise!
          How important a thing it is to keep our promise!
          遵守諾言是多么重要的事!

          (30) leave much to be desired (令人不滿意)
          The condition of our traffic leaves much to be desired.
          我們的交通狀況令人不滿意。

          (31) have a great influence on ... (對...有很大的影響)
          Smoking has a great influence on our health.
          抽煙對我們的健康有很大的影響。

          (32) do good to (對...有益),do harm to (對...有害)
          Reading does good to our mind.
          讀書對心靈有益。
          Overwork does harm to health.
          工作過度對健康有害。

          (33) pose a great threat to ~~ (對...造成一大威脅)
          Pollution poses a great threat to our existence.
          污染對我們的生存造成一大威脅。

          (34) do one's [utmost | best] to do sth.(盡全力去...)
          We should do our utmost to achieve our goal in life.
          我們應盡全力去達成我們的人生目標。

          (35) would rather /sooner + V + than + V + (寧愿...也不)
          They would rather go fishing than stay at home.
          他們寧愿去釣魚,也不愿待在家里。
          She would sooner resign than take part in such dishonest business deals.
          她寧可辭職也不愿參與這種不正當的買賣.



          posted @ 2008-01-07 08:23 水仁圭 閱讀(203) | 評論 (0)編輯 收藏

          2007年12月30日

          Struts 2 Tag用法

           

          append 和 iterator

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/append-tag.shtml

           

          在Action類的execute方法中,實例化List對象 

          public String execute()throws Exception{
              myList = new ArrayList();
              myList.add("     myList.add("Deepak Kumar");
              myList.add("Sushil Kumar");
              myList.add("Vinod Kumar");
              myList.add("Amit Kumar");

           

              myList1 = new ArrayList();
              myList1.add("
              myList1.add("Himanshu Raj");
              myList1.add("Mr. khan");
              myList1.add("John");
              myList1.add("Ravi Ranjan");
              return SUCCESS;
            }

           

          jsp頁面中使用append和iterator兩個tag

           

          <s:append id="myAppendList">
                <s:param value="%{myList}" />
                <s:param value="%{myList1}" />
          </s:append>

             

          <s:iterator value="%{#myAppendList}">
                <s:property /><br>
          </s:iterator>


           

          generator 和 iterator

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/generator-tag.shtml


           

          在jsp中使用,'www.Roseindia.net,Deepak Kumar,Sushil Kumar,Vinod Kumar,Amit Kumar'這些內容被分行的顯示在頁面上。

          <s:generator val="%{'www.Roseindia.net,Deepak Kumar,Sushil Kumar,Vinod Kumar,Amit Kumar'}" separator=",">
              <s:iterator>
                <s:property /><br/>
              </s:iterator>
          </s:generator>

             
          參考:http://www.roseindia.net/struts/struts2/struts2controltags/GeneratorTagCountAttribute.shtml

          count="5" -->在jsp頁面中顯示前5個

          <s:generator val="%{'www.Roseindia.net,Deepak Kumar,Sushil Kumar,Vinod Kumar,Amit Kumar, Sanjay, Vijay '}" count="5" separator=",">
             <s:iterator>
                <s:property /><br/>
             </s:iterator>
          </s:generator>

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/GeneratorTagIdAttribute.shtml
          <s:generator val="%{'www.Roseindia.net,Deepak Kumar,Sushil Kumar,Vinod Kumar,Amit Kumar'}" count="4" separator="," id="myAtt" />
          <%
          Iterator i = (Iterator) pageContext.getAttribute("myAtt");
          while(i.hasNext()) {
            String s = (String) i.next(); %>
            <%=s%> <br/>
          <% }
          %>


           


          iterator

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/iterator-tag.shtml

          在Action類的execute方法中實例化一個List

          public String execute()throws Exception{
              myList = new ArrayList();
              myList.add("Fruits");
              myList.add("Apple");
              myList.add("Mango");
              myList.add("Orange");
              myList.add("Pine Apple");
              return SUCCESS;
            }


           

          在Jsp中可以通過list的名字來調用

          <s:iterator value="myList">
              <s:property /><br>
          </s:iterator>


           


          merge

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/merge-tag.shtml
          在Action類的execute方法中實例化兩個List
          public String execute() throws Exception{
              myList = new ArrayList();
              myList.add("www.Roseindia.net");
              myList.add("Deepak Kumar");
              myList.add("Sushil Kumar");
              myList.add("Vinod Kumar");
              myList.add("Amit Kumar");

              myList1 = new ArrayList();
              myList1.add("www.javajazzup.com");
              myList1.add("Himanshu Raj");
              myList1.add("Mr. khan");
              myList1.add("John");
              myList1.add("Ravi Ranjan");
              return SUCCESS;
            }


           

          在jsp中,用merge tag把兩個List合并,在iterator中用merge的id來調用

          <s:merge id="mergeId">
                  <s:param value="%{myList}" />
                  <s:param value="%{myList1}" />

          </s:merge>
          <s:iterator value="%{#mergeId}">
              <s:property /><br>
          </s:iterator>
          顯示順序:
          Display first element of the first list.
          Display first element of the second list.
          Display second element of the first list.
          Display second element of the second list.
          Display third element of the first list.
          Display thrid element of the second list.....and so on.


          subset

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/subsetTag.shtml

          public String execute() throws Exception{
              myList = new ArrayList();
              myList.add(new Integer(50));
              myList.add(new Integer(20));
              myList.add(new Integer(100));
              myList.add(new Integer(85));
              myList.add(new Integer(500));
              return SUCCESS;
            }


           

          調用Action類中的List

           <s:subset source="myList">
              <s:iterator>
                <s:property /><br>
              </s:iterator>
          </s:subset>
          在頁面上顯示前三個
          <s:subset source="myList" count="3">
              <s:iterator>
                <s:property /><br>
              </s:iterator>
          </s:subset>
          在頁面上顯示從2開始的3個
          <s:subset source="myList" count="3" start="2">
              <s:iterator>
                <s:property /><br>
              </s:iterator>
          </s:subset>

          action tag

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/action-tag.shtml

          The action tag is a generic tag that is used to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified.

          在struts.xml中定義action映射
          <action name="actionTag" class="net.roseindia.actionTag">
                 <result name="success">/pages/genericTags/success.jsp</result>
          </action>

          public String execute() throws Exception{
              return SUCCESS;
            }


           

          在jsp頁面寫入下面代碼,那么當請求actionTag.action時,無論Action類net.roseindia.actionTag中怎么處理、如何設定頁面轉向,此請求直接轉到successs.jsp頁面

          <s:action name="success">
              <b><i>The action tag will execute the result and include it in this page.</i></b></div>
          </s:action>


           

          bean tag


          參考:http://www.roseindia.net/struts/struts2/struts2controltags/bean-tag.shtml
          定義一個包含name屬性的普通JavaBean,
          public class companyName {
           
            private String name;

            public void setName(String name){
              this.name =name ;
            }

            public String getName(){
              return name;
            }
          }


           

          在jsp中調用

          <s:bean name="net.roseindia.companyName" id="uid">
              <s:param name="name">RoseIndia</s:param>
              <s:property value="%{name}" /><br>
          </s:bean>


          date tag

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/date-tag.shtml

            private Date currentDate;
            public String execute() throws Exception{
              setCurrentDate(new Date());
              return SUCCESS;
            }

          <s:date name="currentDate" format="MM/dd/yy" />

          <s:date name="currentDate" format="MM/dd/yy hh:mm" />

          <s:date name="currentDate" format="MM/dd/yy hh:mm:ss" />

          Nice Date (Current Date & Time):<s:date name="currentDate" nice="false" />

          Nice Date:<s:date name="currentDate" nice="true" />


           


          include tage

          是不是可以替換frame

          <body>
              <h1><span style="background-color: #FFFFcc">Include Tag (Data Tags) Example!</span></h1>
                <s:include value="myBirthday.jsp" />
            </body>


          param tag

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/param-tag.shtml

          <ui:component>
                  <ui:param name="empname">Vinod</ui:param><br>
                  <ui:param name="empname">Amit</ui:param><br>
                  <ui:param name="empname">Sushil</ui:param>
          </ui:component>


          Case 1. <param name="empname">Amit</param>  Here the value would be evaluated to the stack as a java.lang.String object.
          Case 2. <param name="empname" value="Vinod"/> Here the value would be evaluated to the stack as a java.lang.Object object.


          set tag

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/set-tag.shtml


           

          set tag給指定范圍內的變量賦值,得到name-value值對
          賦值:<s:set name="technologyName" value="%{'Java'}"/>
          調用:Technology Name: <s:property value="#technologyName"/>

          set tag is used to assign a value to a variable in a specified scope. The parameters name and value in the tag <s:set name="technologyName" value="%{'Java'}"/> acts as the name-value pair. Here we set the parameters as name="technologyName" value="Java".

          Text Tag

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/text-tag.shtml


           

          struts.xml 文件中定義

          <action name="textTag" class="net.roseindia.textTag">
                 <result>/pages/genericTags/textTag.jsp</result>
          </action>


          在textTag.java文件所在包下,創建一個package.properties,內容如下:

          webname1 = http://www.RoseIndia.net
          webname2 = http://www.javajazzup.com
          webname3 = http://www.newstrackindia.com


           

          在jsp文件調用,如下,前三行顯示package.properties對應信息;第四行顯示Vinod, Amit, Sushil, .......;最后一行empname

          <s:text name="webname1"></s:text><br>
          <s:text name="webname2"></s:text><br>
          <s:text name="webname3"></s:text><br>
          <s:text name="empname">Vinod, Amit, Sushil, .......</s:text><br>
          <s:text name="empname"></s:text>

          property tag

          參考:http://www.roseindia.net/struts/struts2/struts2controltags/property-tag.shtml


           

          定義個JavaBean

          public class companyName {
           
            private String name;

            public void setName(String name){
              this.name =name ;
            }

            public String getName(){
              return name;
            }
          }


           

          第二行給companyName的name屬性賦值;第三行顯示該值(RoseIndia),相當于調用了getName()方法;,

          <s:bean name="net.roseindia.companyName" id="uid">
          <s:param name="name">RoseIndia</s:param>
            <s:property value="%{name}" /><br>
          </s:bean>
          <!-- Default value -->
          <s:property value="name" default="Default Value" />


          <s:property value="%{name}" /> it prints the result of myBean's getMyBeanProperty() method.
          <s:property value="name" default="Default Value" /> it prints the result of companyName's
          getName() method and if it is null, print 'a default value' instead
          .

           

           

          posted @ 2007-12-30 19:43 水仁圭 閱讀(3641) | 評論 (0)編輯 收藏

          Struts 2 中Session的用法

          在ActionSupport子類的execute方法中存儲session
          Map session = ActionContext.getContext().getSession();
          session.put("logged-in","true");

           

          同樣在execute方法中,可以清除session變量
          Map session = ActionContext.getContext().getSession();
          session.remove("logged-in");

           

          在jsp的head部分引入css文件
          <head>
               <link href="<s:url value="/css/main.css"/>" rel="stylesheet" type="text/css"/> 
          </head>

          在jsp訪問session
          session Time: </b><%=new Date(session.getLastAccessedTime())%>

          <a href="<%= request.getContextPath() %>/roseindia/logout.action">Logout</a>

           jsp中使用struts-tag訪問session變量
          <s:if test="#session.login != 'admin'">
           <jsp:forward page="/pages/uiTags/Login.jsp" /> 
          </s:if>

          posted @ 2007-12-30 18:02 水仁圭 閱讀(5634) | 評論 (3)編輯 收藏

          2007年12月28日

          Java對象數組的強制轉換問題

          Java子類對象可以強制轉換為父類對象,但是子類對象數字不能強制轉換為父類對象數組
          如下:

          public void test(Number n){...}

          test(new Float(2)); // 這是正確的

          public void test2(Number n[]){...}

          Float t[] = {new Float(5),
          new Float(2),};

          test2(t); //這是編譯不通過的,會出現不可轉換的類型錯誤

          posted @ 2007-12-28 11:52 水仁圭 閱讀(1880) | 評論 (0)編輯 收藏

          TestLoginWeb

          01 /**
          02 * 本程序可以模擬web登錄。向服務器端提交數據。
          03 * 1、向服務器post多個參數時,如何做?
          04 * 2、如何取得一個連接的Cookie和sessionId?
          05 * 3、如何使用sessionId訪問一個網站?
          06 */
          07
          08 import java.io.BufferedReader;
          09 import java.io.IOException;
          10 import java.io.InputStreamReader;
          11 import java.io.OutputStream;
          12 import java.net.HttpURLConnection;
          13 import java.net.URL;
          14
          15
          16 public class TestLoginWeb {
          17
          18 public static void main(String args[]) throws IOException {
          19
          20 URL url = new URL("http://localhost:8080/backgroundH/login.jsp");
          21 URL url1 = new URL("http://localhost:8080/backgroundH/execute.jsp");
          22 HttpURLConnection huc = (HttpURLConnection) url.openConnection();
          23
          24 // 設置允許output
          25 huc.setDoOutput(true);
          26 // 設置為post方式
          27 huc.setRequestMethod("POST");
          28 huc.setRequestProperty("user-agent", "mozilla/4.7 [en] (win98; i)");
          29
          30 OutputStream os = huc.getOutputStream();
          31 // 多個參數的輸出時,需要用&連接,并轉換成bytes
          32 os.write("name=gaolei".getBytes("gbk"));
          33 os.close();
          34
          35 BufferedReader br = new BufferedReader(
          36 new InputStreamReader(huc.getInputStream()));
          37
          38 huc.connect();
          39 String line = br.readLine();
          40
          41 while (line != null) {
          42 System.out.println(line);
          43 line = br.readLine();
          44 }
          45
          46 // 取得cookie
          47 String cookieval = huc.getHeaderField("set-cookie");
          48
          49 System.out.println(cookieval);
          50 String sessionid = null;
          51
          52 // 取得cookie,這段代碼對于不同網站不同,因為有的網站有多個session標識
          53 if (cookieval != null) {
          54 sessionid = cookieval.substring(0, cookieval.indexOf(";"));
          55 }
          56
          57 huc.disconnect();
          58 huc = null;
          59
          60 HttpURLConnection huc1 = (HttpURLConnection) url1.openConnection();
          61 // 使用sessionId訪問一個網站
          62 huc1.setRequestProperty("cookie", sessionid);
          63 // 設置允許output
          64 huc1.setDoOutput(true);
          65 // 設置為post方式
          66 huc1.setRequestMethod("POST");
          67 huc1.setRequestProperty("user-agent", "mozilla/4.7 [en] (win98; i)");
          68
          69 OutputStream os1 = huc1.getOutputStream();
          70
          71 os1.write("value=1234567890".getBytes("gbk"));
          72 os1.close();
          73
          74 BufferedReader br1 = new BufferedReader(
          75 new InputStreamReader(huc1.getInputStream()));
          76
          77 huc1.connect();
          78 line = br1.readLine();
          79 while (line != null) {
          80 System.out.println(line);
          81 line = br1.readLine();
          82 }
          83 huc1.disconnect();
          84
          85 }
          86 }
          87

          第31行,關于POST多個參數到服務器端,可以參照下面代碼:

          StringBuffer params = new StringBuffer("typeid=");
          params.append(args[0]).append("&");
          params.append("keyword=").append(args[1]);

          os.write(params.toString().getBytes("gb2312"));

          posted @ 2007-12-28 11:25 水仁圭 閱讀(200) | 評論 (0)編輯 收藏

          主站蜘蛛池模板: 余江县| 日土县| 绥滨县| 辽阳市| 南安市| 海原县| 金溪县| 南华县| 板桥市| 丹棱县| 土默特左旗| 鸡西市| 广元市| 韩城市| 张家口市| 将乐县| 汤阴县| 阜阳市| 黄平县| 夏邑县| 芒康县| 遵义市| 于都县| 鸡西市| 榕江县| 尤溪县| 武清区| 南宁市| 益阳市| 科技| 克拉玛依市| 高陵县| 鄂伦春自治旗| 屏东县| 海阳市| 当阳市| 紫金县| 五峰| 容城县| 蚌埠市| 永顺县|