servlet+jdbc实现用户注册功能

一、需求

在Servlet中可以使用JDBC技术访问数据库,常见功能如下:

  • 查询DB数据,然后生成显示页面,例如:列表显示功能。
  • 接收请求参数,然后对DB操作,例如:注册、登录、修改密码等功能。

二、代码演示

1、编写注册界面

  1. 创建空工程,在工程中创建javaEE模块

  2. 配置中设置tomcat的部署
    servlet+jdbc实现用户注册功能_第1张图片
    servlet+jdbc实现用户注册功能_第2张图片

  3. 编写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 获取注册信息

  1. 编写servlet
  • RegisterServlet
 ```java
 package com.example.register_demo01;
 
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.io.IOException;
 
 public class RegisterServlet extends HttpServlet {
     @Override
     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         this.doPost(request, response);
     }
 
     @Override
     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);
     }
 }
 ```
  • web.xml

    
    <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>RegisterServletservlet-name>
            <servlet-class>com.example.register_demo01.RegisterServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>RegisterServletservlet-name>
            <url-pattern>/registerurl-pattern>
        servlet-mapping>
    web-app>
    
  1. 部署测试:

    • 运行tomcat

    • 访问注册界面,发送注册请求,tomcat获取注册信息

      servlet+jdbc实现用户注册功能_第3张图片

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;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", userName='" + userName + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

4、创建数据库

servlet+jdbc实现用户注册功能_第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、准备sql
            String sql = "insert into t_user values(null, ?, ?)";
            //3、获取PreparedStatement
            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 throwables) {
            throwables.printStackTrace();
        }finally {
            //6、关闭资源
            try {
                DbUtil.closeConnection(connection);
                if(preparedStatement != null){
                    preparedStatement.close();
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        }
        return -1;//执行失败

    }
}

7、修改Servlet,添加保存进数据库的操作

  1. 代码:

    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 {
        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            this.doPost(request, response);
        }
    
        @Override
        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、封装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("

    注册成功!

    "
    ); }else { System.out.println("注册失败"); writer.write("

    注册失败!

    "
    ); } writer.close(); } }
  2. 测试结果:

    servlet+jdbc实现用户注册功能_第5张图片

你可能感兴趣的:(tomcat,servlet,java,tomcat)