开发者

Format Spring CommandObject variable on the front end

开发者 https://www.devze.com 2023-03-10 07:21 出处:网络
How do I for开发者_StackOverflow中文版mat a value that is fetched from a command object on front end.

How do I for开发者_StackOverflow中文版mat a value that is fetched from a command object on front end.

Its an SSN value which comes from the DB without any "-" (Hyphens). How do I convert this?

example: Convert 123456789 into 123-45-6789. Also the in the backing bean this field is an Int.


How about creating a custom property editor? Spring uses custom property editors to format special data, like SSN.

An IntegerPropertyEditor looks like this:

package com.pnt.common.propertyeditor;

import java.beans.PropertyEditorSupport;
import com.pnt.util.number.NumUtils;

public class IntegerPropertyEditor extends PropertyEditorSupport {



//private static final Log logger = LogFactory.getLog(IntegerPropertyEditor.class);





public void setValue(Object value) {

    if (value==null) {
        super.setValue(null);
    } 

    else if (value instanceof Integer) {
        super.setValue(value);
    }

    else if (value instanceof String) {
        setValue(NumUtils.stringToInteger((String)value));
    }

    else {
        super.setValue(NumUtils.stringToInteger(value.toString()));
    }       
}


public void setAsText(String text) {
    setValue(NumUtils.stringToInteger(text.replaceAll(" ", "")));
}


public String getAsText() {
    Integer value = (Integer)getValue();
    if (value != null){ 
        String t = value.toString();
        int k = 1;
        for (int i = t.length() - 1; i >= 0; i--) {
            if (k % 3 == 0 && i != 0)
                t = t.substring(0, i) + " " + t.substring(i);
            k++;
        }
        return t;

    } 
    else 
        return "";
}
}

And you have to register it in the controller's initBinder() method:

protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder ){
    try {
        binder.registerCustomEditor(Integer.class, "ssnField", new IntegerPropertyEditor());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

Where "ssnField" is the name of the field.

Now all you have to do is tweak the PropertyEditor to match your format.


How about using fmt:substring

0

精彩评论

暂无评论...
验证码 换一张
取 消