Discuss / Java / DataSource版实现注册登录

DataSource版实现注册登录

Topic source

jdk1.8

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>4.0.3</version>
</dependency>
public User login(String email, String password) throws SQLException {
    try (Connection conn = dataSource.getConnection();
         PreparedStatement ps = conn.prepareStatement("select * from user");
         ResultSet rs = ps.executeQuery()){
        while (rs.next()) {
            long dbId = rs.getLong("id");
            String dbEmail = rs.getString("email");
            String dbPassword = rs.getString("password");
            String dbName = rs.getString("name");
            if (dbEmail.equalsIgnoreCase(email) && dbPassword.equals(password)) {
                User user = new User(dbId, dbEmail, dbPassword, dbName);
                mailService.sendLoginMail(user);
                return user;
            }
        }
    }
    return null;
}

public User register(String email, String password, String name) throws SQLException {
    try (Connection conn = dataSource.getConnection()) {
        try (PreparedStatement ps = conn.prepareStatement("select * from user where email = ?")) {
            ps.setObject(1, email);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    throw new RuntimeException("email exist.");
                }
            }
        }
        try (PreparedStatement ps = conn.prepareStatement(
                "INSERT INTO user (email, password, name) VALUES (?,?,?)",
                Statement.RETURN_GENERATED_KEYS)) {
            ps.setObject(1, email);
            ps.setObject(2, password);
            ps.setObject(3, name);
            int n = ps.executeUpdate();
            try (ResultSet rs = ps.getGeneratedKeys()) {
                if (rs.next()) {
                    long dbId = rs.getLong(1);
                    User user = new User(dbId, email, password, name);
                    mailService.sendRegistrationMail(user);
                    return user;
                }
            }
        }
    }
    return null;}

  • 1

Reply