日期:2014-05-17 浏览次数:20898 次
有一个枚举类型的类:
?
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(); } } }