一、需求
在Servlet中可以使用JDBC技术访问数据库,常见功能如下:
- 查询DB数据,然后生成显示页面,例如:列表显示功能。
- 接收请求参数,然后对DB操作,例如:注册、登录、修改密码等功能。
二、代码演示
1、编写注册界面
-
创建空工程,在工程中创建javaEE模块
-
配置中设置tomcat的部署
-
编写register界面
<!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>
2、编写Servlet 获取注册信息
- 编写servlet
- RegisterServlet
```javapackage com.example.register_demo01;import javax.servlet.*;import javax.servlet.http.*;import java.io.IOException;public class RegisterServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected 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);}}```
-
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"version="4.0"><servlet><servlet-name>RegisterServlet</servlet-name><servlet-class>com.example.register_demo01.RegisterServlet</servlet-class></servlet><servlet-mapping><servlet-name>RegisterServlet</servlet-name><url-pattern>/register</url-pattern></servlet-mapping> </web-app>
-
部署测试:
-
运行tomcat
-
访问注册界面,发送注册请求,tomcat获取注册信息
-
3、 创建原始User类
package com.example.register_demo01.pojo;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;}@Overridepublic String toString() {return "User{" +"id=" + id +", userName='" + userName + '\'' +", password='" + password + '\'' +'}';}
}
4、创建数据库
5、创建DbUtil,使用jdbc控制数据库
代码:
package com.example.register_demo01.utils;import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;public class DbUtil {private static String jdbcName;private static String dbUrl;private static String dbUserName;private static String dbPassword;//静态初始化操作static {jdbcName = "com.mysql.jdbc.Driver";dbUrl = "jdbc:mysql://localhost:3306/db_web";dbUserName = "root";dbPassword = "root";try {Class.forName(jdbcName);} catch (ClassNotFoundException e) {e.printStackTrace();}}public static Connection getConnection() throws SQLException {Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);return connection;}public static void closeConnection(Connection con) throws SQLException {if (null != con){con.close();}}}
6、编写UserDao,将User对象存储到数据库
代码:
package com.example.register_demo01.dao;import com.example.register_demo01.pojo.User;
import com.example.register_demo01.utils.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 connection1 = DbUtil.getConnection();//2、准备sqlString sql = "insert into t_user values(null, ?, ?)";//3、获取PreparedStatementpreparedStatement = connection.prepareStatement(sql);//4、向问号位置设置数据preparedStatement.setString(1, user.getUserName());preparedStatement.setString(2, user.getPassword());//5、执行sqlint row = preparedStatement.executeUpdate();return row;} catch (SQLException throwables) {throwables.printStackTrace();}finally {//6、关闭资源try {DbUtil.closeConnection(connection);if(preparedStatement != null){preparedStatement.close();}} catch (SQLException throwables) {throwables.printStackTrace();}}return -1;//执行失败}
}
7、修改Servlet,添加保存进数据库的操作
-
代码:
package com.example.register_demo01;import com.example.register_demo01.dao.UserDao; import com.example.register_demo01.pojo.User;import javax.servlet.*; import javax.servlet.http.*; import java.io.IOException; import java.io.PrintWriter;public class RegisterServlet extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request, response);}@Overrideprotected 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、封装user信息,将信息保存到数据库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 {System.out.println("注册失败");writer.write("<h1>注册失败!</h1>");}writer.close();} }
-
测试结果: