在Struts中我們用html:errors標簽在JSP頁面上輸出驗證過程中產(chǎn)生的錯誤信息,錯誤信息一般來自于消息資源文件(xxx.properties文件,一般位于classes目錄下,文本文件),當然錯誤信息也可以是不是資源文件中的文本消息,而是自定義的文本。接下來將詳細講述。

  先來看一個簡單例子

1、資源文件錯誤信息來源(其格式為 key = value )
   
   error.test = this is a test error.

2、JSP頁面中用于顯示錯誤信息標簽
  
   <html:errors property="testerror"/>

3、ActionFormBean的validate()方法中產(chǎn)生錯誤信息

   ActionErrors error = new ActionErrors();

   error.add("testerror",new ActionMessage("error.test"))
  
   return error;

 

  這個例子的功能就是在ActionForm Bean的validate()方法中產(chǎn)生一條名為:testerror的錯誤信息,錯誤信息息是資源文件中key為error.test的值。然后在頁面上用html:errors標簽輸出testerror這條錯誤信息。

  這是最常用的一種功能,所有的錯誤信息都在資源文件里面。

  有人會問,錯誤信息只能存放在資源文件中嗎,其實不是這樣。不需要資源文件也可以產(chǎn)生錯誤信息

  我們再來看一下ActionMessage的另一種構(gòu)造方法:

  ActionMessage(String key,boolean isresource)

  如果isresource值為true,則表示key是資源文件中的key,產(chǎn)生的消息就是與key相對應(yīng)的消息
  如果isresource值為false,則表示key為一條普通的消息。

  如果上面的error.add改為error.add("testerror",new ActonMessage("這是一條自定義消息",false",));那么頁面上顯示的將是:這是一條自定義消息.


  另外還可以用ActionMessage產(chǎn)生復(fù)合消息,比如我們要輸出:xxx不能用作用戶名,其中xxx是一個變量。

  首先我們在資源文件中加一個條復(fù)合消息

  testmsg = {0}不能用作用戶名。這里{0}是要被替換的參數(shù)。

  我們再來看一下ActionMessage的另一中構(gòu)造方法
  ActionMessage(String key,Object value0);

  也就是說用value0的值來替換{0}

  我們修改error.add為error.add("testerror",new ActonMessage("testmsg","孫中山"))

  那么JSP頁面上將顯示:毛澤東不能用作用戶名。


  當然在一條復(fù)合消息中也可帶多個參數(shù),參數(shù)依次為{0},{1},{2}或更多
  例如:
loginUser = 用戶名:{0} 姓名:{1} 登錄次數(shù):{2}.....
  那么在產(chǎn)生錯誤消息時就用new ActionMessage(String key,Object value0,Object value1,Object  value2.....)或者使用對象數(shù)組new ActionMessage(String key,Object[] values)
  

  String[] detail = {"Admin","王晶","12"};
  error.add("testerror",new ActionMessage("loginUser",detail))


Note:

Cannot find message resources under key org.apache.struts.action.MESSAGE  錯誤的原因是沒有配置資源文件

解決辦法: 在struts-config.xml 中加入如下的一段

<message-resources parameter="application" null="false"></message-resources>