STRUTS2 request data processing and interceptors (ii)

Source: Internet
Author: User
Tags i18n

Brief introduction

In the future if there is no special to say, in the introduction of the approximate knowledge points. Today we mainly study encapsulation request parameter and type conversion, user input checksum, internationalization, interceptor

Struts2 how to encapsulate request parameters
Mode one: The action itself, as a model object, is problematic through the Member setter encapsulation (implemented by an interceptor named params): Using the First Data encapsulation method, the data is encapsulated into the Action property, and the action object cannot be passed to the business layer   * You need to define a separate JavaBean, wrap the action attribute to JavaBean, and get the second way: action class and model separate, create model object in action, page encapsulated by OGNL expression (attribute-driven) mode three: model-driven model drivers are actually made by an interceptor. Modeldriven interceptors to do. The object returned by the Getmodel method is pressed into the top of a stack called Valuestack. The struts framework calls the setter method of the corresponding stack object based on the Name property of the form, encapsulating the request parameters in
Encapsulating Complex Type parameters (collection type Collection, MAP)
1. Encapsulate data to Collection Object page: Product name <input type= "text" name= "Products[0].name"/><br/>---> Note that the name here is consistent with action Action:public class Productaction extends Actionsupport {private list<product> products; Public list<product> getproducts () {return products;} public void Setproducts (list<product> products) {this.products = Products;}} 2. Encapsulate the data to the Map Object page: Product name <input type= "text" name= "map[' one '].name"/><br/>  ======= a  is the key value action of map :p ublic class 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;}}

Package Parameters--type conversion
1. Display or data echo: Other types----->string? basic Types Auto-Convert Boolean and Booleanchar and Characterint and Integerlong and Longfloat and Floatdouble and Dou blejava.util.date<-------->string (China: Struts2 is automatically converted by default in YYYY-MM-DD local format) # arrays can convert multiple parameters with the same name into an array # collection supports saving data to a list Or a Map collection summary: When using STRUTS2, you basically don't have to write any type converters. Built-in fully enough for 2. Custom type converter a). Implementation of the first implementation of the TypeConverter interface The second inheritance defaulttypeconverter the third inheritance strutstypeconverterb). The type converter has always been a bidirectional conversion page submission request parameter, encapsulated to model---need to convert the model data needs to be translated on the page----need to convert C). Register type Converter Local registration: Only valid for the current action (for attributes) Global registration: Valid for a type-local registration for all action's date type: The action class name-conversion.properties is created in the package where the action class is located. Format: Property name = Type converter full class name Global registration: Create xwork-conversion.properties under SRC, format: type to be converted = Type converter full class name 3. Page steering and error message when conversion fails A, configure a result view of name= "input", which generally points to the page B where the user entered the data, the error <%@ taglib in the JSP using the STRUTS2 label to display the field. Uri= "/ Struts-tags "prefix=" S "%><s:fielderror/>c, configuration prompt information for Chinese, in the action class in the package, establish a name called: Action class name. Properties configuration File

Validation of user input data
1. Check mode: A: Client check. (Anti-Gentleman is not the villain) write JS script in the page. Input the wrong words to remind more timely reduce the pressure on the server B, server-side Check Data security * * * * * * * * * * * * * * * * A+B2 Server-side Check # Programmatic check (code check): Write a checksum code (the disadvantage: The validation rules are written in the code) a). Overwrite the Validate method, complete the action of the business method data validation, in the JSP through the <s:fieldError/> display error information through the code logic to determine whether the parameters are valid, if the parameters are illegal, this.addfielderror ( Actionsupport provided) Workflow interceptor jumps back to input page b). Checks for the specified action one: Write a validate method, you can use the @skipvalidation with this annotation before the action method that does not need to be validated is ignored authentication method Two: Validate method has a certain writing specification. public void Validate Action method name (capitalized) Summary: All validations do not pass or convert different passes, and the framework will turn to the result view of name= "input". To display error prompts, use <s:fielderror/>, display field-related error message # Declarative checksum: Through XML configuration file a). Verify all actions in the action class in the package where the action class is located, establish a name called: "Action class name-validation.xml" configuration file * * Introduced in Dtd--xwork-core-2.3.7.jar/com/opensymphony/ XWORK2/VALIDATOR/VALIDATORS/DEFAULT.XMLB). Checks for the specified action one: use @skipvalidation mode two: the declaration file follows a certain writing specification: The action class name-the action name (in the Struts.xml configuration file)-VALIDATION.XMLC). Struts2 Framework built-in declarative type Validator * required (required validator, the property value required to be checked cannot be null) * Requiredstring (Required String validator, the property value required to be verified cannot be null, and the length is greater than 0, By default, the string is preceded by a space) * Stringlength (string length checker, the property value required to be validated must be within the specified range, otherwise the checksum fails, the minlength parameter specifies the minimum length, the MaxLength parameter specifies the maximum length, The trim parameter specifies the validation fieldWhether to remove the space before or after the string) * Regex (Regular expression validator, check whether the Checked property value matches a regular expression, the expression parameter specifies a regular expression, the CaseSensitive parameter specifies whether the regular expression matches, is case-sensitive, The default value is True) * INT (integer validator, which requires that the integer value of field must be within the specified range, min specifies the minimum value, max specifies the maximum) * double (double-precision floating-point number checker, which requires that the double-precision floating-point number of field must be within the specified range, min specifies the minimum value, MAX Specifies the maximum value) * fieldexpression (field OGNL expression Validator, which requires field to satisfy a OGNL expression, the expression parameter specifies the OGNL expression, which is evaluated based on Valuestack, Returns True when the checksum passes, otherwise does not pass) * Email (email address Checker, if the Checked property value is not NULL, it must be a legitimate email address) * URL (url validator, if the Checked property value is not NULL, then it must be a valid URL address) * Date (DateTime validator, The date value that requires field must be within the specified range, min specifies the minimum value, max Specifies the maximum value, and 3. Custom declarative checksum a). Write a class that implements the validator interface or inherits the Validatorsupport. If you are validating form fields, we recommend inheriting Fieldvalidatorsupporb. To register the validator, under the Web-inf\classes directory, establish a configuration file C with a fixed name of Validators.xml.  Use the validator to create an action class name in the action package-validation.xml**** the custom validator is seldom used in real development

The internationalization of Struts2
1. Configure global Internationalization Message resource bundle add <constant name= "struts.custom.i18n.resources" value= "messages" in Struts.xml ></constant > messages.properties in src root directory <constant name= "struts.custom.i18n.resources" value= " Cn.itcast.resources.messages "></constant> messages.properties in the Cn.itcast.resources package in the Action action class: premise, The action class inherits Actionsuppor/this.gettext ("MSG"); Used in JSP: <s:text name= "msg"/> in config file (checksum xml): <message key= "Agemsg" ></message>2. Configuring the local Message resource bundle data can only be used in the corresponding action, creating the Action class name in the package where the action class is located. The properties---------no need to configure local 3 higher priority than global. Packet-scoped Message resource bundle data is valid for all actions in the package (including the child package), and the package.properties-----created in the package does not need to be configured to write a canonical, named Package_zh_cn.properties, placed in the package of the class. 4 can be accessed by all action classes in the package and in the child package. Temporary information file (mainly introducing internationalized information in JSP) specifies which properties file to read in the JSP <s:i18n name= "cn.itcast.struts2.demo7.package" ><s:text name = "Customer" ></s:text></s:i18n> pass parameter {0} {1} to message------------messageformat dynamic message text This.gettext (" Required ", new string[] {" User name "});

Interceptor in Struts2 (core of frame function)
Use of interceptors, originating from spring AOP (aspect-oriented programming) thought interceptors take the responsibility chain model *  in the chain of responsibility model, many objects are linked together by each object's reference to its next-generation chain. *  Each node of the chain of responsibility can continue to invoke the next node, or prevent the process from continuing execution in Struts2, you can define a number of interceptors that make up the interceptor stack in a specific order (each interceptor in the sequential call stack) 1, struts2 all interceptors must implement the Interceptor Interface 2, the Abstractinterceptor class implements the Interceptor interface. And for Init, destroy provides a blank implementation of all actual developments, custom interceptors only need to inherit the Abstractinterceptor class, providing intercept method implementations 3, common STRUTS2 interceptors <interceptor-r EF name= "Modeldriven"/> Model driven <interceptor-ref name= "fileUpload"/> File upload <interceptor-ref name= "params" > Parameter resolution encapsulation <interceptor-ref name= "Conversionerror"/> type conversion error <interceptor-ref name= "Validation" > Request parameter Check < Interceptor-ref name= "Workflow" > Intercept jump Input view
Comprehensive case
Case: Login, access to other actions permission control through custom interceptors import jar packages (Struts2 jar, c3p0, dbutils, MySQL driver) Web. XML Struts.xmljdbcutils Tool class The first step: Writing IND EX.JSP provides four functions for adding and deleting books and adding bookaction, providing four business methods the second step: completing the landing function The third step: must log in for book management use filter for permission control----Filter all Web requests (all we b resource access) Use Interceptors for permission control----main intercept to action access (cannot intercept JSP) define Interceptor inheritance Abstractinterceptor Configure Interceptor Mode one <!--Register Interceptor-->< Interceptors><interceptor name= "privilege" class= "Cn.itcast.interceptor.PrivilegeInterceptor" ></ Interceptor></interceptors><action name= "book_*" class= "cn.itcast.action.BookAction" method= "{1}" > <!--using interceptors--><!--when a custom interceptor is used, the default interceptor will fail--><interceptor-ref name= "Defaultstack" ></ Interceptor-ref><interceptor-ref name= "privilege" ></interceptor-ref></action> way two <!-- Register Interceptor--><interceptors><interceptor Name= "privilege" class= " Cn.itcast.interceptor.PrivilegeInterceptor "></interceptor><!--custom Interceptor Stack--><interceptor-stack Name= "Privilegestack" &GT;&LT;interceptor-ref name= "Defaultstack" ></interceptor-ref><interceptor-ref name= "privilege" ></ interceptor-ref></interceptor-stack></interceptors><!--Set the current package all action uses a custom interceptor stack-->< Default-interceptor-ref name= "Privilegestack" ></default-interceptor-ref>

STRUTS2 request data processing and interceptors (ii)

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.