| struts出错处理小探 |
|
| 作者是 Administrator | |
| 2008-05-10 21:25:00 | |
|
Struts中提供方便的出错处理机能,利用ActionForm的validate方法就可以进行业务相关的错误处理。 ①首先,我们会在ActionForm中validate方法中将报错信息存储在ActionErrors对象中,在这里只有ActionErrors才会被request捕获 public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { // TODO Auto-generated method stub ActionErrors errors = new ActionErrors(); if(username == null || "".equals(username)) { ActionError error = new ActionError("Invalid.username", "null"); //出现错误,将记录错误的key errors.add("usernameInvalid", error); } return errors; } 错误信息ActionError error = new ActionError("Invalid.username", "null");是将出错信息的对应到资源文件的Key值记录下来存储在ActionError中,还提供了一些参数的记录。这样就可以通过<html:errors/>来读取对应的错误信息。资源文件的描述: Invalid.username=invalid user name "{0}" 这里的Invalid.username就对应到ActionError error = new ActionError("Invalid.username", "null");中的Invalid.username。 {0}将被null替换。 ②JSP代码: <H2><bean:message key="welcome.h2"/></H2><html:errors/> ③Struts-config.xml文件的配置: <action-mappings > <action path="/LoginAction" input="/welcome.jsp" name="Login" type="com.home.struts.action.LoginAction" scope="request" validate="true" > <forward name="success" path="/blank.jsp"/> <forward name="fail" path="/welcome.jsp"/> </action> <message-resources parameter="com.home.struts.ApplicationResources" /> </struts-config> 这里关键是validate属性和input属性,validate属性指定要不要进行错误信息的检查,true为进行检查。input则是指定错误信息输出的路径。message-resources则是指定目录下以及ApplicationResources为前缀的资源信息文件。 ④资源文件的unicode化需要利用native2ascii命令来转化: native2ascii -[options] [inputfile [outputfile]] 说明: -[options]:表示命令开关,有两个选项可供选择 -reverse:将Unicode编码转为本地或者指定编码,不指定编码情况下,将转为本地编码。 -encoding encoding_name:转换为指定编码,encoding_name为编码名称。 [inputfile [outputfile]] inputfile:表示输入文件全名。 outputfile:输出文件名。如果缺少此参数,将输出到控制台。 例:native2ascii -encoding GB2312 ApplicationResources_cn.properties Applicati onResources_zh_CN.properties |
|
| 最近更新 ( 2008-05-10 21:25:00 ) |

