Actionmessages (), actionerror (), actionmessage

Source: Internet
Author: User

Actionmessages (), actionerror ()
Although the Struts framework provides an effective Exception Handling Mechanism, it cannot handle all the errors. In this case, the Struts framework will throw the errors to the Web container, by default, the Web Container directly returns the original information to the user's browser. If you want to avoid directly viewing the original information, you can. configure the <error-page> element in XML. The following Code demonstrates how to avoid HTTP 404, HTTP 500, and 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>
When the Web Container captures an error specified by exception-type or error-code, it will jump to the page specified by location.

Problem: When form Bean is a dynamic bean, the form bean data cannot be verified in action because formbean does not have a specific implementation class. Action cannot be referenced
Actionerror/actionerrors/actionmessage/actionmessages:

Sometimes you need to provide users with relevant processing information, including errors found during form verification.
1. Related Classes:
Actionmessage: stores a message corresponding to the resource bundle. The main constructor is as follows:
Actionmessage (string message );
Actionmessage (string message, paramater ).

Actionmessages: used to save multiple actionmessages. It also plays a role in HTML: errors and HTML: messages.
Main constructor:
Actionmessages ().
The main method is add (string property, actionmessage message)
Actionmessages has a hashmap type messages that stores multiple actionmessage objects. Each actionmessage object has a unique property identifier. This property can be any custom string, or it can be specified by org. Apache. Struts. Action. actionmessages. global_message.
HTML: messages/html: errors use the property to access a resource

Actionerrors: used to save an error message corresponding to the resource bundle. Similar to actionmessages.
Actionerror is not supported.

2. Version:
In struts1.1, actionerrors is used to report errors and actionmessages is used to provide information.
Use actionmessages in struts1.2 to provide information and errors. do not approve of using actionerror
There is no actionerror class in struts1.3.

3. Differences between ationerrors and actionmessages

1. actionerrors is a subclass of actionmessages and has almost the same functions. The difference lies in the differences between the use of tags <HTML: errors/> and <HTML: messages>.
HTML: errors specifies the footer and header attributes. The default values are errors. header and errors. footer. You can specify them as needed. If errors. header and errors. footer are configured in the resource attribute file, the resource information corresponding to these two attributes is used at any time when HTML: errors is used.
HTML: by default, the message does not have the errors. header and errors. footer values. You can specify the values yourself.

2. html: errors can specify an error message based on the property. HTML: messages has a required item ID. HTML: messages cannot directly display information. It puts the selected information into an iterator object identified by ID, and then displays each information using the Ben: write or jstl C: Out tag. for example:
<HTML: messages Message = "true" id = "MSG">
<C: Out value = "$ {MSG}"/> <br/>
</Html: messages>

3. A specific example:
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 = (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 ");
}
Note: When you enter a mobile phone number, the page jumps to the inputaction control layer for processing. If the input data is smaller than 4, an actionmessage class is created to store related error information. Then create the actionerrors class to put this actionmessage into actionerrors. Call the saveerrors method of action to store the actionerrors in the request range, and then return the input. jsp page to request re-input and use HTML: errors to prompt the error message.

4. Action includes the saveerrors () method and savemessages () method. If actionerrors is created, saveerrors () should be called. If actionmessages is created, the savemessages () method should be called.
Saveerrors () receives actionmessages instead of actionerrors, saves it in the request, and uses. apache. struts. globals. the constant specified by error_key "Org. apache. struts. globals. error_key "identifies this actionmessages for HTML: errors search. The savemessages () method receives actionmessages and saves it in the request and uses. apache. struts. globals. the constant specified by message_key "Org. apache. struts. globals. message_key "identifies this actionmessages, and then enables HTML: messages to start from the constant globals. in error_key, traverse to obtain information. You can set the message attribute to true, so it will retrieve information from the constant globals. message_key traversal.

5. By default, HTML: messages from
If you want to save the information in the session instead of the request, struts1.2 provides
Struts1.1 does not have the savemessages (httpsession session, actionmessages messages) method and the saveerrors (javax. servlet. http. httpsession session, actionmessages errors) method.
Inputaction. Java:

Public actionforward execute (actionmapping mapping, actionform form,
Httpservletrequest request, httpservletresponse response ){
CN. rolia. Struts. Form. errorexception. 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 ");
}

 

--------------------------------------------------

 

Actionform is an object-based table, and the Integrity check of table data should be performed in it. For example, whether the user has filled all the buckets, whether all the semantics of actionform is set. You can redefine the validate () method of actionform to perform this operation. For example:
Generation:
Package onlyfun. Caterpillar;

Import javax. servlet. http .*;
Import org. Apache. Struts. Action .*;

Public class userform extends actionform {
Protected string name;
Protected string password;

Public void setname (string name ){
This. Name = Name;
}
Public void setpassword (string password ){
This. Password = password;
}
Public String getname (){
Return name;
}
Public String GetPassword (){
Return password;
}
Public void reset (actionmapping mapping, httpservletrequest req ){
Name = NULL;
Password = NULL;
}

Public actionerrors validate (actionmapping mapping,
Httpservletrequest request ){
Actionerrors errors = new actionerrors ();

If (getname () = NULL | GetUserName (). Length () <1 ){
Errors. Add ("name", new actionerror ("error. Name. Required "));
}
If (GetPassword () = NULL | GetPassword (). Length () <1 ){
Errors. Add ("password", new actionerror ("error. Password. Required "));
}

Return errors;
}
}

When the user sends a table order, and the table has a sequence bit that does not fill in the sequence, the request will include the sequence number, but the value is a null string, if the actionform has some features, but the table does not have the response data of the response, the response of the actionform is not set, these features will be null. Our validate () mainly checks these two conditions.

The Validate () method returns the actionerrors object, and the actionerrors can store the Response Message of the actionerror. Each actionerror will check the key-value response in the source response. When validate () when returning the actionerrors object, the actionservlet will not commit to the next job, but back to the position set by the structs-config.xml, for example:
Generation:
<Global-forwards>
<Forward
Name = "welcome"
Path = "/welcome. Do"/>
</Global-forwards>

<Form-beans>
<Form-bean
Name = "userform"
Type = "onlyfun. Caterpillar. userform"/>
</Form-beans>

<Action-mappings>
<Action
Path = "/welcome"
Type = "org. Apache. Struts. Actions. forwardaction"
Parameter = "/pages/welcome. jsp"/>

<Action
Path = "/loginaction"
Type = "onlyfun. Caterpillar. loginaction"
Name = "userform"
Validate = "true"
Input = "/pages/welcome. jsp">
<Forward name = "greeting" Path = "/pages/greeting. jsp"/>
</Action>
</Action-mappings>

In order to use the validate () method, the validate adequacy in <action> must be set to true, and the input adequacy is also necessary. When validate () when the actionerrors is returned, it will forward to the position set by the input parameter. The information in actionerrors can be displayed using the <HTML: errors/> mark, you will see it later.

The actionform certifies the possibility of null and null strings. This is the evidence of the integrity of the information. Next, we want to confirm the authenticity of the information, whether it meets the configured name and password. We need to modify the loginaction of the previous topic to see how it works:
Generation:
Package onlyfun. Caterpillar;

Import javax. servlet. http .*;
Import org. Apache. Struts. Action .*;
Import org. Apache. commons. beanutils .*;

Public class loginaction extends action {
Public actionforward execute (actionmapping mapping,
Actionform form,
Httpservletrequest request,
Httpservletresponse response)
Throws exception {

String name = (string) propertyutils. getsimpleproperty (form, "name ");
String Password = (string) propertyutils. getsimpleproperty (form, "password ");

If (! (Name. Equals ("caterpillar") & password. Equals ("1234 "))){
Actionmessages messages = new actionmessages ();
Messages. Add (actionmessages. global_message,
New actionmessage ("message. namepass. notmatched "));
Savemessages (request, messages );
Return Mapping. findforward ("welcome ");
}
Else {
Request. getsession (). setattribute ("valid_user", form );
Return Mapping. findforward ("greeting ");
}
}
}

In this program, we used Org. apache. commons. beanutils propertyutils does not allow us to retrieve the value in the actionform, so we do not need to handle the real shape of the actionform. propertyutils will automatically help us determine the value, getsimpleproperty () the returned result is an object, which we refer to as string.

Actionmessages is a type added by Struts 1.1. It becomes the parent type of actionerrors. In the same way, actionmessage is also a type added by Struts 1.1. It is the parent type of actionerror, the format and integrity of the information are verified in actionform. Next, we will check whether the information and integrity comply with the name and password in action, if the information does not match, the related information is added.

In Struts 1.1, message and error should be distinguished. It should be deemed that the reported error indicates that the user's internal error has an internal error in integrity or format, message means that the incoming information basically does not have a response, but it does not conform to the business processing of the subsequent response.

In order to display the alarm and alarm information, we must add a key-Value Pair in application_zh.properties, as shown below:
Generation:
# -- Error --
Error. Name. Required = no signature is returned.
Error. Password. Required = no password is entered.

# -- Message --
Message. namepass. notmatched = The namespace and password are incorrect.

In order to be able to use Chinese, remember to use the native2ascii tool program to compile the program. Next let's take a look at our welcome. note the usage of <HTML: errors/> and <HTM: messages/> in JSP:
Generation:
<% @ Taglib uri = "/tags/Struts-bean" prefix = "Bean" %>
<% @ Taglib uri = "/tags/Struts-html" prefix = "html" %>
<% @ Page contenttype = "text/html; charset = big5" %>
<HTML: HTML locale = "true">
<Head>
<Title> <Bean: Message key = "Welcome. Title"/> </title>
<HTML: base/>
</Head>
<Body bgcolor = "white">
<HTML: errors/>

<HTML: messages id = "messages" message = "true">
<Bean: write name = "messages"/>
</Html: messages>

<H3> log on

<HTML: Form Action = "/login">
Name: <HTML: Text property = "name" size = "20"/> <br>
Password secret: <HTML: Password property = "password" size = "20"/> <br>
<HTML: Submit/> <HTML: reset/>
</Html: Form>

</Body>
</Html: HTML>

If welcome is returned because actionform returns the actionerrors object. JSP, the <HTML: errors/> mark indicates the relevant response information in actionerrors. We use <HTML: messages/> check whether the returned result contains the actionmessages object. If yes, retrieve the object and use the <Bean: Write/> mark to export it.

The following is an example of the Response Message shown by the missing parameter bit during the operation:
Generation:
<HTML lang = "ZH">
<Head>
<Title> haha! Struts! </Title>
<Base href = "http: // localhost: 8080/hellostruts/pages/welcome. jsp">
</Head>
<Body bgcolor = "white">
<Ul>
<Li> no signature
</LI> <li> NO ciphertext is entered.
</LI> </ul>

<H3> log on

<Form name = "userform" method = "Post" Action = "/hellostruts/login. Do">
Name: <input type = "text" name = "name" size = "20" value = ""> <br>
Password secret: <input type = "password" name = "password" size = "20" value = ""> <br>
<Input type = "Submit" value = "Submit"> <input type = "reset" value = "reset">
</Form>

</Body>
</Html>

Note that actionerrors may be marked as deprecated after struts 1.2 and may be replaced by actionmessages in the future. Therefore, <HTML: errors/> must be replaced by the following methods in the future:
Generation:
<HTML: messages id = "MSG">
<Bean: write name = "MSG"/>
</Html: messages>

In the previous example, Set message to true on the adequacy of <HTML: messages/>, which indicates the content of actionmessages:
Generation:
<HTML: messages id = "messages" message = "true">
<Bean: write name = "messages"/>
</Html: messages>

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.