Struts 2 data Check function and the solution of check problem _java

Source: Internet
Author: User
Tags deprecated gettext

By inheriting the Actionsupport class to accomplish action development, the Actionsupport class not only implements the action interface simply, but also adds support for validation, localization, and so on. Custom action in real development needs to inherit the class. Add form validation to user logins

The role of the Actionsupport class:

STRUTS2 does not require our own design action class to inherit any of the struts base classes or struts interfaces, but in order to facilitate the implementation of our own action, In most cases, you will inherit the Com.opensymphony.xwork2.ActionSupport class and override the public String execute () throws exception method in this class. Because of the many practical excuses that are implemented in this class, there are many default methods that include methods for internationalizing information, default methods for handling user requests, and so on, which can greatly simplify acion development. The Struts2 typically uses the action directly to encapsulate the HTTP request parameters, so the action class should also contain the attributes corresponding to the request parameters and provide the corresponding getter and setter methods for the property.

So what's the difference between the action interface and the Actionsupport class?

The action interface has:

public static final String SUCCESS = "SUCCESS";
The public static final String none = "None";
public static final String error = "error";
public static final String login = "Login";
Public String Execute () throws Exception;

You can see that there are five static constants and execute () with a return type of string

The Actionsupport tool class also defines a validate () method based on the implementation of the action interface, overriding the method, which executes before the Execute () method, such as failure of the checksum, into the input office, The input property must be configured when this action is configured.

In addition, Actionsupport provides a gettext (String key) method that also implements internationalization, which obtains internationalization information from a resource file.

This allows you to define a variable to internationalize the new Actionsupport object when customizing the label.

Actionsupport class has (source code):

public class Actionsupport implements Action, Validateable, Validationaware, Textprovider, Localeprovider, Serializable {protected static Logger LOG = Loggerfactory.getlogger (actionsupport.class); private final Validationawaresupport
Validationaware = new Validationawaresupport ();
private transient textprovider textprovider;
Private Container Container; public void Setactionerrors (collection<string> errormessages) {validationaware.setactionerrors (errorMessages
); Public collection<string> getactionerrors () {return validationaware.getactionerrors ();} public void Setactionmessages (collection<string> messages) {validationaware.setactionmessages (messages);} public Collection<string> getactionmessages () {return validationaware.getactionmessages ():} @Deprecated Public Collection<string> geterrormessages () {return getactionerrors ():} @Deprecated public map<string, list< String>> geterrors () {return getfielderrors ();} public void SetfieldeRrors (map<string, list<string>> errormap) {validationaware.setfielderrors (ERRORMAP);} public Map<
String, list<string>> getfielderrors () {return validationaware.getfielderrors ();} public Locale GetLocale () {
Actioncontext CTX = Actioncontext.getcontext (); if (CTX!= null) {return Ctx.getlocale ();} else {if (log.isdebugenabled ()) {Log.debug ("Action Context not initialized"
);
return null;
} public boolean Haskey (string key) {return Gettextprovider (). Haskey (Key):} public string GetText (string atextname) {
Return Gettextprovider (). GetText (Atextname); public string GetText (string atextname, string defaultvalue) {return Gettextprovider (). GetText (Atextname,
DefaultValue); public string GetText (string atextname, String defaultvalue, String obj) {return Gettextprovider (). GetText (Atextname, D
Efaultvalue, obj); public string GetText (string atextname, list<?> args) {return Gettextprovider (). GetText (Atextname, args);} publi C String GetText (string Key, string[] args {return Gettextprovider (). GetText (key, args);} public string GetText (string atextname, String Defau Ltvalue, list<?> args) {return Gettextprovider (). GetText (Atextname, DefaultValue, args); \ public String GetText (S Tring Key, String DefaultValue, string[] args) {return Gettextprovider (). GetText (Key, DefaultValue, args); G GetText (string key, String defaultvalue, list<?> args, Valuestack stack) {return Gettextprovider (). GetText (Key, D
Efaultvalue, args, stack); public string GetText (string key, String defaultvalue, string[] args, Valuestack stack) {return Gettextprovider (). Gette
XT (Key, DefaultValue, args, stack); public string getformatted (string key, String expr) {map<string, object> conversionerrors = Actioncontext.getcont
Ext (). Getconversionerrors ();
if (Conversionerrors.containskey (expr)) {string[] Vals = (string[]) conversionerrors.get (expr); return vals[0];} else { Final Valuestack valuestack = Actioncontext.getcontext (). Getvaluestack ();
Final Object val = valuestack.findvalue (expr);
Return GetText (Key, Arrays.aslist (Val)); } public ResourceBundle gettexts () {return Gettextprovider (). Gettexts ();} public ResourceBundle gettexts (String Abundl
ename) {return Gettextprovider (). gettexts (abundlename);} public void Addactionerror (String anerrormessage) {
Validationaware.addactionerror (Anerrormessage); public void Addactionmessage (String amessage) {validationaware.addactionmessage (amessage);} public void
Addfielderror (String fieldName, String errormessage) {validationaware.addfielderror (fieldName, errormessage);} public string input () throws Exception {return input;} public string Dodefault () throws Exception {return SUCCESS;} PU Blic String Execute () throws Exception {return SUCCESS.} public boolean hasactionerrors () {return VALIDATIONAWARE.HASAC
Tionerrors (); public Boolean hasactionmessages () {return validationaware.hasactionmessages ():} public boolean hasErrors () {return V AlidationawAre.haserrors (); public Boolean hasfielderrors () {return validationaware.hasfielderrors ():} public void Clearfielderrors () {Validation
Aware.clearfielderrors (); public void Clearactionerrors () {validationaware.clearactionerrors ():} public void Clearmessages () {validationaware.
Clearmessages (); public void Clearerrors () {validationaware.clearerrors ():} public void Clearerrorsandmessages () {validationaware.cle
Arerrorsandmessages (); public void Validate () {} @Override Public Object clone () throws Clonenotsupportedexception {return Super.clone ();} p ublic void Pause (String result) {} private Textprovider Gettextprovider () {if (Textprovider = null) {Textproviderfacto
Ry TPF = new Textproviderfactory ();
if (container!= null) {container.inject (TPF);} Textprovider = Tpf.createinstance (GetClass (), this);
return textprovider; @Inject public void Setcontainer (Container Container) {this.container = Container;}

There are a lot of ways to see it, but we obviously see a validate (), data checksum method that we know very well. With this method, we can log in when the username and password are empty, or else the hint

Here's a simple example: when the username and password are empty, give the customer a friendly hint.

Here are two ways to illustrate the data validation capabilities of Struts 2.

1. Coding mode Check

1 action must inherit from Actionsupport

2 a public void ValidateXxx () method is written for a request processing method to be validated, and a form data checksum is performed within the method.

3 The public void Validate () method can also be written for all request processing methods.

4 in the calibration method, the Addfielderror () method can be used to add field validation error messages.

5 When the checksum fails, the struts framework automatically jumps to the result page with the name input. In the Validation failure page, you can use <s:fielderror/> to display error messages
6) Simple and flexible. But the reusability is not high

Overriding the Validate method

1. We write the action of the general inheritance and Actionsupport, and Actionsupport not only implemented the action interface, but also implemented the Validatable interface, providing data verification function. Define a validate method in the Validatable interface, override the method, and add errors to the Fielderror domain of the Actionsupport class and then output through the OGNL expression if there is an error in the Validation form input field.

The following is the user logon verification interface:

<body>
<%--Output Check information--%>
<%--want a single hint <s:fielderror fieldname= "uname"/>--%> <%
--<s:property value= ""/>
--%><div style= "color:red" ><s:fielderror/></div> 
<s:form name= "Form1" namespace= "/" method= "POST" action= "Loginvalidateaction" >
<s:div> Please enter user name: <s : TextField name= "User.uname" ></s:textfield></s:div>
<s:div> Please enter password: <s:password name= " User.upwd "></s:password></s:div>
<s:submit value=" Login "></s:submit>
</s: form>
<%--debug--%>
<s:debug></s:debug>
</body>

After the user enters the data, commits to the loginvalidateaction:

public class Loginvalidateaction extends Actionsupport implements Action {public
user user;
Public map<string, object> Map;
The validated method will work on all the action
@Override public 
Void Validate () {
if (user.getuname (). Length () ==0) {
Addfielderror ("uname", "User name cannot be empty!");
if (User.getupwd (). Length () ==0) {
addfielderror ("upwd", "Password cannot be empty!");
} 
Method of processing business public
String execute () throws Exception {
System.out.println (User.getuname ());
if (User.getuname (). Equals ("admin") &&user.getupwd (). Equals ("admin") {
//Let Struts2 inject map collection
Map.put ("Uname", User.getuname ());
Returns "Success" return success if the login is successful
;
else{
//Login failure, return error returns
input;//here must be input
}
}
/**
* @return the user * *
Public
User GetUser () {return
user;
}
/**
* @param user the user to set
*
/public void SetUser (user user) {
this.user = user
}

The Loginvalidateaction class above overrides the Validate method, which executes before the Excute method is executed, and if the method is executed, the filederror of the Action class contains a data checksum error. The request is forwarded to the input logical view.

The Struts.xml configuration is as follows:

<!--data validation-->
<action name= "loginvalidateaction" class= "Cn.struts2.action.LoginValidateAction" >
<!--result is "success", Jump to success.jsp page-->
<result name= "Success" >success.jsp</result>
<!--result is "error", jump to fail.jsp page or also in the login interface login.jsp-->
<result name= "Input" > loginvalidateaction.jsp</result>
<result name= "Login" >fail.jsp</result> 
<result Name= "Error" >fail.jsp</result> 
</action>

Effects on the client:

But the attention does not, when the prompt error is not very much the effect that we want to display.

This is not what we want, so how do we change it? In fact this mainly shows the Struts2 theme style caused by the

Take another look:

It automatically adds a style to us. Struts2 offers three themes, Ajax, Simple, XHTML, which defaults to XHTML themes, and of course you can write any of your own topics, which we call custom themes. You can resolve the above problem by setting

There are two ways to fix this:

1. Simple method (also very practical, for all struts2 tags), in the Struts.xml, add the next line of code is OK.

<constant name= "Struts.ui.theme" value= "simple"/>

On behalf of all the pages are simple theme, when it output the page, not back to add any extra code, such as table TR TD, and so on, we can edit the page like other ways to edit the style of the page.

Now take a look at the wrong hint format

We can set such a label by:

<s:property value= "errors.uname[0]"/>

Comment out this tag:

 
 

But that's what happens when we set it up like this.

This effect is a bit like we usually enter the error when the hint, there are other attribute values, here is not to enumerate.

Using the STRUTS2 validation framework

XML configuration Method Checksum.

is executed before the encoding method.

1 for the Action class to verify, under the same package to write a name: Action class name-validation.xml validation rules file.

2 in the validation rules file to add a checksum rule: the specific validator name, parameters can refer to Struts2 's reference or STRUTS2 API.

A field checksum: A rule that verifies the field of each non custom type in the action class.

<field name= "field name to validate" >
<field-validator type= Verify rule name "short-circuit=" for short path checksum (default is False) >
<param name= "parameter name to be used by the validator" > Value </param>
<message> validation failure When prompted message </message>
</ Field-validator>
<!--can also add other validation rules-->
</field>

b) Non-field checksum: Uses OGNL expression for some field of the action class to combine checksums.

<validator type= "Fieldexpression" >
<param name= "FieldName" >pwd</param>
<param name= " FieldName ">pwd2</param>
<param name=" expression "><![ cdata[pwd==pwd2]]></param><!--ognl expression-->
<message> Confirm password and password input inconsistency </message>
</validator>

c) Visitor checksum: is used primarily to verify the custom type field in the action class. (When using model-driven mode)

i) Use visitor validation rules for custom type field in the validation rule file for the action class.

<!--use visitor checksum for custom field-->
<field name= "user" >
<field-validator type= "required" Short-circuit= "true" >
<message> User information is required </message><!--message prefix-->
</field-validator >
<field-validator type= "Visitor" ><!--specified as visitor checksum rule--> <param
"Context" > usercontext</param><!--Specifies the context name of the visitor checksum-->
<param name= "Appendprefix" >true</param> <!--do you want to add the prefix-->
<message> user's </message><!--message prefix--> for validation failure messages
</field-validator >
</field>

II Write a checksum rule file for the field of visitor. The file name is: Visitor field type name [-visitor validation context name]-validation.xml. For example, in this example, the file name is User-usercontext-validation.xml

Note: This file is to be stored under the package that contains the Visitor field type.

III) Add a checksum rule for the field to be validated in the Visitor field validation rule file.

We can also do data validation without rewriting the Validate method, and by increasing the checksum configuration file. This checksum configuration file completes the validation of the form field by using the Struts2 existing validator, which, for example, takes the Requiredstring validator, which is a required validator, specifying that a form field must be entered.

The following is the loginvalidateaction-validation.xml of this checksum configuration file:

<?xml version= "1.0" encoding= "UTF-8"?> <!
DOCTYPE validators Public "-//apache struts//xwork Validator 1.0.2//en" 
"http://struts.apache.org/dtds/ Xwork-validator-1.0.2.dtd ">
<validators>
<field name=" uname ">
<field-validator Type= "requiredstring" >
<message> User name cannot be empty </message>
</field-validator>
</ field>
<field name= "upwd" > <field-validator type= "requiredstring
" >
<message> Password cannot be null </message>
</field-validator>
<field-validator type= "Stringlength" >
< param name= "maxLength" >18</param>
<param name= "minlength" >6</param>
<message > Password length should be between ${minlength}--${maxlength} bits </message>
</field-validator>
</field>
</validators>

Note: This checksum configuration file must comply with the following two rules:

1, the file fate format must be an action class name-validation.xml, for example, in this case, the file name is: Loginvalidateaction-validation.xml

2. The file must be located in the same path as the action class file, in this case the file is located in the

The code for the Loginvalidateaction class is still the same:

public class Loginvalidateaction extends Actionsupport implements Action {public
user user;
Public map<string, object> Map;
The validated method will work on all the action
@Override public 
Void Validate () {
if (user.getuname (). Length () ==0) {
Addfielderror ("uname", "User name cannot be empty!");
if (User.getupwd (). Length () ==0) {
addfielderror ("upwd", "Password cannot be empty!");
} 
Method of processing business public
String execute () throws Exception {
System.out.println (User.getuname ());
if (User.getuname (). Equals ("admin") &&user.getupwd (). Equals ("admin") {
//Let Struts2 inject map collection
Map.put ("Uname", User.getuname ());
Returns "Success" return success if the login is successful
;
else{
//Login failure, return error returns
input;//here must be input
}
}
/**
* @return the user * *
Public
User GetUser () {return
user;
}
/**
* @param user the user to set
*
/public void SetUser (user user) {
this.user = user
}

The above is a small series to introduce the Struts 2 data check function and verify the problem of the solution, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.