学习开发过程中有的代码分享下:供大家参考
使用SimpleDateFormat来进行日期格式的转换
- import java.text.SimpleDateFormat;
import com.dao.UserDao;
import com.domain.user;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;
import com.utils.DBUtils;
public class UserDaoImpl implements UserDao {
public void addUser(user user) throws Exception {
// TODO Auto-generated method stub
Connection conn = null;
PreparedStatement ps = null;
try {
conn = (Connection) DBUtils.getConnection();
ps = (PreparedStatement) conn.prepareStatement("insert into users (username,password,email,birthday) values(?,?,?,?,)");
ps.setString(1, user.getUsername());
ps.setString(2,user.getPassword());
ps.setString(3,user.getEmail());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
String date = sdf.format(user.getBirthday());
ps.setString(4,date);
int i = ps.executeUpdate();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException("添加失败");
}finally {
DBUtils.closeAll(null, ps, conn);
}
}
} - 看到有博主也是这样使用的
- @Test
- public void test2() throws Exception{
- User newUser=new User();
- String birthString="1993-09-30";
- ConvertUtils.register(new Converter(){
- @Override
- public Object convert(Class type, Object value) {
- if( type != Date.class) return null;
- if(value == null || "".equals(value.toString().trim())) return null;
- try {
- SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
- return sdf.parse(value.toString());
- } catch (ParseException e) {
- throw new RuntimeException(e);
- }
- }
- },Date.class);
- BeanUtils.copyProperty(newUser, "birth", birthString);
- System.out.println(newUser.getBirth());
- }
beanUtils的使用
- try {
BeanUtils.populate(user, request.getParameterMap());
//调用业务逻辑
UserService us = new UserServiceImpl();
try {
us.register(user);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (IllegalAccessException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}