Druid数据库连接池
-
Druid配置文件:druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/login
username=root
password=Wsd246503
initialSize=5
maxActive=10
maxWait=3000
minIdle=3 -
JDBCUtils类
连接数据池与返回连接池对象与连接对象
import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; //使用durid连接池 public class JDBCUtils { private static DataSource ds; static { try { //1.加载配置文件 Properties pro =new Properties(); InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //2.使用CLassLoader加载配置文件,获取字节输入流 ds = DruidDataSourceFactory.createDataSource(pro); }catch (Exception e) { e.printStackTrace(); } } //获取连接池对象 public static DataSource getDataSource(){ return ds; } //获取连接对象 public static Connection getConnection()throws Exception{ return ds.getConnection(); } }
-
UserDao类
与数据库打交道,查询语句,返回相应的对象
import org.springframework.dao.DataAccessException; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import javax.xml.transform.Templates; public class UserDao { //登录方法 //返回的方法包含全部数据 //声明JDBCTemplate对象共用 private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource()); public User login(User loginUser){ // String sql = "select * from 'user' where username = ? and password = ? "; try { String sql = "select * from user where username = ? and password = ? ;"; User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword() ); return user; } catch (DataAccessException e) { return null; } } }
-
LoginServlet类
对于表单数据就行验证,然后传递给FaliServlet类或者SuccessServlet类
还可使用BeanUtils类进行简化代码 -
BeanUtils类中有三个常用方法
eanUtils.setProperty(loginUser,“username”,“wsd”);
设置一个javaBean的值和属性相当于set
BeanUtils.getProperty(loginUser,“username”);
获取一个javaBean的属性相当于get
BeanUtils.populate(loginUser,mp);
将map<string.string[]>一一映射过去,简化了代码
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.xml.transform.Templates;
public class UserDao {
//登录方法
//返回的方法包含全部数据
//声明JDBCTemplate对象共用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
public User login(User loginUser){
// String sql = "select * from 'user' where username = ? and password = ? ";
try {
String sql = "select * from user where username = ? and password = ? ;";
User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword()
);
return user;
} catch (DataAccessException e) {
return null;
}
}
}
总结
登录表单首先将数据传给LoginServlet,然后servlet将数据发送给UserDao,UserDao返回检测的数据,然后LoginServlet再根据成功或者失败在进行相应的处理