Struts2 dry cargo note – second days

Catalog

1. Struts2 provides three ways of data encapsulation
2. encapsulate data to Collection and Map
3. Struts2 type converter
Error handling in 4. type converter
5. request parameter validation
6. check the specified method in action
Struts2 provides three ways of data encapsulation
1. attribute driven
  • Action itself as a model object, the setter package
    page: the user name < input type= “text” name= “username” /> < br/> Action:public class RegistAction extends ActionSupport String public void {private username; setUsername (String username) {this.username = username;}}
  • Create a separate model object, ognl page by page:
    expression package user name < input type= “text” name= “user.username” /> < br/> / / OGNL Action:public class RegistAction2 extends expressions written ActionSupport User user {private public void based on setUser (User; user) {this.user = user;} public User getUser (return) {user}};
2. model driven (mainstream)
  • Use the ModelDriven interface to encapsulate the
    page request parameters: the user name < input type= “text” name= “username” /> < br/> Action:public class RegistAction3 extends ActionSupport implements ModelDriven< User> User user new = {private (User); / / User getModel must manually instantiate the public (return) {user};}

Encapsulate data to Collection and Map

  1. The encapsulated data to Collection, common in the fast entry batch data scene
    page: product name < input type= “text” name= “products[0].name” /> < br/> Action:public class ProductAction extends ActionSupport List&lt Product&gt {private; products; public; List< Product> getProducts (return) {products}; public void setProducts (List< Product> products) {this.products = products;}}

2.
page:
product name < input type= “text” name= “map[‘one’].name” /> < br/> one is map
Action
public class key: ProductAction2 extends ActionSupport {
private Map< String, Product> map;

Public Map< String; Product> getMap () {return map;} public; void; setMap (Map< String; Product> map); {this.map = map;}

Struts2 type converter

When we send a HTTP request, the content of the request to send a string to the server, so need to be converted to the types defined in Action, for example, if you have a integer property in the Action class, you do not need to perform any operation, Struts will request parameters into the integer attribute. For most common types, there is no converter needed to build, and Struts2 has many converters for common data types.

The type converter root interface in Struts2 is: com.opensymphony.xwork2.conversion.TypeConverter.

Custom type converter

  • Boolean and Boolean
  • Char and Character
  • Int and Integer
  • Long and Long
  • Float and Float
  • Double and Double
  • Date can receive yyyy-MM-dd formatted strings
  • Arrays can convert multiple name parameters into arrays
  • Collection supports saving data to a collection of List or Map

The Date type attribute can receive request format for the 2000-02-20 parameter, but if you want to receive the format for the 20000220 request parameters, it must be a custom type converter, otherwise Struts2 cannot complete automatic type conversion.

Step:

Method for creating a custom type converter

Register a custom type converter

  1. Create a class to implement the TypeConverter interface
  2. Override methods in the interface to implement type conversion operations
  3. Register type converter

Error handling in a type converter

  1. Implement TypeConverter, rewrite methods, public, Object, convertValue (Map&lt, String, Object&gt, context, Object, target, Member, member, String, propertyName, Object, value, Class, toType);
  2. Inheriting the DefaultTypeConverter class public, Object, convertValue (Map&lt, String, Object&gt, context, Object, value, Class, toType) {return, convertValue (value, toType)}
  3. Inherit a subclass of StrutsTypeConverter class DefaultTypeConverter public abstract Object convertFromString (recommended) (Map context, String[] values, Class toClass); public abstract String convertToString (Map context, Object o);

We want the user to enter the ABC string, def mode, the input string contains a comma separated English as username and password, if the user enters a English comma, or no input English comma will cause system abnormalities, because the type above converter will be normal solution a username and password, actually the presentation layer, data involving two treatments: a checksum of the data type conversion is closely related, only when the input data is valid data, the system can be effectively converted — of course, sometimes the user input data can be effectively converted, but it is still illegal data (assuming the need to enter a person the age of 200 is illegal, the input data). Therefore, the basis for valid type conversions can be made, and only after the data has been effectively converted type, the next step is to do the data validation.

  1. For the action
    to the local configuration file location and name: in the Action package to create a Action class -conversion.properties,
    configuration file: writing format: full class name attribute name = type converter
  2. For the model
    to the local configuration file location and name: in the model package to create a model class -conversion.properties,
    configuration file: writing format: full class name attribute name = type converter
  3. The global
    configuration file location and name: create a xwork-conversion.properties
    configuration file written in SRC format: Name: type = type converter to convert the

    for.PNG Struts2 dry cargo note - second days full name

Struts2 provides an interceptor called conversion-Error, which is registered in the default interceptor stack, and we look at the default configuration file for the Struts2 framework: the struts-default.xml file,

< interceptor, name=, “conversionError”, “class=”, “org.apache.struts2.interceptor.StrutsConversionErrorInterceptor”, />

Through the analysis of the interceptor role, when the type conversion error, automatically jump in the input view, input view page in < s:fieldError/>
display error information to create the ActionName.properties Action package, and presenting information in the local resource configuration file: invalid.fieldvalue. attribute name = error information

Request parameter validation

Two ways:

1. manual calibration (understanding)

2. configuration check (focus)
requirements: the action class must inherit from the ActionSupport
configuration file:

  • Manual check
  • Configuration check (XML)

Verifier provided by the system:

  • Inherit ActionSupport, override the validate () method, complete the validation in that method, and execute the validate () method before the other business methods
  • Verify that the page
    struts.xml configuration &lt after the error occurs; result, name=, input, > /validate/login.jsp< /result>
  • When did the validation error occur?
    this.addFieldError (“a”, “error information”); a collection of methods pointing to
    ; when the collection is not empty, turn to the error page.
    uses
    &lt in JSP pages; s:fielderror> displays all error messages;
    , < s:fielderror, fieldName=; “&gt”; displays specific name error messages

Required required calibrator

  • Location: the XML file is in the same package as the action class
  • Name: action class name -validation.xml
  • Xwork-validator-1.0.3.dtd constraint: xwork-core-2.3.7.jar < DOCTYPE validators! PUBLIC “-//Apache Struts//XWork Validator” 1.0.3//EN “http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd” >
  • Method:
    1) root element < validators>
    2) &lt field name= sub elements; the property name > < /field>, name name of the form field validation of the
    page is 3 &lt); field> sub element < type= field-validator > the verifier “is specified check
    check what?
    in xwork-core-2.3.7.jar /com/opensymphony/xwork2/validator/validators/default.xml < validator name=” required “class=” com.opensymphony.xwork2.validator.validators.RequiredFieldValidator “/> &lt validator; name=” requiredstring “class=” com.opensymphony.xwork2.validator.validators.RequiredStringValidator “/> &lt validator; name=” int “class=” com.opensymphony.xwork2.validator.validators.IntRangeFieldValidator “/& Gt; < validator name= “long” class= “com.opensymphony.xwork2.validator.validators.LongRangeFieldValidator” /> &lt validator; name= “short” class= “com.opensymphony.xwork2.validator.validators.ShortRangeFieldValidator” /> &lt validator; name= “double” class= “com.opensymphony.xwork2.validator.validators.DoubleRangeFieldValidator” /> &lt validator; name= “date” class= “com.opensymphony.xwork2.validator.validators.DateRangeFieldValidator” /> &lt validator; name= “expression” class= “com.opensymphony.xwork2.validator.validators.ExpressionValidator /> < validator” name= “fieldexpression” class= “com.opensymphony.xwork2.validator.validators.FieldExpressionValidator” /> &lt validator; name= “email” class= “com.opensymphony.xwork2.valid Ator.validators.EmailValidator /> &lt validator; name= “URL” class= “com.opensymphony.xwork2.validator.validators.URLValidator” /> &lt validator; name= “visitor” class= “com.opensymphony.xwork2.validator.validators.VisitorFieldValidator” /> &lt validator; name= “conversion” class= “com.opensymphony.xwork2.validator.validators.ConversionErrorFieldValidator” /> &lt validator; name= “stringlength” class= “com.opensymphony.xwork2.validator.validators.StringLengthFieldValidator” /> &lt validator; name= “regex” class= “com.opensymphony.xwork2.validator.validators.RegexFieldValidator” /> &lt validator; name= “conditionalvisitor” class= “com.opensymphony.xwork2.validator.validators.ConditionalVisitorFieldValidator” /> < field-validato 4) R> child elements < message> error information; < /message>
    5) < field-validator> child element < param name= ‘&gt’; value < /param> used to specify the parameters in the validator

< field-validator type=; required; > < message> gender cannot be empty; < /message> < /field-validator>

  • Required (required validator, requirements are checking the property value cannot be null)
  • Requiredstring (required string validator, are checking the property value cannot be null, and the length of more than 0 cases of silent * recognized string to space before and after)
  • Stringlength (string length validator, required check attribute values must be within the specified range, otherwise the check fails, the minLength parameter specifies the minimum length, the maxLength parameter specifies the maximum length, the trim parameter specifies the check
  • Before field, do you want to remove the space before and after the string?
  • Regex (regex validator, check the checked whether the attribute value matches a regular expression, the expression parameter specifies the regular expression, the caseSensitive parameter specifies the regular expression matching, is case insensitive, the default value is true)
  • Int (integer validator, which requires the integer value of field must be within the specified range, min specifies the minimum, and Max specifies the maximum)
  • Double (double precision floating point checker) requires field double precision floating point numbers must be within the specified range, min specifies the minimum, and Max specifies the maximum value
  • Fieldexpression (field OGNL expression validator, field requires an ognl expression that satisfies the expression parameter to specify the ognl expression, the logical expression based on ValueStack evaluation, true check by return, otherwise not by)
  • Email (mail address validator) requires that if the value of the property being checked is not empty, it must be a valid email address
  • URL (URL validator) requires that if the value of the property being checked is not null, it must be a valid URL address
  • Date (date validator, which requires the date value of field must be within the specified range, min specifies the minimum, and Max specifies the maximum)

Requiredstring required string calibrator

< field-validator type=; requiredstring; > param; name=; trim; > true< /param> < < message> user name cannot be empty; < /message> < /field-validator>

Stringlength: string length verifier

< field-validator type= > < stringlength; param name= "maxLength" > 10< /param> < param name= "minLength" > 2< /param> < param name= "trim" > true< /param> < message> < CDATA[]]>! [product name should be between 2-10 character; < /message> < /field-validator>

Int: integer calibrator

< field-validator type= > < int; param name= "Min" > 1< /param> < param name= "Max" > 150< /param> < message> age must be between 1-150 and < /message> < /field-validator>

Date: date validator

< field-validator type= > < date; param name= "Min" > 1900-01-01< /param> < param name= "Max" > 2050-02-21< /param> < message> birthday must be ${min} to ${max} < /message> < field-validator> url: network path calibrator < field-validator type= "URL" > < message> energy-saving home address must be a valid < /message> < /field-validator>

Email: mail address calibrator

< field-validator, type=, email, > < message> email address is invalid; < /message> < /field-validator>

Regex: regular expression checker

< field-validator type= > < regex; param name= "regexExpression" > < [CDATA[^13/d{9}$]]> < /param>!; < message> mobile phone number is not in the correct format! < /message> < /field-validator>

Fieldexpression: field expression check

< field-validator type= "fieldexpression" > < param; name= > expression < [CDATA[! (password==repassword)]]> < /param> < message> two password < /message> < /field-validator>

The name of the specified action in the method of checking
when the checksum file is ActionClassName-validation.xml, will implement the input validation on all processing methods in action, if you only need to check for a action in the action method, then, should check the file’s name ActionClassName-ActionName-validation.xml, where ActionName is the name of Struts.xml action. Such as:

< action name= "user_*" class= "com.java.action.UserAction" method= "{1}" > < result; name= "success" > /WEB-INF/page/message.jsp< /result> < result name= "input" > /WEB-INF/page/addUser.jsp< /result> < /action>

There are two methods in UserAction:
public String (add) throws Exception{}
public String (update) throws Exception{}
(add) method to perform verification, check file named: UserAction-user_add-validation.xml
update () method to the implementation of the verification, check file name: UserAction-user_update-validation.xml


The Action itself is encapsulated as a model object through the setter