strusts2--Course Note 4

Source: Internet
Author: User

Type converters:

Struts2 by default, the text data entered in the form can be converted to the corresponding base data type. The implementation of this feature is mainly due to the Struts2 built-in type converter. These converters can see their definitions in Struts-default.xml.

A common type, basically, can be converted from a string to the appropriate type. Note, however, that date can only receive strings in YYYY-MM-DD or YYYY-MM-DD HH:mm:ss format.

Custom Converters:

1. Code:

 PackageCom.tongji.converter;Importjava.text.ParseException;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJava.util.regex.Pattern;ImportCom.opensymphony.xwork2.ActionContext;Importcom.opensymphony.xwork2.conversion.TypeConversionException;ImportCom.opensymphony.xwork2.conversion.impl.DefaultTypeConverter; Public classMydatetypeconverterextendsDefaulttypeconverter {//value is the data to be converted, and its type is an array of strings, because it is compatible with the data passed from the front end, is an array, such as a checkbox of multiple options, or a single data, such as text. //in the case of a single data, the first element in the array is taken from the code. //ToType is the type of data converted into@Override PublicObject Convertvalue (object value, Class totype) {Try {            if(ToType = = Date.)class) {//a page-to-server conversion from a string to a date typeString Source = ((string[)) value) [0]; SimpleDateFormat SDF=Getsimpledateformat (source); Actioncontext.getcontext (). GetSession (). Put ("SDF", SDF); returnsdf.parse (source); } Else if(ToType = = String.class) {//data echo: Server-to-page conversions from date to string typeSimpleDateFormat SDF = (SimpleDateFormat) actioncontext.getcontext (). GetSession (). Get ("SDF"); returnSdf.format ((Date) value); }        } Catch(ParseException e) {e.printstacktrace (); }        return Super. Convertvalue (value, ToType); }        PrivateSimpleDateFormat Getsimpledateformat (String source) {SimpleDateFormat SDF=NULL; if(Pattern.matches ("^\\d{4}/\\d{2}/\\d{2}$", source)) {SDF=NewSimpleDateFormat ("Yyyy/mm/dd"); } Else if(Pattern.matches ("^\\d{4}-\\d{2}-\\d{2}$", source)) {SDF=NewSimpleDateFormat ("Yyyy-mm-dd"); } Else if(Pattern.matches ("^\\d{4}\\d{2}\\d{2}$", source)) {SDF=NewSimpleDateFormat ("YyyyMMdd"); } Else {            Throw Newtypeconversionexception (); }                returnSDF; }    }

There are three points to note: One is that value represents an array, and the other is that the data type conversion is bidirectional, because there is the need for data echo, and the third is because the typeconversionexception exception is thrown when the type conversion fails, for subsequent processing.

  2. Configuration of the local type converter:

A local type converter that works only on the specified property of the specified action. To register, under the package under the action class, place a property file with the following format name:actionclassname-conversion.properties file. Where Actionclassname is the action class name,-conversion.properties is a fixed notation.

The contents of this property file follow the following format: Property name = Full class name of the type converter . Example: Birthday=com.tongji.converter.mydatetypeconverter

3. Implementation of data echo:

(1) The front-end code of the form submission:

<%@ Pagelanguage= "Java"Import= "java.util.*"pageencoding= "Utf-8"%><%@ taglibURI= "/struts-tags"prefix= "S"%><HTML>  <Head>    <title>Index page</title>  </Head>    <Body>      <S:formAction= "Test/login.action"Method= "POST">          <S:textfieldname= "Age"label= "Age"/>          <S:textfieldname= "Birthday"label= "Birthday"/>          <S:submitvalue= "Submit"/>      </S:form>  </Body></HTML>

    Use OGNL expressions to implement

    (2) struts2.xml Code:

<?XML version= "1.0" encoding= "UTF-8"?>    <!DOCTYPE struts Public "-//apache software foundation//dtd struts Configuration 2.3//en" "HTTP://STRUTS.APACHE.O Rg/dtds/struts-2.3.dtd "><Struts>    < Packagename= "Demo"namespace= "/test"extends= "Struts-default">        <Actionname= "Login"class= "Com.tongji.actions.LoginAction">            <resultname= "Success">/welcome.jsp</result>            <resultname= "Input">/index.jsp</result>        </Action>    </ Package></Struts>

The key to the data echo implementation is that when the data type conversion fails and the Typeconversionexception exception is thrown, the page request jumps to the input view, so you configure the front-end page for the input view.

    (3) Modification of the type conversion exception prompt information:

Type conversion exception hint information, is the system-defined content, if displayed directly to the user page, will make the page unfriendly. However, the type conversion exception hint information can be modified. The steps are as follows:

In the action package, add a property file named actionclassname.properties , where actionclassname is the class name of the action. Write content to this file:invalid.fieldvalue. Variable name = exception prompt Information

(4) Data echo final page display results:

      

4. Global type converter configuration:

A global type converter that takes effect on all properties of the specified type of action. It is registered by: in the SRC directory, place the name of the xwork-conversion.properties property file. The content format of the file is: the type to be converted = The full class name of the type converter

Java.util.date=com.tongji.converter.mydatetypeconverter

strusts2--Course Note 4

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.