Discuss / Java / 练习:在上述示例的基础上,继续给UserService注入DataSource,并把注册和登录功能通过数据库实现

练习:在上述示例的基础上,继续给UserService注入DataSource,并把注册和登录功能通过数据库实现

Topic source

jasmine

#1 Created at ... [Delete] [Delete and Lock User]

创建user表

CREATE TABLE `user` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `email` varchar(128) DEFAULT NULL,
  `name` varchar(64) DEFAULT NULL,
  `password` varchar(128) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

pom.xml

<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.30</version>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>com.zaxxer</groupId>
			<artifactId>HikariCP</artifactId>
			<version>4.0.3</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>2.0.0-alpha0</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-jdk14</artifactId>
			<version>2.0.0-alpha0</version>
			<scope>runtime</scope>
		</dependency>

application.xml

<bean id="userService"
		class="com.itranswarp.learnjava.service.UserService">
		<property name="mailService" ref="mailService" />
		<property name="dataSource" ref="dataSource" />
	</bean>

	<bean id="mailService"
		class="com.itranswarp.learnjava.service.MailService" />

	<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/test" />
		<property name="username" value="root" />
		<property name="password" value="" />
		<property name="maximumPoolSize" value="10" />
		<property name="autoCommit" value="true" />
	</bean>

UserService.java

package com.itranswarp.learnjava.service;
import javax.sql.DataSource;
import java.security.MessageDigest;
import java.sql.*;

public class UserService {
	private MailService mailService;
	private DataSource dataSource;
	public void setMailService(MailService mailService) {
		this.mailService = mailService;
	}
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	public User login(String email, String password) {
		try (Connection conn = dataSource.getConnection()){
			PreparedStatement ps = conn.prepareStatement("select * from user where email = ?");
			ps.setObject(1, email);
			try (ResultSet rs = ps.executeQuery()) {
				if (rs.next()) {
					String dbPassword = rs.getString("password");
					if (dbPassword.equals(shaEncode(password))) {
						Long dbId = rs.getLong("id");
						String dbName = rs.getString("name");
						return new User(dbId, email, dbPassword, dbName);
					}
				} else {
					throw new RuntimeException("email not exist.");
				}
			}
			throw new RuntimeException("login password error.");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public User register(String email, String password, String name) throws SQLException {
		try (Connection conn = this.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, shaEncode(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;
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;}

	public DataSource getDataSource() {
		return dataSource;
	}


	public  String shaEncode(String inStr) throws Exception {
		MessageDigest sha = null;
		try {
			sha = MessageDigest.getInstance("SHA");
		} catch (Exception e) {
			System.out.println(e.toString());
			e.printStackTrace();
			return "";
		}
		byte[] byteArray = inStr.getBytes("UTF-8");
		byte[] md5Bytes = sha.digest(byteArray);
		StringBuffer hexValue = new StringBuffer();
		for (int i = 0; i < md5Bytes.length; i++) {
			int val = ((int) md5Bytes[i]) & 0xff;
			if (val < 16) {
				hexValue.append("0");
			}
			hexValue.append(Integer.toHexString(val));
		}
		return hexValue.toString();
	}
}

Main.java

User user = userService.register("tom@local.com", "password", "tomcat");
System.out.println(user.getName());

jasmine

#2 Created at ... [Delete] [Delete and Lock User]

运行结果

8月 23, 2022 9:47:55 上午 com.zaxxer.hikari.HikariDataSource getConnection
信息: HikariPool-1 - Starting...
8月 23, 2022 9:47:55 上午 com.zaxxer.hikari.HikariDataSource getConnection
信息: HikariPool-1 - Start completed.
Welcome, tomcat!
tomcat

流非沫

#3 Created at ... [Delete] [Delete and Lock User]

照抄下作业,这个答案好。


  • 1

Reply