In-depth analysis of JavaWeb Item46 -- Struts2 data validation and Internationalization
1. user input data validation1. Verification Method
A:Client Verification. (The Anti-gentleman cannot defend against the villain) Write js scripts on the page. The benefits of doing so are:
Prompt when input is incorrect; reduce the pressure on the server
B,Server Verification.
Data security: the entire application blocks the last line of defense against illegal data
In actual development, a + B is usually selected.
2. server-side data verification:
1. Programmatic Verification: Write a verification code in your own Action (Disadvantage: All verification rules are written in the Code)
Premise: the validate class inherits ActionSupport and overrides the Validateable () method in the Validateable interface to complete verification in this method.
The procedure is as follows:
* The validate () method is executed before other business methods.
Verification error redirection page
Struts. xml configuration
/validate/login.jsp
The input redirection is defined in the action.
public static final String INPUT = "input";
When indicates a verification error (turning to the page pointed to by input)
This. addFieldError ("sss", "error message ");
The method points to a set. When the set is not empty, the error page is redirected. The error Jsp page is displayed: Use
Show error message
1. Verify all actions in the actions class
Compile UserAction to inherit ActionSupport and use the validate () method.
Package com. itheima. actions; import java. util. arrays; import org. apache. commons. lang3.StringUtils; import org. apache. struts2.interceptor. validation. skipValidation; import com. opensymphony. xwork2.ActionSupport; public class UserAction extends ActionSupport {private String username; private String password; public String getUsername () {return username;} public void setUsername (String username) {this. username = username;} public String getPassword () {return password;} public void setPassword (String password) {this. password = password;} public int getAge () {return age;} public void setAge (int age) {this. age = age;} public String add () {// call Service try {System. out. println ("saved successfully:" + this); return SUCCESS;} catch (Exception e) {e. printStackTrace (); return ERROR ;}// write verification rules here: Verify public void validate () for all action Methods () {// The username cannot be null or "" if (StringUtils. isEmpty (username) {addFieldError ("username", "username cannot be blank"); // Map
Key: field name, value error message }}@ Override public String toString () {return "UserAction [username =" + username + ", password =" + password + ", age = "+ age +", birthday = "+ birthday +", holobby = "+ Arrays. toString (holobby) + "]" ;}}
Configure action in struts. xml
/success.jsp
/error.jsp
/regist.jsp
Three simple pages, success. jsp-error.jsp-register.jsp.
Register. jsp
<% @ Page language = "java" import = "java. util. * "pageEncoding =" UTF-8 "%> <% @ taglib uri ="/struts-tags "prefix =" s "%> User Registration
Error. jsp
Server busy
Success. jsp
Saved
The preceding verification method verifies all action methods. To verify the specified method, you must
2. Verify the specified action
Method 1: Write A validate method. You can use @ SkipValidation before the action method that does not need to be verified. For example, the action Method add can be expressed
// @ SkipValidation // ignore public String add () {// call Service try {System. out. println ("saved successfully:" + this); return SUCCESS;} catch (Exception e) {e. printStackTrace (); return ERROR ;}}
Method 2: The validate method has certain writing specifications. Public void validate Action Method Name (uppercase), such as action method edit
public String edit(){ return SUCCESS;}
Verification Method
// Only verify the public void validateEdit () for the edit Action Method {// the user name cannot be null or "" if (StringUtils. isEmpty (username) {addFieldError ("username", "the user name cannot be blank. Why not be obedient ");//}}
ValidateXxx () only verifies the method named Xxx in the action. The first letter of Xxx must be in uppercase.
Underlying code (ValidationInterceptor interceptor)
Summary: The framework changes to any verification that fails or is converted differently.name=”input”
. To display an error message,
Use
To display error messages related to fields.
The above verification process:
The type converter performs type conversion on the Request Parameters and assigns the converted value to the attribute in the action.
If an exception occurs during the execution of type conversion, the system saves the exception information to ActionContext. The conversionError interceptor encapsulates the exception information in fieldErrors and then executes step 1. If no exception occurs during type conversion, go to step 1.
The system uses reflection technology to call the validateXxx () method in action. Xxx is the method name.
Call the validate () method in action.
After the above four steps, if the fieldErrors in the system has an error message (that is, the size of the Set storing the error information is greater than 0), the system automatically forwards the request to the view named input. If fieldErrors in the system does not have any error information, the system will execute the processing method in the action.
2. Declarative verification: using xml configuration files (convenient)
1. Verify all actions in the actions class
In this verification file, to verify the string-type username attribute in UserAction, you must first call the trim () method to remove spaces and then determine whether the username is empty.
The file needs to be placed in the same package with the action class, the file name should comply with the ActionClassName-validation.xml rules, the ActionClassName is the simple class name of action,-validation is a fixed writing. For example, if the Action class is cn. msg. validate. UserAction. Then the file name should be: UserAction-validation.xml
The UserAction-validation.xml is configured for the file as follows
False
Enter a username.
3
9
The user name must be between $ {minLength }~ Between $ {maxLength}
Enter the correct email address.
Password = repassword
The two passwords must be consistent.
** Note:
: Root element
: Specifies the attribute to be verified in the action, and the name attribute specifies the name of the form field to be verified
: Specify the validator and type specify the validation rules.
The requiredstring specified above is provided by the system, which can meet most verification requirements.
Which can be defined in the xwork-2.x.jar
Com. opensymphony. xwork2.validator. validatorsIn default. xml.
: Sub-elements can pass parameters to the validators
: The subelement is the prompt message after the verification fails. If you want to internationalize the subelement, it can be the message
Specifies the key attribute. The key value is the key in the attribute file.
2. Verify the specified action
Method 1: Use @ SkipValidation
Method 2: The Declaration File follows certain writing specifications:
If you only need to verify a add method in UserAction, then the validation file name should be: ActionClassName-ActionName-validation.xml, where ActionName is the name of the action in struts. xml.
UserAction-UserAdd-validation.xml
Some features of XML-based Validation
When a validation file provides ActionClassName-validation.xml and ActionClassName-ActionName-validation.xml rules for an action, the system looks for the validation file in the order below:
1. AconClassName-validation.xml
2. ActionClassName-ActionName-validation.xml
When the system finds the first check file, it will continue to search for the subsequent check files. When it finds all the check files, it will summarize all the validation rules in the check file, then it is applied to the verification of the processing method. If the verification rules specified in the two verification files conflict, only the validation rules in the following files are used.
A prompt message is not displayed when you compile the verification file.
When writing a ActionClassName-validation.xml validation file, if there is no help information, you can solve the problem as follows:
Windwos-> preferences-> myeclipse-> files and editors-> xml-> xmlcatalog
Click add, select File system in the location in the window that appears, and then select the xwork-2.1.2 In the src \ java directory of the xwork-validator-1.0.3.dtd extract directory, when you return to the settings window, do not rush to close the window. You should change the Key Type in the window to URI. Key to http://www.opensymphony.com/xwork/xwork-validator-1.0.3.dtd
Checker Introduction
Required
Gender cannot be blank!
Requiredstring mandatory string validator
True
The user name cannot be blank!
Stringlength: String Length checker
10
2
True
产品名称应在2-10个字符之间
Int: integer validator
1
150
The age must be between 1 and.
Date: date validator
1900-01-01
2050-02-21
The birthday must be between $ {min} and $ {max }.
Url: network path validator
The home address of Chuanzhi podcast must be a valid website.
Email: email address checker
Invalid email address
Regex: Regular Expression validator
^13\d{9}$
Incorrect mobile phone number format!
Fieldexpression: field expression Validation
(password==repassword)
The two passwords are inconsistent.
3. Custom declarative Verification
Custom validators must implementValidatorInterface.
The Validation interceptor is responsible for loading and executing various verification programs. after a verification program is loaded, the interceptor will call the setValidatorContext method of the verification program and pass the current ValidatorContext object to it, which allows the programmer to access the current Action. next, the Validation interceptor will call the validate method and pass the object to be verified. the validate method is the method that needs to be overwritten when writing a custom verification program.
ValidatorSupport and FieldValidatorSupport implement the Validator interface.
If you need a common verification program, you can inherit
ValidatorSupportIf you need a field verification program, you can inherit
FieldValidatorSupportClass if the validators need to accept an input parameter, they need to add a corresponding attribute for this parameter
Case:Verify password strength
Development steps:
1. Compile a StrongPasswordValidator class: implement the Validator interface or inherit the ValidatorSupport class. We recommend that you inherit FieldValidatorSupport.
Package com. itheima. actions; import com. opensymphony. xwork2.validator. validationException; import com. opensymphony. xwork2.validator. validators. fieldValidatorSupport; public class StrongPasswordValidator extends FieldValidatorSupport {private int minLength =-1; public int getMinLength () {return minLength;} public void setMinLength (int minLength) {this. minLength = minLength;} // verification method: determines the content that does not meet the requirements. To add information to the Map. // parameter: the object is the current action Object public void validate (object Object) throws ValidationException {// get the name of the field to be verified String fieldName = getFieldName (); Object fieldValue = getFieldValue (fieldName, object); if (fieldValue = null) return; if (! IsStrong (String) fieldValue) {addFieldError (fieldName, object);} if (minLength>-1) & (String) fieldValue). length ()
2. register the validator
Under the WEB-INF \ classes directory, create a fixed name namedValidators. xmlConfiguration File
3. You can use a validator like requiredstring.
2. Struts2 InternationalizationI have talked about internationalization before.
ResourceBundle rb = ResourceBundle.getBunle(“message”,Locale);
In struts2, prepare the resource file first. The naming format of the resource file is as follows:
BaseName_language_country.properties
BaseName_language.properties
BaseName. properties
The baseName is the basic name of the resource file, which can be customized, but the language and country must be the languages and countries supported by java. For example:
Mainland China:baseName_zh_CN.properties
US:baseName_en_US.properties
Now add two resource files for the application:
The first one Stores Chinese characters:msg_zh_CN.properties
hello=\u60A8\u5403\u4E86\u5417\u554A\u6CA1\u5403username=\u7528\u6237\u540D
The second one Stores English (USA ):msg_en_US.properties
Content:
hello=good morningusername=Username
After compiling an attribute file in Chinese, we should use the native2ascii Command provided by jdk to convert the file to a unicode-encoded file. The command is used as follows:
Native2ascii source file. properties target file. properties
1. Configure the global message Resource PackageA. Configure the global message Resource Package
After preparing the resource file, we can use the struts. custom. i18n. resources constant in struts. xml to define the resource file as a global resource file, as shown below:
Msg is the base name of the resource file.
B. Access
In the category class:
Premise: the category class inherits ActionSupportPackage com. itheima. actions; import com. opensymphony. xwork2.ActionSupport; // access the international message public class I18nAction extends ActionSupport {public String execute () {String value = getText ("hello"); // TextProvider System. out. println (value); return SUCCESS ;}}
On the page:
Or
You can specify a message resource package with struts2 related international tags:
If the message resource package is incom.itheima.resources.msg_zh_CN.properties
2. configure a local message Resource PackageYou must go through the Action:
Writing rules: Create a name in the package where the category class is located"CATEGORY class name-zh-CN.properties
. When accessing the hosts class, it is found that the local access has a higher priority than the global access.
3. Package range message Resource PackageIt must also be accessed by action.
The name must be standardized.package_zh_CN.properties
In the class package. It can be accessed by all the response classes in the package and sub-packages.
When you search for a message with the specified key, the system first searches for the message from the ActionClassName_language_country.properties resource file. If the corresponding key is not found, the system searches for the resource file with the basic name package along the current package, always find the top-level package. If the corresponding key is not foundstruts.custom.i18n.resources
Search for the specified resource file.
The order is as follows: