BeanUtil解析HttpServletRequest到Bean的测试

介绍如何将网页页面上表单传上来的参数,装配到用户自字义的Bean中。页面上一般传上来的时间都是形如2009-02-16的字符串。因此有必要定义一个解析类,对日期进行解析。方法如下:
package myutil; 
import java.lang.reflect.InvocationTargetException; 
import java.util.Map; 
import javax.servlet.http.HttpServletRequest; 
import org.apache.commons.beanutils.BeanUtils; 
import org.apache.commons.beanutils.ConvertUtils; 
import org.apache.commons.beanutils.converters.DateConverter; 
public class RequestToBean { 
  static { 
    DateConverter d = new DateConverter(); 
    String[] datePattern = { "yyyy-mm-dd", "yyyy/mm/dd", "yyyy.mm.dd" }; 
    d.setPatterns(datePattern); 
    ConvertUtils.register(d, java.util.Date.class); 
  } 

  public static void populate(HttpServletRequest request, Object obj) { 
    Map map = request.getParameterMap(); 
    try { 
      BeanUtils.populate(obj, map); 
    } catch (IllegalAccessException e) { 
      e.printStackTrace(); 
    } catch (InvocationTargetException e) { 
      e.printStackTrace(); 
    } 
  } 
} 

你可能感兴趣的:(java,apache,bean,servlet)