Servlet+JDBC应用
<1> 在Servlet中可以使用JDBC技术访问数据库,常见功能如下:
查询DB数据,然后生成显示页面,例如:列表显示功能
接收请求参数,然后对DB操作,例如:注册、登录、修改密码等功能
<2> 为了方便重用和便于维护等目的,经常会采用DAO(Data Access Object)模式对数据库操作进行 独立封装
<3> DAO工厂(工厂模式)
工厂类:封装了对象的创建细节,为调用者提供符合要求的对象
<4> demo01
Dao / UserDao.java
package com.lagou.demo01.dao; import com.lagou.demo01.model.User; import com.lagou.demo01.util.DbUtil; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; public class UserDao { public int createUser(User user) { Connection connection = null; PreparedStatement preparedStatement = null; try { // 1.获取连接 connection = DbUtil.getConnection(); // 2.准备sql语句 String sql = "insert into t_user values(null, ?, ?)"; // 3.获取PrepareStatement类型的引用 preparedStatement = connection.prepareStatement(sql); // 4.向问号所占的位置设置数据 preparedStatement.setString(1, user.getUserName()); preparedStatement.setString(2, user.getPassword()); // 5.执行sql语句 int row = preparedStatement.executeUpdate(); return row; // 执行成功 } catch (SQLException e) { e.printStackTrace(); } finally { // 6.关闭资源 try { DbUtil.closeConnection(connection, preparedStatement); } catch (SQLException e) { e.printStackTrace(); } } return 0; // 执行失败 } }
Model / User.java
package com.lagou.demo01.model; public class User { private int id; private String userName; private String password; public User() { } public User(String userName, String password) { this.userName = userName; this.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; } @Override public String toString() { return "User{" + "userName='" + userName + '\'' + ", password='" + password + '\'' + '}'; } }
Servlet / RegisterServlet.java
package com.lagou.demo01.servlet; import com.lagou.demo01.dao.UserDao; import com.lagou.demo01.model.User; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class RegisterServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1.获取请求对象中保存的用户名和密码信息 String userName = request.getParameter("userName"); System.out.println("获取到的用户名为:" + userName); String password = request.getParameter("password"); System.out.println("获取到的密码为:" + password); // 2.将接受到的用户名和密码信息打包成用户对象交给DAO层进行处理 User user = new User(userName, password); UserDao userDao = new UserDao(); int res = userDao.createUser(user); // 3.将处理结果响应到浏览器 response.setContentType("text/html;charset=utf-8"); PrintWriter writer = response.getWriter(); if (1 == res) { System.out.println("注册成功!"); writer.write("<h1>注册成功!</h1>"); } else { writer.write("<h1>注册失败!</h1>"); } writer.close(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } }
Test / DBUtilTest.java
package com.lagou.demo01.test; import com.lagou.demo01.util.DbUtil; import java.sql.Connection; import java.sql.SQLException; public class DbUtilTest { public static void main(String[] args) { Connection connection = null; try { connection = DbUtil.getConnection(); System.out.println("连接数据库成功!"); } catch (SQLException e) { e.printStackTrace(); } finally { /*try { DbUtil.closeConnection(connection); } catch (SQLException e) { e.printStackTrace(); }*/ } } }
Util / DBUtil.java
package com.lagou.demo01.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; public class DbUtil { private static String jdbcName; // 用于描述驱动信息 private static String dbUrl; // 用于描述URL信息 private static String dbUserName; // 用户描述用户名信息 private static String dbPassword; // 用户描述密码信息 // 进行静态成员的初始化操作 static { jdbcName = "com.mysql.jdbc.Driver"; dbUrl = "jdbc:mysql://localhost:3306/db_web"; dbUserName = "root"; dbPassword = "123456"; try { Class.forName(jdbcName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取连接 * @return * @throws SQLException */ public static Connection getConnection() throws SQLException { Connection con = DriverManager.getConnection(dbUrl, dbUserName, dbPassword); return con; } /** * 关闭连接 * @param con * @throws SQLException */ public static void closeConnection(Connection con, PreparedStatement psts) throws SQLException { if (null != con) { con.close(); } if (null != psts) { psts.close(); } } }
Web / index.jsp
<%-- Created by IntelliJ IDEA. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> $END$ </body> </html>
Web / register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>实现简单的注册功能</title> </head> <body> <form action="register" method="post"> 用户名:<input type="text" name="userName"/><br/> 密 码:<input type="text" name="password"/><br/> <input type="submit" value="注册"/> </form> </body> </html>