This article is a mirror article of machine translation, please click here to jump to the original article.

View: 12756|Reply: 0

[JavaEE] struts2 custom time converter

[Copy link]
Posted on 12/24/2014 2:15:38 AM | | |
The default time format of struts2 is yyyy-MM-dd, and to use the yyyyMMdd format, you need to write a format converter
Partial:

Step 1: Write a time type converter that inherits from DefaultTypeConverter


[mw_shl_code=java,true]package utils;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import com.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;


/**
* @author Delver_Si
*
*/
public class DateConvert extends DefaultTypeConverter {


        @Override
        public Object convertValue(Map<String, Object> context, Object value,
                        Class toType) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
               
                        try {
                                if(toType==Date.class){
                                        String[] params = (String[]) value;
                                        return dateFormat.parseObject(params[0]); The first element in the array is the one to be transformed
                                }else if (toType==String.class) {
                                        Date date = (Date) value;
                                        return dateFormat.format(date);
                                }
                        } catch (ParseException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                        }
                        return null;
                }
               
        }
[/mw_shl_code]


Create the following format configuration file under the action package, with the Action name before -conversion.properties and the full path of the converter after the property


Big picture:

The configuration file is modified as follows, placed in the src directory












Previous:struts2file upload
Next:ajax goes to the database to verify that the username is registered without submitting the form
Disclaimer:
All software, programming materials or articles published by Code Farmer Network are only for learning and research purposes; The above content shall not be used for commercial or illegal purposes, otherwise, users shall bear all consequences. The information on this site comes from the Internet, and copyright disputes have nothing to do with this site. You must completely delete the above content from your computer within 24 hours of downloading. If you like the program, please support genuine software, purchase registration, and get better genuine services. If there is any infringement, please contact us by email.

Mail To:help@itsvse.com