apache.commons.beanutils转换器的使用
2013-04-14 22:12
337 查看
有一个枚举类型的类:
为他定义一个转换器:
最后在Filter里面注册一下就行了:
public enum Gender { MAN{ public String getName(){return "男";} },WOMEN{ public String getName(){return "女";} }; public abstract String getName(); }
为他定义一个转换器:
import org.apache.commons.beanutils.Converter; import cn.aaron.bean.user.Gender; public class GenderConverter implements Converter{ @SuppressWarnings("unchecked") public Object convert(Class clazz, Object value) { if(value==null || "".equals((String)value)) return null; if(value instanceof Gender) return value;//如果要转换为枚举类型 try{//如果要转换为String类型 return Gender.valueOf((String) value); }catch (Exception e) {} return null; } }
最后在Filter里面注册一下就行了:
public class SetCodeFilter implements Filter{ public void destroy() {} public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterchain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; req.setCharacterEncoding("UTF-8"); filterchain.doFilter(request, response); } public void init(FilterConfig config) throws ServletException { ConvertUtils.register(new DateConverter(), Date.class); ConvertUtils.register(new SexConverter(), Sex.class); ConvertUtils.register(new GenderConverter(), Gender.class);//此处就是注册Gender转换器 ConvertUtils.register(new DeliverWayConverter(), DeliverWay.class); ConvertUtils.register(new PaymentWayConverter(), PaymentWay.class); try{ Properties prop = new Properties(); prop.put("runtime.log", config.getServletContext().getRealPath("/WEB-INF/log/velocity.log")); prop.put("file.resource.loader.path", config.getServletContext().getRealPath("/WEB-INF/vm")); prop.put("input.encoding", "UTF-8"); prop.put("output.encoding", "UTF-8"); Velocity.init(prop); }catch( Exception e ){ e.printStackTrace(); } } }
相关文章推荐
- 使用org.apache.commons.beanutils个人感受
- org.apache.commons.beanutils.PropertyUtils使用明细
- Apache Commons BeanUtils组件介绍使用
- Apache Commons beanutils使用
- apache-commons之BeanUtils、ConvertUtils、PropertyUtils、CollectionUtils的基本使用
- 使用org.apache.commons.beanutils个人感受
- Apache Commons Beanutils 一 (使用PropertyUtils访问Bean属性)
- Apache commons beanutils简介和使用
- org.apache.commons.beanutils.BeanUtils使用示例
- 利用Apache的commons-beanutils和commons-collections包实现Java对象的按属性排序
- com.qsoft.commons.beanutils源代码(.net版本的org.apache.commons.beanutils)
- Apache commons net 包介绍和简单使用
- 使用apache的BeanUtils封装数据
- 使用org.apache.commons.net.ftp包开发FTP客户端,实现进度汇报,实现断点续传,中文支持
- apache commons collections CollectionUtils工具类简单使用
- struts使用JSON时出现错误java.lang.NoClassDefFoundError: org/apache/commons/lang/xwork/StringUtils .
- java项目中添加邮件发送功能(使用apache commons mail开源项目)
- org.apache.commons.beanutils.BeanUtils 简介
- Apache Commons DbUtils 使用
- org.apache.commons.beanutils.BeanUtils