I added my error and message in struts2 action class using addActionMessage
and addActionError
method.
Now I want code for displaying this message and this error in the html page? Is it possible to print?
问题:
回答1:
Put
<s:actionerrors />
and
<s:actionmessages />
tags inside your JSP
AND, for a better graphical result, use a particular div container (one red, one green for example) and check before if you have messages or errors (to print the div only if not empty):
<s:if test="hasActionErrors()">
<div class="feedError">
<s:actionerrors />
</div>
</s:if>
<s:if test="hasActionMessages()">
<div class="feedOk">
<s:actionmessages />
</div>
</s:if>
and in CSS
.feedError{
width: 100%;
border: 10px solid red;
}
.feedOk{
width: 100%;
border: 10px solid green;
}
EDIT: no, as far as I know you can't get Action Errors and Messages directly from HTML. You can make ajax calls to an action that retrieves them from Session and returns them in JSon, but this is really overkill, bad designed and not necessary.
As a solution, you can use another view technology instead of JSP; it isn't just plain HTML, but at least you can't use Scriptlets inside pages, if that's is your problem with using JSP.
You can use FreeMarker Template, for example.
The previous JSP snippet would become something like this (untested), in the .ftl file:
<#if (actionErrors?size>0)>
<div class="feedError">
<@s.actionerror />
</div>
</#if>
<#if (actionMessages?size>0)>
<div class="feedOk">
<@s.actionmessage />
</div>
</#if>
Or Velocity (again, untested):
#if( $actionErrors.size() > 0 )
<div class="feedError">
#foreach( $msg in $actionErrors )
[$msg]<br />
#end
</div>
#end
#if( $actionMessages.size() > 0 )
<div class="feedOk">
#foreach( $msg in $actionMessages )
[$msg]<br />
#end
</div>
#end
NOTE: if the reason for not using JSPs is to prevent scriptlets, you can configure this behaviour in web.xml adding
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
</jsp-config>
Using JSP with Struts2 is not the only way, but it is the easiest and the fastest, imho.