Struts2 a custom type converter for the framework

Source: Internet
Author: User
Tags dateformat

Preface: For the basic data types of Java and some system classes (such as Date class, Collection Class), STRUTS2 provides built-in type conversion functionality, but there are some limitations. So the custom type converter is shown

First, apply to the local type converter

eg, user login The date of birth can only be converted successfully in 2016-06-09, then 2016/06/09 will not be successful, so it leads to our custom type converter

1 First we will do the preparatory work

1) login.jsp Registration page

<%@ page language="Java"import="java.util.*"pageencoding="Utf-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () +"://"+request.getservername () +":"+request.getserverport () +path+"/";%><! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en">Basehref="<%=basePath%>"> <title> Registration </title> "adduseraction"Method="Post">User name:<input type="text"Name="User.Name"/><br/>Age:<input type="text"Name="User.age"/><br/>Date of birth<input type="text"Name="User.birthday"/><br/> <input type="Submit"Value="Submit"/> </form> </body>

2) will be ready for Success page success.jsp

<%@ page language="Java"import="java.util.*"pageencoding="Utf-8"%><%String Path=Request.getcontextpath (); String BasePath= Request.getscheme () +"://"+request.getservername () +":"+request.getserverport () +path+"/";%><% @taglib uri="/struts-tags"prefix="s"%><! DOCTYPE HTML Public"-//w3c//dtd HTML 4.01 transitional//en">Basehref="<%=basePath%>"> <title> Success Pages </title> "User.birthday"/> </body>

3) will prepare the entity class user

 Public class User {    private  String name;     Private String age;     Private Date birthday;         // omit get and set}    

4) An action class will be prepared

Package cn.happy.action;import Cn.happy.entity.user;import com.opensymphony.xwork2.ActionSupport; Public classAdduseraction extends actionsupport{Privateuser User; @Override PublicString Execute () throws Exception {System. out. println (User.getbirthday ()); returnSUCCESS; }     PublicUser GetUser () {returnuser; }     Public voidsetUser (user user) { This. user =user; }    }

5) will be ready to adduseraction-conversion.properties the name of the first part of the adduseraction to be the same as the action class name, because it is local, so action and Adduseraction-conversion.propert IES placed in the same directory

6) Prepare the converter

Package Cn.happy.converter;import Java.text.dateformat;import java.text.parseexception;import Java.text.simpledateformat;import Java.util.map;import Org.apache.struts2.util.strutstypeconverter;import com.opensymphony.xwork2.conversion.TypeConversionException; Public classDateConverter extends Strutstypeconverter {PrivateFinal dateformat[] Dfs={            NewSimpleDateFormat ("YYYY/MM/DD")    }; @Override PublicObject convertfromstring (Map context, string[] values, Class totype) {String datestr=values[0];//Gets the date of the string         for(inti =0; i < dfs.length; i++) {            Try {                returnDfs[i].parseobject (DATESTR); } Catch(ParseException e) {Continue; }        }        //If there is still no successful conversion after the traversal, the conversion exception occurs        Throw Newtypeconversionexception (); } @Override PublicString converttostring (Map context, Object obj) {return NewSimpleDateFormat ("YYYY/MM/DD"). Format (obj); }}

7) Prepare a Adduseraction.xml

<?xml version="1.0"encoding="UTF-8"? ><!DOCTYPE Struts public"-//apache software foundation//dtd Struts Configuration 2.3//en"    "HTTP://STRUTS.APACHE.ORG/DTDS/STRUTS-2.3.DTD"><struts > <constant name="Struts.devmode"Value="true"/> <!--Create a default package that inherits from Struts2 Struts-default Package--<package name="default" namespace=""extends="Struts-default"> <action name="adduseraction" class="cn.happy.action.AddUserAction"> <!--Save directory path with param parameter settings--<result name="Success">/Convert/success.jsp</result> <result name="input">/Convert/login.jsp</result> </action> </package> &L T;/struts>

8) Quote a adduseraction.xml in Struts.xml

<?xml version="1.0" encoding="UTF-8" ? ><! DOCTYPE struts     Public " -//apache software foundation//dtd Struts Configuration 2.3//en "    " HTTP://STRUTS.APACHE.ORG/DTDS/STRUTS-2.3.DTD "><struts >        </package>    <include file="  Adduseraction.xml"></include></struts>

Second, global custom type converters

Under the above steps, change the

Adduseraction-conversion.properties---> Copy to src directory-----> renamed to Xwork-conversion.properties---> in file

Third, we will be in the date of birth if the error, we should give the hint!!!

1) In the case of global variables we first have to change the type converter to add

New SimpleDateFormat ("yyyy mm month DD Day")
Package Cn.happy.converter;import Java.text.dateformat;import java.text.parseexception;import Java.text.simpledateformat;import Java.util.map;import Org.apache.struts2.util.strutstypeconverter;import com.opensymphony.xwork2.conversion.TypeConversionException; Public classDateConverter extends Strutstypeconverter {PrivateFinal dateformat[] Dfs={            NewSimpleDateFormat ("YYYY/MM/DD"),            NewSimpleDateFormat ("yyyy mm month DD Day")    }; @Override PublicObject convertfromstring (Map context, string[] values, Class totype) {String datestr=values[0];//Gets the date of the string         for(inti =0; i < dfs.length; i++) {            Try {                returnDfs[i].parseobject (DATESTR); } Catch(ParseException e) {Continue; }        }        //If there is still no successful conversion after the traversal, the conversion exception occurs        Throw Newtypeconversionexception (); } @Override PublicString converttostring (Map context, Object obj) {return NewSimpleDateFormat ("YYYY/MM/DD"). Format (obj); }}

If your page input error will report an error that the field is invalid. -----"How to convert English to Chinese

Configuring <constant name= "struts.custom.i18n.resources" value= "message" /> in Strurts.xml is internationalized

In the configuration of a message.properties under the root directory src

So the page error will be displayed in Chinese

Struts2 a custom type converter for the framework

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.