神秘的 J2ee 殿堂

·古之学者必有师·做学者亦要做师者·FIGHTING·

Struts中的error handling,html:messages 与html:errors的显示错误消息的区别

在struts中,对Form和Action等错误信息在页面中的显示非常方便,通过<html:messages/>与<html:errors/>
标签都能完成。而他们在语法上的区别也很小,举例说明:<html:messages/>

        ActionMessages message = new ActionMessages();
        
//从Request范围获得出错页面的资源文件属性
        MessageResources messageResources = getResources(request);
        
//判断是否出错,出错就添加到message对象中,其中add的第一个属性用于标识不同的错误信息,第二个属性是得到错误提        示字符串,第一个属性与显示页面的Property对应,如果设为一样就把错一起显示出来
        if(bookEditForm.getAuthor().equals(""))
            message.add(
"author"new ActionMessage(
            "
error.field", messageResources.getMessage("label.author", request)));
        
if(bookEditForm.getTitle().equals(""))
            message.add(
"author2"new ActionMessage(
            "
error.field", messageResources.getMessage("label.title", request)));
        
//判断是否有错误,并跳转        
        if(!message.isEmpty()){
        //在Request范围保存错误消息
            saveMessages(request, message);
            
return mapping.findForward("showEdit");
        }
页面显示:
其中id属性可以随便取,但bean:wirte的name要与id一样,显示全部错误信息就不要Property属性,显示特定的出错信息就要指定property属性
            <html:messages id="haha" property="author" message="true"> 
                
<font style="font-weight:bold; color=#FF0000">
                <
bean:write name="haha" />
               
</font><br>
            
</html:messages>


<html:errors/>
        ActionErrors actionErrors = new ActionErrors();
        MessageResources messageResources 
= getResources(request);
        
        
if(bookEditForm.getAuthor().equals(""))
            actionErrors.add(
"author"new ActionError(
           
"error.field", messageResources.getMessage("label.author", request)));
        
if(bookEditForm.getTitle().equals(""))
            actionErrors.add(
"author2"new ActionError(
           
"error.field", messageResources.getMessage("label.title", request)));

        
if(!actionErrors.isEmpty()){
            saveErrors(request, actionErrors);
            
return mapping.findForward("showEdit");
        }

页面显示:
<html:errors property="author"/>
//或者
<html:errors />

最后:html:messages是1.1以后出现的,也是推荐使用的;

posted on 2007-09-13 14:48 月芽儿 阅读(684) 评论(0)  编辑  收藏 所属分类: J2EE学习心得


只有注册用户登录后才能发表评论。


网站导航:
 

导航

统计

常用链接

留言簿(2)

随笔分类

随笔档案

相册

搜索

最新评论

阅读排行榜

评论排行榜