Automatic encapsulation and type conversion of struts-base Content-Data

Source: Internet
Author: User
Tags dateformat

Automatic encapsulation of request data

Principle of implementation-parameter handling interceptor

<interceptor name= "Staticparams" class= "Com.opensymphony.xwork2.interceptor.StaticParametersInterceptor"/>

Way 1.jsp form data is populated with properties in the action

<%--Created by IntelliJ. User:cxspace Date:16-7-9Time : PM:39 to change ThisTemplate Use File | Settings |File Templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>User name:<input type= "text" name= "name" > <br>Password:<input type= "password" name= "pwd" > <br>Age:<input type= "text" name= "age" > <br>Birthday:<input type= "text" name= "Birth" > <br> <input type= "Submit" value= "register" > </form></bod Y>
Importjava.util.Date;/*** * Struts core business, request data Auto-encapsulation and type conversion * Created by Cxspace on 16-7-10.*/ Public classuseraction {//get the request data    PrivateString name; PrivateString pwd; Private intAge ; PrivateDate Birth; //You have to give the set method get without giving     Public voidsetName (String name) { This. Name =name; }     Public voidsetpwd (String pwd) { This. PWD =pwd; }     Public voidSetage (intAge ) {         This. Age =Age ; }     Public voidSetbirth (Date birth) { This. Birth =birth; }    //Processing Registration Requests      PublicString Register () {System.out.println (name);         System.out.println (PWD);         System.out.println (age);         System.out.println (birth); return"Success"; }}

Way 2.jsp The form data is populated with the properties in the object in the action-object type be sure to give the Get method

User

 PackageCom.cx.type;Importjava.util.Date;/*** Created by Cxspace on 16-7-10.*/ Public classUser {//get the request data    PrivateString name; PrivateString pwd; Private intAge ; PrivateDate Birth;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString getpwd () {returnpwd; }     Public voidsetpwd (String pwd) { This. PWD =pwd; }     Public intGetage () {returnAge ; }     Public voidSetage (intAge ) {         This. Age =Age ; }     PublicDate Getbirth () {returnbirth; }     Public voidSetbirth (Date birth) { This. Birth =birth; }}
Action

PackageCom.cx.type;/*** * Struts core business, request data Auto-encapsulation and type conversion * Created by Cxspace on 16-7-10.*/ Public classuseraction {Privateuser User; PublicUser GetUser () {returnuser; } Public voidsetUser (user user) { This. user =user; } //You have to give the set method get without giving//Processing Registration Requests PublicString Register () {System.out.println (User.getname ()); System.out.println (User.getpwd ()); System.out.println (User.getage ()); System.out.println (User.getbirth ()); return"Success"; }}
Jsp

<%--Created by IntelliJ. User:cxspace Date:16-7-9Time : PM:39 to change ThisTemplate Use File | Settings |File Templates.--%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>User name:<input type= "text" name= "User.Name" > <br>Password:<input type= "Password" name= "User.pwd" > <br>Age:<input type= "text" name= "User.age" > <br>Birthday:<input type= "text" name= "User.birth" > <br> <input type= "Submit" value= "register" > </form>&lt ;/body>

Type conversion-the use of converters

Strus the data that is submitted by the JSP, struts is automatically converted to the type of the property in the action

For basic data types and date types are automatically converted

Date type only supports YYYY-MM-DD format

Custom type converters are required

Local type Converters

Global type Converters

Struts Converter API

|----TypeConverter Converter interface

|----Default type converter class

|----Strutstypeconverter Converter class

Put 19900318 ==> 1990-03-18

I. Partial-type conversions

1. Write Converter class

 PackageCom.cx.type;ImportOrg.apache.struts2.util.StrutsTypeConverter;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Map;/*** Created by Cxspace on 16-7-10.*/ Public classMyconverterextendsStrutstypeconverter {/** * Convert a string to a specific type * * * The context of the current environment * * * * * * * * * * * in the values form*/@Override PublicObject convertfromstring (Map context, string[] values, Class aclass) {SimpleDateFormat SDF=NewSimpleDateFormat ("YyyyMMdd"); Try {            returnSdf.parse (values[0]); } Catch(ParseException e) {Throw NewRuntimeException (e); }} @Override PublicString converttostring (map map, Object o) {return NULL; }}

2. Configuring the Converter Class

Create a new property profile in the same package's action directory

The file naming rule: actionclassname-conversion.properties

3. Convert Content

Configuration file contents-contains the attributes to be converted and the corresponding processing classes

User.birth=com.cx.type.myconverter 

User.birth= Converter class full path (Com.cx.type.MyConverter)

4. This converter is not available for other action

Two. Global Converters

Write a converter for all action

--Build xwork-conversion.properties in the SRC directory

--Content

Type of conversion = Converter full path

 PackageCom.cx.type;Importorg.apache.struts2.components.Date;ImportOrg.apache.struts2.util.StrutsTypeConverter;ImportJava.text.DateFormat;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Map;/*** Created by Cxspace on 16-7-10.*/ Public classMyconverterextendsStrutstypeconverter {/** * Convert a string to a specific type * * * The context of the current environment * * * * * * * * * * * in the values form*/    //if the type of project to be supported many yyyy-mm-dd/yyyymmdd/yyyy MM month DD DayDateFormat [] DF= {            NewSimpleDateFormat ("Yyyy-mm-dd"),            NewSimpleDateFormat ("YyyyMMdd"),            NewSimpleDateFormat ("yyyy mm month DD Day")    }; //define the conversion formats supported in the project@Override PublicObject convertfromstring (Map context, string[] values, Class aclass) {//judgment content cannot be empty            if(values==NULL|| Values.length==0)            {                return NULL; }            //The judging type must be date            if(Date.class!=AClass) {                return NULL; }        //conversion failed the next loop         for(inti=0; i < df.length; i++)        {            Try {                returnDf[i].parse (values[0]); } Catch(ParseException e) {Continue; }        }        return NULL; } @Override PublicString converttostring (map map, Object o) {return NULL; }}

Automatic encapsulation and type conversion of struts-base Content-Data

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.