用于对前台FormBean
import java.util.Date;//注意
import java.text.ParseException;
import java.text.SimpleDateFormat;
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.Converter;
public class WebUtils {
public static <T> T request2Bean(HttpServletRequest request,Class<T> beanClass){
try {
ConvertUtils.register(new Converter() {
@Override
public Object convert(Class arg0, Object value) {
if(value==null){
return null;
}
String s=(String)value;
if(s.trim().equals("")){
return null;
}
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
try {
return sdf.parse(s);
} catch (ParseException e) {
return null;
}
}
}, Date.class);//如果出现500错误且是指向转换错,可能就是导错包了!
T bean=beanClass.newInstance();
Map map=request.getParameterMap();
BeanUtils.populate(bean, map);
return bean;
} catch (Exception e) {
System.out.println("WEB异常");
throw new RuntimeException(e);
}
}
}