下面我们讲的是在javaweb中对于Durid的使用,我们通过JDBC来连接数据库,我们会在一个登录案例中了解,在web项目中如何获取数据库连接对象。
这是JDBCUtils类相当于JDBC的工具类
public class JDBCUtils {
private static DataSource ds;
static {
try {
//1.加载配置文件,获取字节输入流
Properties props = new Properties();
//使用ClassLoder加载配置文件获取字节输入流
// InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
// props.load(is);
props.load(new FileReader("C:\Users\86157\Desktop\javatest\JavaWeb\Servlet\src\druid.properties"));
//初始化连接池对象
ds = DruidDataSourceFactory.createDataSource(props);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接池对象
public static DataSource getDataSource(){
return ds;
}
//获取Connection对象
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
这个呢是我们的连接JDBC的druid.properties配置文件
#driverClassName=com.mysql.jdbc.Driver driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql:///javaee username=root password=123456 initialSize=5 maxActive=200 maxWait=5000
接下来我们创建一个用户实体类,此类用来对接数据库中的数据
public class User {
private int id;
private String username;
private String password;
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + ''' +
", password='" + password + ''' +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserDao这个类呢,是用来匹配用户名和密码的。
利用template中的queryForObject方法执行sql,并把查询的到的user对象返回
public class UserDao {
//声明JDBCTemplate对象共用
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
public User login(User loginUser) {
try {
//1.编写sql
String sql = "select * from user where username = ? and password = ?";
//2.调用query方法
User user = template.queryForObject(sql,
new BeanPropertyRowMapper(User.class),
loginUser.getUsername(), loginUser.getPassword());
return user;
} catch (DataAccessException e) {
e.printStackTrace();//记录日志
return null;
}
}
}
下面是整个代码最核心的部分
登录页面的核心代码
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.设置编码
req.setCharacterEncoding("utf-8");
//2.获取所有请求参数
Map map = req.getParameterMap();
//3.创建User对象
User loginUser = new User();
//3.2使用BeanUtils封装
try {
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
//4.调用UserDao的login方法
UserDao dao = new UserDao();
User user = dao.login(loginUser);
//5.判断user
if(user == null){
//登录失败
req.getRequestDispatcher("/failServlet").forward(req,resp);
}else{
//登录成功
//存储数据
req.setAttribute("user",user);
//转发
req.getRequestDispatcher("/successServlet").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
一开始我们用的是这个方法获取的用户名和密码
//2.获取请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//3.封装user对象
User loginUser = new User();
loginUser.setUsername(username);
loginUser.setPassword(password);
后来我们用
request中的getParameterMap方法获取全部参数然后封装对象
//2.获取所有请求参数
Map map = req.getParameterMap();
//3.创建User对象
User loginUser = new User();
//3.2使用BeanUtils封装
try {
BeanUtils.populate(loginUser,map);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
然后是我们登录成功的页面和失败的页面
@WebServlet("/failServlet")
public class FailServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//给页面写一句话
//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录失败,用户名或密码错误");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取request域中共享的user对象
User user = (User) request.getAttribute("user");
if(user != null){
//给页面写一句话
//设置编码
response.setContentType("text/html;charset=utf-8");
//输出
response.getWriter().write("登录成功!"+user.getUsername()+",欢迎您");
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}



