欧美黄色片免费观看,精品一区二区三区影院在线午夜,久久福利影视http://www.aygfsteel.com/keweibo/category/25070.htmlAs long as you are there to lead me ,I won't lose my way zh-cnThu, 20 Sep 2007 09:01:12 GMTThu, 20 Sep 2007 09:01:12 GMT60在Struts2中實現文件上傳(二)http://www.aygfsteel.com/keweibo/articles/146616.htmlKEKEWed, 19 Sep 2007 14:14:00 GMThttp://www.aygfsteel.com/keweibo/articles/146616.htmlhttp://www.aygfsteel.com/keweibo/comments/146616.htmlhttp://www.aygfsteel.com/keweibo/articles/146616.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/146616.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/146616.html

在Struts2中實現文件上傳(二)

 發布者:[IT電子教育門戶]   

發布運行應用程序,在瀏覽器地址欄中鍵入:http://localhost:8080/Struts2_Fileupload/FileUpload.jsp,出現圖示頁面:

 
清單7 FileUpload頁面

選擇圖片文件,填寫Caption并按下Submit按鈕提交,出現圖示頁面:

 
清單8 上傳成功頁面

更多配置
在運行上述例子,如果您留心一點的話,應該會發現服務器控制臺有如下輸出:

Mar 20 , 2007 4 : 08 : 43 PM org.apache.struts2.dispatcher.Dispatcher getSaveDir
INFO: Unable to find 'struts.multipart.saveDir' property setting. Defaulting to javax.servlet.context.tempdir
Mar 20 , 2007 4 : 08 : 43 PM org.apache.struts2.interceptor.FileUploadInterceptor intercept
INFO: Removing file myFile C:\Program Files\Tomcat 5.5 \work\Catalina\localhost\Struts2_Fileupload\upload_251447c2_1116e355841__7ff7_00000006.tmp 清單9 服務器控制臺輸出
上述信息告訴我們,struts.multipart.saveDir沒有配置。struts.multipart.saveDir用于指定存放臨時文件的文件夾,該配置寫在struts.properties文件中。例如,如果在struts.properties文件加入如下代碼:

struts.multipart.saveDir = /tmp 清單10 struts配置
這樣上傳的文件就會臨時保存到你根目錄下的tmp文件夾中(一般為c:\tmp),如果此文件夾不存在,Struts 2會自動創建一個。

錯誤處理
上述例子實現的圖片上傳的功能,所以應該阻止用戶上傳非圖片類型的文件。在Struts 2中如何實現這點呢?其實這也很簡單,對上述例子作如下修改即可。

首先修改FileUpload.jsp,在<body>與<s:form>之間加入“<s:fielderror />”,用于在頁面上輸出錯誤信息。

然后修改struts.xml文件,將Action fileUpload的定義改為如下所示:

        < action name ="fileUpload" class ="tutorial.FileUploadAction" >
            < interceptor-ref name ="fileUpload" >
                < param name ="allowedTypes" >
                    image/bmp,image/png,image/gif,image/jpeg
                </ param >
            </ interceptor-ref >
            < interceptor-ref name ="defaultStack" />           
            < result name ="input" > /FileUpload.jsp </ result >
            < result name ="success" > /ShowUpload.jsp </ result >
        </ action > 清單11 修改后的配置文件
顯而易見,起作用就是fileUpload攔截器的allowTypes參數。另外,配置還引入defaultStack它會幫我們添加驗證等功能,所以在出錯之后會跳轉到名稱為“input”的結果,也即是FileUpload.jsp。

發布運行應用程序,出錯時,頁面如下圖所示:

 
清單12 出錯提示頁面

上面的出錯提示是Struts 2默認的,大多數情況下,我們都需要自定義和國際化這些信息。通過在全局的國際資源文件中加入“struts.messages.error.content.type.not.allowed=The file you uploaded is not a image”,可以實現以上提及的需求。對此有疑問的朋友可以參考我之前的文章《在Struts 2.0中國際化(i18n)您的應用程序》。

實現之后的出錯頁面如下圖所示:

 
清單13 自定義出錯提示頁面

同樣的做法,你可以使用參數“maximumSize”來限制上傳文件的大小,它對應的字符資源名為:“struts.messages.error.file.too.large”。

字符資源“struts.messages.error.uploading”用提示一般的上傳出錯信息。

多文件上傳
與單文件上傳相似,Struts 2實現多文件上傳也很簡單。你可以將多個<s:file />綁定Action的數組或列表。如下例所示。

< s:form action ="doMultipleUploadUsingList" method ="POST" enctype ="multipart/form-data" >
    < s:file label ="File (1)" name ="upload" />
    < s:file label ="File (2)" name ="upload" />
    < s:file label ="FIle (3)" name ="upload" />
    < s:submit />
</ s:form > 清單14 多文件上傳JSP代碼片段
如果你希望綁定到數組,Action的代碼應類似:

     private File[] uploads;
     private String[] uploadFileNames;
     private String[] uploadContentTypes;

     public File[] getUpload()  { return this .uploads; }
      public void setUpload(File[] upload)  { this .uploads = upload; }
 
      public String[] getUploadFileName()  { return this .uploadFileNames; }
      public void setUploadFileName(String[] uploadFileName)  { this .uploadFileNames = uploadFileName; }
 
      public String[] getUploadContentType()  { return this .uploadContentTypes; }
      public void setUploadContentType(String[] uploadContentType)  { this .uploadContentTypes = uploadContentType; } 清單15 多文件上傳數組綁定Action代碼片段
如果你想綁定到列表,則應類似:

     private List < File > uploads = new ArrayList < File > ();
     private List < String > uploadFileNames = new ArrayList < String > ();
     private List < String > uploadContentTypes = new ArrayList < String > ();

     public List < File > getUpload()  {
         return this .uploads;
    }
      public void setUpload(List < File > uploads)  {
         this .uploads = uploads;
    }
 
      public List < String > getUploadFileName()  {
         return this .uploadFileNames;
    }
      public void setUploadFileName(List < String > uploadFileNames)  {
         this .uploadFileNames = uploadFileNames;
    }
 
      public List < String > getUploadContentType()  {
         return this .uploadContentTypes;
    }
      public void setUploadContentType(List < String > contentTypes)  {
         this .uploadContentTypes = contentTypes;
    } 清單16 多文件上傳列表綁定Action代碼片段
總結
在Struts 2中實現文件上傳的確是輕而易舉,您要做的只是使用<s:file />與Action的屬性綁定。這又一次有力地證明了Struts 2的簡單易用。



KE 2007-09-19 22:14 發表評論
]]>
在Struts2中實現文件上傳(一)http://www.aygfsteel.com/keweibo/articles/146615.htmlKEKEWed, 19 Sep 2007 14:11:00 GMThttp://www.aygfsteel.com/keweibo/articles/146615.htmlhttp://www.aygfsteel.com/keweibo/comments/146615.htmlhttp://www.aygfsteel.com/keweibo/articles/146615.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/146615.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/146615.html

在Struts2中實現文件上傳(一)

轉自:http://www.mldn.cn/articleview/2007-8-22/article_view_2245.htm

前一陣子有些朋友在電子郵件中問關于Struts 2實現文件上傳的問題, 所以今天我們就來討論一下這個問題。

實現原理
Struts 2是通過Commons FileUpload文件上傳。Commons FileUpload通過將HTTP的數據保存到臨時文件夾,然后Struts使用fileUpload攔截器將文件綁定到Action的實例中。從而我們就能夠以本地文件方式的操作瀏覽器上傳的文件。

具體實現
前段時間Apache發布了Struts 2.0.6 GA,所以本文的實現是以該版本的Struts作為框架的。以下是例子所依賴類包的列表:

依賴類包的列表 
清單1 依賴類包的列表

首先,創建文件上傳頁面FileUpload.jsp,內容如下:

<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
    < title > Struts 2 File Upload </ title >
</ head >
< body >
    < s:form action ="fileUpload" method ="POST" enctype ="multipart/form-data" >
        < s:file name ="myFile" label ="Image File" />
        < s:textfield name ="caption" label ="Caption" />       
        < s:submit />
    </ s:form >
</ body >
</ html > 清單2 FileUpload.jsp
在FileUpload.jsp中,先將表單的提交方式設為POST,然后將enctype設為multipart/form-data,這并沒有什么特別之處。接下來,<s:file/>標志將文件上傳控件綁定到Action的myFile屬性。

其次是FileUploadAction.java代碼:

 package tutorial;

 import java.io.BufferedInputStream;
 import java.io.BufferedOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.util.Date;

 import org.apache.struts2.ServletActionContext;

 import com.opensymphony.xwork2.ActionSupport;

 public class FileUploadAction extends ActionSupport  {
     private static final long serialVersionUID = 572146812454l ;
     private static final int BUFFER_SIZE = 16 * 1024 ;
   
     private File myFile;
     private String contentType;
     private String fileName;
     private String imageFileName;
     private String caption;
   
     public void setMyFileContentType(String contentType)  {
         this .contentType = contentType;
    }
   
     public void setMyFileFileName(String fileName)  {
         this .fileName = fileName;
    }
       
     public void setMyFile(File myFile)  {
         this .myFile = myFile;
    }
   
     public String getImageFileName()  {
         return imageFileName;
    }
   
     public String getCaption()  {
         return caption;
    }
 
      public void setCaption(String caption)  {
         this .caption = caption;
    }
   
     private static void copy(File src, File dst)  {
         try  {
            InputStream in = null ;
            OutputStream out = null ;
             try  {               
                in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
                out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
                 byte [] buffer = new byte [BUFFER_SIZE];
                 while (in.read(buffer) > 0 )  {
                    out.write(buffer);
                }
             } finally  {
                 if ( null != in)  {
                    in.close();
                }
                  if ( null != out)  {
                    out.close();
                }
            }
         } catch (Exception e)  {
            e.printStackTrace();
        }
    }
   
     private static String getExtention(String fileName)  {
         int pos = fileName.lastIndexOf( " . " );
         return fileName.substring(pos);
    }
 
    @Override
     public String execute()      {       
        imageFileName = new Date().getTime() + getExtention(fileName);
        File imageFile = new File(ServletActionContext.getServletContext().getRealPath( " /UploadImages " ) + " / " + imageFileName);
        copy(myFile, imageFile);
         return SUCCESS;
    }
   
} 清單3 tutorial/FileUploadAction.java
在FileUploadAction中我分別寫了setMyFileContentType、setMyFileFileName、setMyFile和setCaption四個Setter方法,后兩者很容易明白,分別對應FileUpload.jsp中的<s:file/>和<s:textfield/>標志。但是前兩者并沒有顯式地與任何的頁面標志綁定,那么它們的值又是從何而來的呢?其實,<s:file/>標志不僅僅是綁定到myFile,還有myFileContentType(上傳文件的MIME類型)和myFileFileName(上傳文件的文件名,該文件名不包括文件的路徑)。因此,<s:file name="xxx" />對應Action類里面的xxx、xxxContentType和xxxFileName三個屬性。

FileUploadAction作用是將瀏覽器上傳的文件拷貝到WEB應用程序的UploadImages文件夾下,新文件的名稱是由系統時間與上傳文件的后綴組成,該名稱將被賦給imageFileName屬性,以便上傳成功的跳轉頁面使用。

下面我們就來看看上傳成功的頁面:

<% @ page language = " java " contentType = " text/html; charset=utf-8 " pageEncoding = " utf-8 " %>
<% @ taglib prefix = " s " uri = " /struts-tags " %>

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
< html xmlns ="http://www.w3.org/1999/xhtml" >
< head >
    < title > Struts 2 File Upload </ title >
</ head >
< body >
    < div style ="padding: 3px; border: solid 1px #cccccc; text-align: center" >
        < img src ='UploadImages/<s:property value ="imageFileName" /> ' />
        < br />
        < s:property value ="caption" />
    </ div >
</ body >
</ html > 清單4 ShowUpload.jsp
ShowUpload.jsp獲得imageFileName,將其UploadImages組成URL,從而將上傳的圖像顯示出來。

然后是Action的配置文件:

<? xml version="1.0" encoding="UTF-8" ?>

<! DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd" >

< struts >
    < package name ="fileUploadDemo" extends ="struts-default" >
        < action name ="fileUpload" class ="tutorial.FileUploadAction" >
            < interceptor-ref name ="fileUploadStack" />
            < result name ="success" > /ShowUpload.jsp </ result >
        </ action >
    </ package >
</ struts > 清單5 struts.xml
fileUpload Action顯式地應用fileUploadStack的攔截器。

最后是web.xml配置文件:

<? xml version="1.0" encoding="UTF-8" ?>
< web-app id ="WebApp_9" 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" >

    < display-name > Struts 2 Fileupload </ display-name >

    < filter >
        < filter-name > struts-cleanup </ filter-name >
        < filter-class >
            org.apache.struts2.dispatcher.ActionContextCleanUp
        </ filter-class >
    </ filter >
   
    < filter >
        < filter-name > struts2 </ filter-name >
        < filter-class >
            org.apache.struts2.dispatcher.FilterDispatcher
        </ filter-class >
    </ filter >
   
    < filter-mapping >
        < filter-name > struts-cleanup </ filter-name >
        < url-pattern > /* </ url-pattern >
    </ filter-mapping >

    < filter-mapping >
        < filter-name > struts2 </ filter-name >
        < url-pattern > /* </ url-pattern >
    </ filter-mapping >

    < welcome-file-list >
        < welcome-file > index.html </ welcome-file >
    </ welcome-file-list >

</ web-app >



KE 2007-09-19 22:11 發表評論
]]>
struts標簽使用舉例--logic篇http://www.aygfsteel.com/keweibo/articles/145473.htmlKEKESun, 16 Sep 2007 02:24:00 GMThttp://www.aygfsteel.com/keweibo/articles/145473.htmlhttp://www.aygfsteel.com/keweibo/comments/145473.htmlhttp://www.aygfsteel.com/keweibo/articles/145473.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/145473.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/145473.html          該標簽是用來判斷是否為空的。如果為空,該標簽體中嵌入的內容就會被處理。該標簽用于以下情況:

         1)當Java對象為null時;

         2)當String對象為""時;

         3)當java.util.Collection對象中的isEmpty()返回true時;

         4)當java.util.Map對象中的isEmpty()返回true時。
          eg. 
            <logic:empty   name="userList">   
              ...   
           </logic:empty> 
           該句等同于:
           if   (userList.isEmpty())   {   
                 ...   
           }   
   2.  logic:notEmpty
          該標簽的應用正好和logic:empty標簽相反,略。
   3. logic:equal
          該標簽為等于比較符。
          eg1. 比較用戶的狀態屬性是否1,若為1,輸出"啟用";
                 <logic:equal   name="user"   property="state"   value="1">
                     啟用
                 </logic:equal>
         eg2. 如果上例中的value值是動態獲得的,例如需要通過bean:write輸出,因struts不支持標簽嵌套,可采用EL來解決該問題。
                <logic:equal   name="charge"   property="num"   value="${business.num}">   
                    ......
                </logic:equal>
    4. logic:notEqual
          該標簽意義與logic:equal相反,使用方法類似,略。
    5. logic:forward
          該標簽用于實現頁面導向,查找配置文件的全局forward。
          eg. <logic:forward name="index"/>
    6. logic:greaterEqual
          為大于等于比較符。
          eg. 當某學生的成績大于等于90時,輸出“優秀”:
               <logic:greaterEqual name="student" property="score" value="90">
                  優秀
            </logic:greaterEqual>
    7. logic:greaterThan
         
此為大于比較符,使用方法同logic:greaterEqual,略;
    8. logic:lessEqual
         
此為小于等于比較符,使用方法同logic:greaterEqual,略;
    9. logic:lessThan
         
此為小于比較符,使用方法同logic:greaterEqual,略;
    10. logic:match
         
此標簽比較對象是否相等;
          eg1. 檢查在request范圍內的name屬性是否包含"amigo"串: 
            <logic:match name="name" scope="request" value="amigo">
                  <bean:write name="name"/>中有一個“amigo”串。
            </logic:match>
         eg2. 檢查在request范圍內的name屬性是否已“amigo”作為起始字符串:
           <logic:match name="name" scope="request" value="amigo" location="start">
               <bean:write name="name"/>以“amigo”作為起始字符串。
            </logic:match>
         eg3. 
            <logic:match header="user-agent" value="Windows">
               你運行的是Windows系統
            </logic:match>
    11.  logic:notMatch

 

 

          此標簽用于比較對象是否不相同,與logic:match意義相反,使用方法類似,略。
     12. logic:messagePresent
          該標簽用于判斷ActionMessages/ActionErrors對象是否存在;
          eg. 如果存在error信息,將其全部輸出:
               <logic:messagePresent property="error"> 
                  <html:messages property="error" id="errMsg" > 
                        <bean:write name="errMsg"/> 
                  </html:messages>   
               </logic:messagePresent >
     13. logic:messagesNotPresent
          該標簽用于判斷ActionMessages/ActionErrors對象是否不存在,使用方法與logic:messagePresent類似,略
      14. logic:present
           此標簽用于判斷request對象傳遞參數是否存在。
           eg1. user對象和它的name屬性在request中都存在時,輸出相應字符串:
              <logic:present name="user" property="name">
                  user對象和該對象的name屬性都存在
            </logic:present> 
          eg2. 若有一個名字為“user”的JavaBean,輸出對應字符串:
             <logic:present name="user" >
                  有一個名字為“user”的JavaBean。
            </logic:present>
          eg3. 
            <logic:present header="user-agent">
                  we got a user-agent header.
            </logic:present>
      15. logic:notPresent
           此標簽用于判斷request對象傳遞參數是否不存在,意義與了logic:present相反,使用方法類似,略。
      16. logic:redirect
           該標簽用于實現頁面轉向,可傳遞參數。
           eg1. <logic:redirect href="http://www.chinaitlab.com"/>
       
       17. logic:iterator
            用于顯示列表為collection的值(List ,ArrayList,HashMap等)。
            eg1. 逐一輸出用戶列表(userlList)中用戶的姓名:
               <logic:iterate  id="user" name="userList">
                  <bean:write name="user" property="name"/><br>
               </logic:iterate>
            eg2. 從用戶列表中輸出從1開始的兩個用戶的姓名
               <logic:iterate  id="user" name="userList" indexId="index"  offset="1" length="2">
                  <bean:write name="index"/>.<bean:write name="user" property="name"/><br>
               </logic:iterate>
            eg3. logic:iterator標簽的嵌套舉例
                <logic:iterate id="user" indexId="index" name="userList">
                       <bean:write name="index"/>. <bean:write name="user" property="name"/><br>
                       <logic:iterate id="address" name="user" property="addressList" length="3" offset="1">
                           <bean:write name="address"/><br>
                       </logic:iterate>
               </logic:iterate>



KE 2007-09-16 10:24 發表評論
]]>
應用中異常的處理(二)http://www.aygfsteel.com/keweibo/articles/140663.htmlKEKETue, 28 Aug 2007 13:19:00 GMThttp://www.aygfsteel.com/keweibo/articles/140663.htmlhttp://www.aygfsteel.com/keweibo/comments/140663.htmlhttp://www.aygfsteel.com/keweibo/articles/140663.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/140663.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/140663.html業務異常的設計

  業務異常的層次結構設計在開發中也是非常重要的要作,業務異常體系結構的設計方法將直接影響
到異常處理的方法.
  對于異常系統的結構通常會被劃分為三個層次,第一層為異常的基類,第二層為功能層或者模塊層,
第三層為業務異常層,層與層之間是父子工的繼承關系.
  對于一個通用的異常系統而言,通常會定義一個異常基類,假設是BaseException,該類繼承自RuntimeException
之所以將業務異常的基類定義為RuntimeException,是因為業務異常是否需要開發人員在開發過程中進行捕獲的
對于業務異常的捕獲交給系統的框架或者表示層來完成.
  接下來,在BaseException的基礎之上,還要為應用中的每個層次定義一個異常基類.例如,業務層的異常
可以定義為BusinessException,持久層的異常可以定義為DAOException等.當然,這一層次的異常也可以按照
功能或者模塊來進行劃分,劃分的方式主要依賴于頂層對異常的處理方法.
  最后,就是為每一個業務異常定義相應的業務對象.另外,為減少異常對象的數量,在這一層也可以采取錯誤
代碼,使得頂層的攔截程序可以依據錯誤代碼來得到相應的錯誤信息.

異常處理方法

  Servlet容器中異常的處理
在web.xml文件中進行異常處理的配置是通過<error-page>元素來進行的,它支持兩種類型的異常攔截.

<error-page>
 <error-code>404</error-code>
 <location>/error/notFound.jsp</location>
</error-page>

<error-page>
 <error-type>java.lang.NullPointException</error-type>
 <location>/error/nullPointer.jsp</location>
</error-page>

從JSP 2.0開始,除了在錯誤頁面中可以使用綁定到request的exception對象外,還增加了一個名稱為
errorData的綁定到pageContext的對象,該對象是javax.servlet.jsp.ErrorData類的實例,它可以當做
一個普通的Bean來使用,通過它的屬性可以了解到異常的更多信息.
其屬性如下:
屬性      類型      描述
requestURI   String     發生請求失敗的URI
servletName   String     發生錯誤的Servlet或者JSP頁面的名稱
statueCode   int       發生錯誤的狀態碼
throwable    Throwable    導致當前錯誤的異常
例如:
...
<title>404狀態碼錯誤的頁面</title>
...
<jsp:useBean id="now" class="java.util.Date" />
發生異常的時間:${now}<br>
請求的地址: ${pageContext.errorData.requestURI }<br>
錯誤狀態碼: ${pageContext.errorData.statueCode }<br>
異常:    ${pageContext.errorData.throwable }
...

自定義異常頁面

  自己在JSP頁面中的定義將會覆蓋在web.xml中的定義
  自定義異常頁面的方法如下
<%@ page errorPage="/error/errorPage.jsp" %>

 



KE 2007-08-28 21:19 發表評論
]]>
應用中異常的處理(一)http://www.aygfsteel.com/keweibo/articles/140656.htmlKEKETue, 28 Aug 2007 12:49:00 GMThttp://www.aygfsteel.com/keweibo/articles/140656.htmlhttp://www.aygfsteel.com/keweibo/comments/140656.htmlhttp://www.aygfsteel.com/keweibo/articles/140656.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/140656.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/140656.html應用中異常的處理的原則

  在處理應用中的異常時,通常可以將應用中所遇到的異常分為兩大類,一種是業務異常,一種是非業務異常.
  業務異常是指在進行正常的業務處理時,由于某些業務的特殊需求而導致處理不能繼續所拋出的異常,這種異常
常是由開發人員所定義,它屬于可以預知的異常. 
  非業務異常是指在正常情況下所產生的異常.例如,由于網絡故障而導致無法訪問數據庫,必要的配置文件不存在
等情況下所產生的異常都屬于非業務異常.非業務異常是不可預知的.

業務異常的處理

  在業務層或者業務處理方法中拋出異常,在表示層攔截異常,并將異常以友好的方式反饋給操作者,以
便其可以提示信息正確的完成業務功能處理.在這里要注意的是,在表示層攔截異常不是只需要針對每個異常
都進行攔截和處理,而是是充分利用框架來進行統一的處理.最好做到正常的處理流程中看不到任何異常處理.

非業務異常的處理

  在應用的框架中進行統一的攔截和處理,在開發中不需要進行任何處理.對于非業務異常的處理結果
通常是返回到專門的錯誤頁面,給出很泛泛的提示信息,表明系統發生不可預知的異常,并請與管理員聯系
此類信息.

注:本文來自 struts,spring,hibernate集成開發 一書 



KE 2007-08-28 20:49 發表評論
]]>
利用公共的Action實現用戶合法性的校驗http://www.aygfsteel.com/keweibo/articles/140649.htmlKEKETue, 28 Aug 2007 12:23:00 GMThttp://www.aygfsteel.com/keweibo/articles/140649.htmlhttp://www.aygfsteel.com/keweibo/comments/140649.htmlhttp://www.aygfsteel.com/keweibo/articles/140649.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/140649.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/140649.html利用公共的Action實現用戶合法性的校驗

  在這里,我們可以通過實現一個公共的Action并增加相應的權限驗證功能來實現用戶權限的校驗工作.
這樣,在進行業務功能開發的時候,所有需要執行權限校驗的Action都需要繼承自此公共的Action.
下面是一個簡單的例子
具有校驗功能的Action(SecureAction.java)
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package dgut.ke.struts.secure;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

/**
 * MyEclipse Struts
 * Creation date: 08-28-2007
 *
 * XDoclet definition:
 * @struts.action validate="true"
 */
public abstract class SecureAction extends Action {
 /*
  * Generated Methods
  */

 /**
  * Method execute
  * @param mapping
  * @param form
  * @param request
  * @param response
  * @return ActionForward
  */
 public final ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)throws Exception {
  HttpSession session = request.getSession();
  String userId = (String)session.getAttribute("SESSION.USER");
  if(userId==null)
   return (mapping.findForward("isNullSession"));
  else
   return doExecute(mapping,form,request,response);
 }
 
 public abstract ActionForward doExecute(ActionMapping mapping,
             ActionForm form,
             HttpServletRequest request,
             HttpServletResponse response)
 throws Exception;
    
}
下面編寫一個普通的Action(isNullSessionAction.java)繼承自此公共Action
/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package dgut.ke.struts.secure;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class IsNullSessionAction extends SecureAction {

 @Override
 /*重寫類中的方法*/
 public ActionForward doExecute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
  //通過父類的權限驗證則該方法會被執行
  return mapping.findForward("success");
 }
}
struts-config.xml中的相關配置
  <action path="/isNullSession" type="dgut.ke.struts.secure.IsNullSessionAction">
     <forward name="success" path="/success.jsp"></forward>
     <forward name="isNullSession" path="/index.jsp"></forward>
  </action>
  <action path="/secureAction" type="dgut.ke.struts.secure.SecureActionAction"/>



KE 2007-08-28 20:23 發表評論
]]>
使用Struts的PlugIn進行Web應用的擴展http://www.aygfsteel.com/keweibo/articles/140637.htmlKEKETue, 28 Aug 2007 11:18:00 GMThttp://www.aygfsteel.com/keweibo/articles/140637.htmlhttp://www.aygfsteel.com/keweibo/comments/140637.htmlhttp://www.aygfsteel.com/keweibo/articles/140637.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/140637.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/140637.html使用Struts的PlugIn進行Web應用的擴展

  Struts提供了PlugIn的方式來擴展Struts的功能,這種方式的擴展適合于實現Struts啟動或者
停止時需要執行的某些特殊處理的情況,可以方便地實現Web應用啟動時的系統初始化工作以及在Web
應用卸載時的資源釋放工作,它不能實現針對每個用戶請求的處理功能.
  開發一個Struts的PlugIn需要以下兩個步驟:
(1)實現Struts定義的PlugIn接口,其中的init()方法將在應用啟動時被調用,而destory()方法將在服務
終止時被調用.
(2)在Struts的配置文件中配置該PlugIn以及設置的初始化參數.Struts還允許為PlugIn定義一些參數,
在默認的情況下,這些參數必須作為PlugIn屬性的形式出現,并且為每個參數提供符合javabean規范
的setter方法,而這些參數在struts的配置文件中進行.
  基本的配置形式如下:
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
 <set-property property="pathnames"
        value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml"/>
</plug-in>
下面是一個例子.在服務器啟動和停止時輸出系統的時間.
MyPlugIn.java

package dgut.ke.struts.plugIn;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;

public class MyPlugIn implements PlugIn {

 private String timePattern;
 public String getTimePattern() {
  return timePattern;
 }

 public void setTimePattern(String timePattern) {
  this.timePattern = timePattern;
 }

 public void destroy() {
  // TODO 自動生成方法存根
  DateFormat df = new SimpleDateFormat(getTimePattern());
  Calendar rightNow = Calendar.getInstance();
  Date now = rightNow.getTime();
  System.out.println("The service shutdown at --> "+df.format(now));
 }

 public void init(ActionServlet actionServlet, ModuleConfig moduleConfig)
   throws ServletException {
  DateFormat df = new SimpleDateFormat(getTimePattern());
  Calendar rightNow = Calendar.getInstance();
  Date now = rightNow.getTime();
  System.out.println("The service start at ---> "+df.format(now));

 }

}
相關配置
<plug-in className="dgut.ke.struts.plugIn.MyPlugIn">
    <set-property property="timePattern" value="yyyy-MM-dd" />
  </plug-in>



KE 2007-08-28 19:18 發表評論
]]>
ForwardAction和IncludeActionhttp://www.aygfsteel.com/keweibo/articles/139960.htmlKEKEMon, 27 Aug 2007 07:18:00 GMThttp://www.aygfsteel.com/keweibo/articles/139960.htmlhttp://www.aygfsteel.com/keweibo/comments/139960.htmlhttp://www.aygfsteel.com/keweibo/articles/139960.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/139960.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/139960.htmlForwardAction

  基于struts的WEB應用系統通常情況下應該避免JSP頁面之間的跳轉.因為這樣跳轉的用戶請求沒有
經過Struts的處理,會導致很多在Struts框架中進行的處理不起的作用.
  對于每個用戶的請求,struts的RequestProcessor將會進行一系列的處理,其中包括了國際化,權限
緩存等多方面.如果采用頁面之間的直接跳轉會導致很多內容都需要自己處理.

在struts中配置ForwardAction
  <action path="home"
      type="org.apache.struts.actions.ForwardAction"
      parameter="/index.jsp"
  />
  其中path屬性是Action的匹配路徑,type屬性說明實現Action的類,parameter屬性用于指定往哪轉發
也就是轉發的目的URI.這三個屬性是必須的,其它的可以省略.
forward屬性和ForwardAction
  使用forward進行頁面跳轉的配置方法如下
  <action path="/home"
      forward="/index.jsp"
  />
  forward屬性和ForardAction在頁面中使用時是沒有區別的,并且在通常情況下struts對這兩種形式
的跳轉的處理也是相同的.但是使用自己的RequestProcessor并且覆蓋了父類的processForwardConfig()
方法時,這兩種方式就存在一定的區別了.

IncludeAction

  IncludeAction類的意義類似于ActionForward類,它和頁面中的<jsp:include>動作或Servlet中的
RequestDispatcher的include()方法執行的功能一樣的.在基于struts框架結構的應用中,最好不要在
<jsp:include>標記中直接引用另一個JSP頁面,而是通過IncludeAciton來實現頁面之間的引用,這樣比較
安全等等.
  IncludeAction的使用
IncludeAction的使用和Forward基本相同,在頁面中還可以通過<jsp:include>標記來調用.
<jsp:include page="/somePath/someAction.do" />
  IncludeAction的配置
  <action path="/include"
      type="org.apache.struts.actions.IncludeAction"
      parameter="/include.jsp"
  />
  include屬性和IncludeAction
  Struts也可以通過使用include屬性來在Action的配置文件中直接定義被引用的頁面.如
  <action path="/include"
      include="/include.jsp"
  />



KE 2007-08-27 15:18 發表評論
]]>
ActionForm中對集合屬性的處理http://www.aygfsteel.com/keweibo/articles/139821.htmlKEKEMon, 27 Aug 2007 03:09:00 GMThttp://www.aygfsteel.com/keweibo/articles/139821.htmlhttp://www.aygfsteel.com/keweibo/comments/139821.htmlhttp://www.aygfsteel.com/keweibo/articles/139821.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/139821.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/139821.htmlpackage com.ke.struts.bean;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;


public class ActionForm extends ActionForm {

 private List<String> friends = new ArrayList<String>();
 private static String[] skillLevels = new String[]{"Beginner","Intermediate","Advanced"};
 private Map<String,Object> skills = new HashMap<String,Object>();
 

public ActionErrors validate(ActionMapping mapping,
   HttpServletRequest request) {
  // TODO Auto-generated method stub
  return null;
 }
 public void reset(ActionMapping mapping, HttpServletRequest request) {

  this.friends.clear();
 }
 public Object getSkill(String key)
 {
  return skills.get(key);
 }
 public void setSkill(String key,Object value)
 {
  skills.put(key, value);
 }
 public Map getSkills()
 {
  return skills ;
 }
 public String[] getSkillLevels()
 {
  return skillLevels;
 }
 public List<String> getFriends() {
  return friends;
 }

 public void setFriends(List<String> friends) {
  this.friends = friends;
 }
 
 public void setFriend(int index,String friend)
 {
  if(this.friends.size() > index)
  {
   /*用指定的元素替代此列表中指定位置上的元素*/
   this.friends.set(index, friend);
  }
  else
  {
   while(this.friends.size() < index)
   {
    this.friends.add(null);
   }
   this.friends.add(index, friend);
  }
 }
 
 public String getFriend(int index)
 {
  if(this.friends.size() > index)
  {
   return (String)this.friends.get(index);
  }
  else
  {
   return null ;
  }
 }
}
輸入頁面
     Friend 1 :<html:text property="friend[0]"></html:text><br>   <!-- 調用setFriend(int index,String friend)-->
     Friend 2 :<html:text property="friend[1]"></html:text><br>
     Friend 3 :<html:text property="friend[2]"></html:text><br>
java skill: <html:select property="skill(java)">   <!-- 調用setSkill(String key,Object value) -->
                <html:options property="skillLevels"/>
              </html:select><br>
  jsp skill:<html:select property="skill(jsp)">
                <html:options property="skillLevels"/>
              </html:select><br>
  struts skill:<html:select property="skill(struts)">
                   <html:options property="skillLevels"/>
                 </html:select><br>

輸出頁面
    Friend 1:<bean:write name="ActionForm" property="friend[0]"/><br><!-- 調用getFriend(int index)-->
    Friend 2:<bean:write name="ActionForm" property="friend[1]"/><br>
    Friend 3:<bean:write name="ActionForm" property="friend[2]"/><br>
  java skill :<bean:write name="ActionForm" property="skill(java)"/><br><!-- 調用getSkill(String key) -->
  jsp skill :<bean:write name="ActionForm" property="skill(jsp)"/><br>
  struts skill :<bean:write name="ActionForm" property="skill(struts)"/>

 



KE 2007-08-27 11:09 發表評論
]]>
柱狀圖顯示http://www.aygfsteel.com/keweibo/articles/139803.htmlKEKEMon, 27 Aug 2007 02:41:00 GMThttp://www.aygfsteel.com/keweibo/articles/139803.htmlhttp://www.aygfsteel.com/keweibo/comments/139803.htmlhttp://www.aygfsteel.com/keweibo/articles/139803.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/139803.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/139803.html<%@ page language="java" contentType="text/html;charset=gbk"%>
<%@ taglib uri="

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>柱狀圖顯示頁面</title>
  </head>
  <body>
    <div align="center">
      <h3>Color Bar Chart (horizontal)</h3>
      <table width="60%">
        <c:forEach var="col" items="${weekWeather}">
          <tr>
            <td align="right" width="20%">${col.item }(${col.percent }%)</td>
            <td align="left" width="80%">
              <table width="100%" height="20">
                <tr>
                  <td width="${col.percent }%" bgcolor="#003366"></td>
                  <td width="${100-col.percent }%"></td>
                 </tr>
              </table>
        </c:forEach>
      </table>
      <hr>
      <h3>Color BAr Chart (vertical)</h3>
      <table width="300" height="500">
        <tr>
        <c:forEach var="row" items="${weekWeather }">
         <td>
          <table width="100%" height="100%">
             <tr>
               <td height="${100-row.percent }%"></td>
             </tr>
               <tr>
              <td height="${row.percent }%" bgcolor="#006633"></td>
            </tr>
            <tr>
              <td align="center">${row.item }(${row.percent }%)</td>
            </tr>
          </table>
      </td>
        </c:forEach>
        </tr>
      </table>
    </div>
  </body>
</html>



KE 2007-08-27 10:41 發表評論
]]>
struts中AtionErrors和ActionMessages的區別(轉)http://www.aygfsteel.com/keweibo/articles/138223.htmlKEKEMon, 20 Aug 2007 12:26:00 GMThttp://www.aygfsteel.com/keweibo/articles/138223.htmlhttp://www.aygfsteel.com/keweibo/comments/138223.htmlhttp://www.aygfsteel.com/keweibo/articles/138223.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/138223.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/138223.htmlstruts中AtionErrors和ActionMessages的區別

盡管Struts框架提供了有效的異常處理機制,但不能保證處理所有的錯誤,這時Struts框架會把錯誤拋給Web容器,在默認情況下Web容器會向用戶瀏覽器直接返回原始信息。如果想避免直接讓用戶看到這些原始信息,可以在web.xml中配置<error-page>元素,以下代碼演示了如何避免用戶看到HTTP 404、HTTP 500錯誤和Exception異常。

web.xml:
  <error-page>
    <error-code>404</error-code>
    <location>/exception/error404.jsp</location>
  </error-page>
  <error-page>
    <error-code>500</error-code>
    <location>/exception/error500.jsp</location>
  </error-page>
  <error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/exception/default.jsp</location>
  </error-page>
當WEB容器捕獲到exception-type或error-code指定的錯誤時將跳到由location指定的頁面。

? 問題:當form bean 為動態bean時,在action中無法對form bean數據進行驗證,因為formbean沒有具體實現類。action中無法引用
? ActionError/ActionErrors/ActionMessage/ActionMessages:

有時候你需要向用戶提供相關處理信息,包括表單驗證時發現錯誤等。
1. 相關類介紹:
ActionMessage:用于保存一個與資源束對應的提示信息。主要構造函數如:
ActionMessage(String message);
ActionMessage(String message,paramater)。

ActionMessages:用于保存多個ActionMessage。并在html:errors 和html:messages中起作用。
主要構造函數:
ActionMessages().
主要方法是add(String property,ActionMessage message)
ActionMessages有一個HashMap類型messages保存多個ActionMessage對象,每個ActionMessage對象都有唯一的一個property標識。這個property可以是自定義的任意字符串,也可以由org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE指定
html:messages/html:errors使用property屬性訪問某個資源

ActionErrors:用于保存一個與資源束對應的錯誤信息。用法跟ActionMessages差不多。
ActionError不贊成使用。


2. 版本:
struts1.1中用ActionErrors報告錯誤,用ActionMessages提供信息。
在struts1.2中使用ActionMessages提供信息和錯誤,不贊成使用ActionError
struts1.3中已經沒有ActionError類了。

3. AtionErrors和ActionMessages的區別

1. ActionErrors是ActionMessages的一個子類,功能幾乎相同,不同點在于標簽<html:errors/>和<html:messages>的使用上的區別。
html:errors指定了footer和header屬性。默認值為errors.header和errors.footer,需要時可以自己指定。如果資源屬性文件配置了 errors.header和errors.footer,則任何時候使用html:errors時開頭和結尾都是這兩個屬性對應的資源信息。
而html:message默認情況下沒有errors.header和errors.footer值,當然可以自己指定。

2. html:errors可以根據property屬性指定顯示一個錯誤信息。html:messages有一個必添項id。html:messages不能直接顯示信息,它將選出的信息放入一個用id標識的Iterator對象里,然后在用ben:write或JSTL c:out標簽顯示每個信息.例如:
<html:messages message="true" id="msg">
    <c:out value="${msg}"/><br />
</html:messages>

3. 具體的一個例子:
接受輸入頁面input.jsp:

  <html:form action="/errormessage/input">
    phoneNumber : <html:text property="phoneNumber"/> <html:errors     property="<%=org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE %>"/><br/>
  <html:submit/><html:cancel/>
  </html:form>

struts-config.xml:
  <form-beans >
    <form-bean name="inputForm" type="cn.rolia.struts.form.errorexception.InputForm" />
  </form-beans>
  <action-mappings >
    <action
      attribute="inputForm"
      input="/errormessage/input.jsp"
      name="inputForm"
      path="/errormessage/input"
      scope="request"
      type="com.yourcompany.struts.action.errormessage.InputAction"
      validate="false">
      <forward name="success" path="/errormessage/success.jsp" />
    </action>
  </action-mappings>

InputAction.java:

public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
  cn.rolia.struts.form.errorexception.InputForm inputForm = (cn.rolia.struts.form.errorexception.InputForm) form;// TODO Auto-generated method stub
  String phoneNumber = inputForm.getPhoneNumber();
  if(phoneNumber.length()<4){
  ActionErrors messages = new ActionErrors();
    messages.add(org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.errormessage.input"));
    this.saveErrors(request, messages);
    return mapping.getInputForward();
  }

  return mapping.findForward("success");
}
解說:用戶輸入手機號碼,頁面跳轉到InputAction控制層進行處理,若輸入數據小于4,則創建一個ActionMessage類存儲相關錯誤信息。然后再創建ActionErrors類將此ActionMessage放入ActionErrors。再調用Action的saveErrors方法將此ActionErrors保存的request范圍里,然后返回input.jsp頁面要求重新輸入并用html:errors提示錯誤信息。

4. Action包含saveErrors()方法和saveMessages()方法。

如果創建的ActionErrors則應該調用saveErrors(),若創建的是ActionMessages則應該調用saveMessages()方法。
saveErrors()接收ActionMessages而不是ActionErrors;同時將其保存在request中并用一個由org.apache.struts.Globals.ERROR_KEY指定的常量” org.apache.struts.Globals.ERROR_KEY”標識這個ActionMessages,便于html:errors查找。saveMessages()方法接收ActionMessages同時將其保存在request中并用一個由org.apache.struts.Globals.MESSAGE_KEY指定的常量” org.apache.struts.Globals.MESSAGE_KEY”標識這個ActionMessages,進而讓html:messages從常量Globals.ERROR_KEY中遍歷獲取信息。可以將其屬性message設置為true,那么它將從常量Globals.MESSAGE_KEY中遍歷獲取信息。

5. 默認情況下html:messages從如果你想將信息保存在session里而不是request,struts1.2提供了
struts1.1沒有的saveMessages(HttpSession session, ActionMessages messages)方法和saveErrors(javax.servlet.http.HttpSession session, ActionMessages errors)方法。
InputAction.java:

public ActionForward execute(ActionMapping mapping, ActionForm form,
    HttpServletRequest request, HttpServletResponse response) {
cn.rolia.struts.form.errorexception.InputForm inputForm = (cn.rolia.struts.form.errorexception.InputForm) form;// TODO Auto-generated method stub
  String phoneNumber = inputForm.getPhoneNumber();
  if(phoneNumber.length()<4){
    ActionErrors messages = new ActionErrors();
    messages.add(org.apache.struts.action.ActionMessages.GLOBAL_MESSAGE,new ActionMessage("error.errormessage.input"));
    this.saveErrors(request.getSession(true), messages);
    return mapping.getInputForward();
  }

  return mapping.findForward("success");
}



KE 2007-08-20 20:26 發表評論
]]>
Struts標簽庫(轉)http://www.aygfsteel.com/keweibo/articles/138222.htmlKEKEMon, 20 Aug 2007 12:23:00 GMThttp://www.aygfsteel.com/keweibo/articles/138222.htmlhttp://www.aygfsteel.com/keweibo/comments/138222.htmlhttp://www.aygfsteel.com/keweibo/articles/138222.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/138222.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/138222.html閱讀全文

KE 2007-08-20 20:23 發表評論
]]>
Action中添加請求參數http://www.aygfsteel.com/keweibo/articles/138088.htmlKEKEMon, 20 Aug 2007 04:29:00 GMThttp://www.aygfsteel.com/keweibo/articles/138088.htmlhttp://www.aygfsteel.com/keweibo/comments/138088.htmlhttp://www.aygfsteel.com/keweibo/articles/138088.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/138088.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/138088.htmlAction中的內容
ActionForward  forwrad  =   mapping . findForward(" show" );

StringBuffered path = new StringBuffered(forward.getPath());

if ( path.indexOf("?") >= 0 )
{
      path.append(" &nbsp;paramId=paramValue");
}
else
{
      path.append("?paramId=paramValue");
}

return new ActionForward( path.toString() );

struts-config.xml中的內容

<forward  name="show"  path="/show.jsp"  />



KE 2007-08-20 12:29 發表評論
]]>
Struts中配置Validator插件http://www.aygfsteel.com/keweibo/articles/137801.htmlKEKESat, 18 Aug 2007 05:02:00 GMThttp://www.aygfsteel.com/keweibo/articles/137801.htmlhttp://www.aygfsteel.com/keweibo/comments/137801.htmlhttp://www.aygfsteel.com/keweibo/articles/137801.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/137801.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/137801.html    <set-property property="pathnames" value="/WEB-INF/validator-rules.xml,/WEB-INF/validation.xml" />
 </plug-in>
required : 強制某個域不能為空,它沒有參數。
validwhen : 通過一個域的值來檢查另一個域的值。
minlength ; 檢查用戶輸入的數據長度不小于某個指定的值,需要一個最小的長度變量。
                 配置方法如下
                  <field property="username" depends="required,minlength">
                     <arg key="form.username" />
                     <arg position="1" name="minlength" key="${var : minlength}" resource="false" />
                     <var>
                           <var-name>minlength</var-name>
                           <var-value>6</var-value>
                     </var>
                  </field>
maxlength : 檢查用戶輸入的最大長度。具體配置方法參照上面minlength的配置。
mask : 根據正則表達式來檢查數據的格式,它需要一個正則表達式掩碼變量。從struts1.1開始,正則表達式必須以“^”開始并以“$”結束,其配置如下
            <field property="username" depends="mask">
               <arg key="form.username" />
               <var>
                    <var-name>mask</var-name>
                    <var-value>^[a-zA-Z]*$</var-value>
                </var>
            </field>
data : 檢查一個域是否可以被轉換成Data對象。它使用java.text.SimpleDateFormat來進行分析和檢驗,它可以使用dataPatten或者dataPattenStrict(這個比較嚴格,它要求輸入的數據長度必須與模式中的指定長度一致)例如:
             <field property="birthday" depends="date">
                <arg key="form.date"/>
                <var>
                    <var-name>dataPattern</var-name>
                    <var-value>yyyy-MM-dd</var-value>
                </var>
             </field>
intRange  /  floatRange  /  doubleRange : 檢驗一個整數 / 浮點數 / 雙精度浮點數 的值是否在一個指定的范圍內,需要最大值和最小值來指定范圍。這些檢驗分別要依賴于 integer  /  float  / double  檢驗,所以也要要求將它們也指定到depends屬性中。它定義的方法如下(這里以intRange為例)
            <field proerty="age" depends="required,integer,intRange">
               <arg position="0" key="form.age" />
               <arg position="1" name="intRange" key="${var : min }" resource="false" />
               <arg position="2" name="intRange" key="${var : max}" resource="false" />
                     <var>
                           <var-name>min</var-name>
                           <var-value>6</var-value>
                     </var>
                     <var>
                           <var-name>max</var-name>
                           <var-value>16</var-value>
                     </var>
creditCard : 檢驗一個信用卡的格式是否正確,不需要任何參數,它的定義如下。
                  <field property="card" depends="required,creditCard">
                        <arg key="form.card" />  
                   </field>
email : 檢驗電子郵件地址格式是否正確,不需要任何參數,它的定義如下。
                 <field property="email" depends="required,email">
                      <arg key="form.email"/>
                  </field>
url : 檢驗URL的格式是否正確。它有四個參數,分別是allowallschemes,allow2slashes,nofragments和schemes 。
   allowallschemes : 用來指明是否允許所有的schemes 。它的值可以為true(允許)/  false(禁止),默認值為false。如果這個值被設置為真,那么將會忽略schemes變量。
   allow2slashes : 用來指明是否允許兩個“/”出現。它的值可以為true(允許)/  false(禁止),默認值為false。
   nofragments : 用來說明是否不允許分段。它的值可以為true(不允許)/  false(允許),默認值為false。
   schemes : 指定合法的schemes,多個可以用逗號分隔。如果沒有進行指定,那么默認為http , https ,  和 ftp  。
            url檢驗的方法如下
           <field proper="custUrl" depends="url" >
                <arg key = "form.coutUrl" />
            </field>

         <field proper="custUrl" depends="url" >
                <arg key = "form.coutUrl" />
                  <var>
                     <var-name>nofragments</var-name>
                     <var-value>true</var-value>
                  </var>
                  <var>
                     <var-name>schemes</var-name>
                     <var-value>http,https,telnet,file</var-value>
                  </var>
            </field>
驗證兩個輸入域是否相等
             <field property="password2" depends="required,validwhen">
                <arg position="0" key="form.password2" />
                <arg position="1" key="form.password" />
                <msg name="validwhen" key="error.password.mathch"/>
                <var>
                    <var-name>test</var-name>
                    <var-value>(*this* == password)</var-value>
                </var>
              </field>


初始化配置文件
 validation.xml內容如下
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE form-validation PUBLIC "-//Apache Software Foundation//DTD Commons Validator Rules Configuration 1.1.3//EN" "validator_1_1_3.dtd" >
<form-validation>
 <formset>
  <form name="userForm">
      <field proper="" depends="">
            ....................................
      </field>
  </form>
 </formset>
</form-validation>
-------------------------------------------------------------------------------------------------------------------------------
Validator的調用配置
Validator的調用方法要依據所采用的驗證方式而定。
   后臺服務器端驗證
      Action中的Validate屬性值設為 true
      還有在頁面中通過<html:errors />標記來顯示錯誤信息
   前臺Javascrip驗證
      Action中的Validate屬性值設為 false
     還有在頁面用使用<html:javascript />
      <html:form onsubmit="return ValidateXXXForm(this)" >
      </html:form>
      <html:javascript forName="XXXForm" />


KE 2007-08-18 13:02 發表評論
]]>
重寫ActionServlet解決亂碼http://www.aygfsteel.com/keweibo/articles/137536.htmlKEKEFri, 17 Aug 2007 06:09:00 GMThttp://www.aygfsteel.com/keweibo/articles/137536.htmlhttp://www.aygfsteel.com/keweibo/comments/137536.htmlhttp://www.aygfsteel.com/keweibo/articles/137536.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/137536.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/137536.html寫一個MyActionServlet來并覆蓋ActionServlet中的process()方法。
添加一行代碼:request.setCharacterEncoding("gbk");就可以了.

package com.ke.struts;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionServlet;

public class MyActionSerlvet extends ActionServlet
{

 @Override
 protected void process(HttpServletRequest request,
   HttpServletResponse response) throws IOException, ServletException {
  request.setCharacterEncoding("gbk");
  super.process(request, response);
 }
 
}

當然別忘了改一下web.xml里面的配置
  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>com.ke.struts.MyActionSerlvet</servlet-class><!-- 需要修改的地方 -->
    <init-param>
      <param-name>config</param-name>
      <param-value>/WEB-INF/struts-config.xml</param-value>
    </init-param>
    <init-param>
      <param-name>debug</param-name>
      <param-value>3</param-value>
    </init-param>
    <init-param>
      <param-name>detail</param-name>
      <param-value>3</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

改一下servlet-class標簽中的內容就可以!

真的可以,一勞用yi!

具體編碼的理論就不說了,google上已經夠多了。

另外,如果不用struts的話,hibernate也可能碰到中文亂碼問題,
只要在hibernate.cfg.xml配置中如下:

<property name="hibernate.connection.url">   jdbc:microsoft:sqlserver://Localhost:1433;SelectMethod=cursor;characterEncoding=GBK;DatabasName=myDatabase. 
</property>

characterEncoding=GBK!就可以了



KE 2007-08-17 14:09 發表評論
]]>
使Struts 中的 properties屬性的文件支持中文的插件的安裝方法http://www.aygfsteel.com/keweibo/articles/137531.htmlKEKEFri, 17 Aug 2007 06:05:00 GMThttp://www.aygfsteel.com/keweibo/articles/137531.htmlhttp://www.aygfsteel.com/keweibo/comments/137531.htmlhttp://www.aygfsteel.com/keweibo/articles/137531.html#Feedback0http://www.aygfsteel.com/keweibo/comments/commentRss/137531.htmlhttp://www.aygfsteel.com/keweibo/services/trackbacks/137531.html使Struts 中的 properties屬性的文件支持中文的插件的安裝方法
 在此想和大家分享一個不錯的編寫properties文件的Eclipse插件(plugin),
有了它我們在編輯一些簡體中文、繁體中文等Unicode文本時,就不必再使用native2ascii編碼了。
您可以通過Eclipse中的軟件升級(Software Update)安裝此插件,步驟如下:

1、展開Eclipse的Help菜單,將鼠標移到Software Update子項,在出現的子菜單中點擊Find and Install;
2、在Install/Update對話框中選擇Search for new features to install,點擊Next;
3、在Install對話框中點擊New Remote Site;
4、在New Update Site對話框的Name填入“PropEdit”或其它任意非空字符串,
 在URL中填入http://propedit.sourceforge.jp/eclipse/updates/
5、在Site to include to search列表中,除上一步加入的site外的其它選項去掉,點擊Finsih;
6、在彈出的Updates對話框中的Select the features to install列表中將所有結尾為“3.1.x”的選項去掉
 (適用于Eclipse 3.2版本的朋友);
7、點擊Finish關閉對話框;
8、在下載后,同意安裝,再按提示重啟Eclipse,在工具條看到形似vi的按鈕表示安裝成功,插件可用。
 此時,Eclpise中所有properties文件的文件名前有綠色的P的圖標作為標識。
 



KE 2007-08-17 14:05 發表評論
]]>
主站蜘蛛池模板: 阿坝县| 吉木萨尔县| 咸宁市| 涡阳县| 信宜市| 韩城市| 增城市| 拉萨市| 昌邑市| 南汇区| 正定县| 嵊泗县| 东阿县| 织金县| 秦安县| 黄平县| 合作市| 澄江县| 色达县| 罗江县| 石狮市| 牡丹江市| 讷河市| 塔城市| 色达县| 长沙市| 瑞安市| 石楼县| 华阴市| 胶州市| 本溪| 苍梧县| 洪洞县| 汝南县| 景谷| 项城市| 汉中市| 汾阳市| 平阴县| 临湘市| 宣汉县|