当前位置:网站首页>1. Phase II of the project - user registration and login
1. Phase II of the project - user registration and login
2022-06-25 04:13:00 【@JiaHao】
The second stage —— User registration and login
1、JavaEE The three-tier architecture of the project

The purpose of layering is to decouple . Decoupling is to reduce the coupling of code . It is convenient for the maintenance and upgrading of the project later .
web layer com.my.book.web/servlet/controller
service layer com.my.book.service Service Interface package
com.my.book.service.impl Service Interface implementation class
dao Persistence layer com.my.book.dao Dao Interface package
com.my.book.dao.impl Dao Interface implementation class
Entity bean object com.my.book.pojo/entity/domain/bean JavaBean class
Test package com.my.book.test/junit
Tool class com.my.book.util
Build a Book City project development environment :

2、 First create the database and tables required by the book city .
database
drop database if exists book;
create database book;
use book;
create table t_user(
id int primary key auto_increment,
username varchar(20) not null unique,
password varchar(32) not null,
email varchar(200)
);
insert into t_user(username,password,email) values(admin,123,[email protected]);
select * from t_user;

3、 Write the corresponding database table JavaBean object
public class User {
private Integer id;
private String username;
private String password;
private String email;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public User(Integer id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
public User() {
}
}
4、 Write a tool class JdbcUtils
4.1、 Import required jar package ( The database and connection pool need ):

4.2、 stay src Source code directory under the preparation of jdbc.properties Properties profile :
username=root
password=root
url=jdbc:mysql://localhost:3306/book
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10
4.3、 To write JdbcUtils Tool class :
public class JdbcUtils {
private static DruidDataSource dataSource;
static {
try {
Properties properties = new Properties();
// Read jdbc.properties Properties profile
InputStream inputStream =
JdbcUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
// Loading data from a stream
properties.load(inputStream);
// establish Database connection pool
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Get the connections in the database connection pool
* If you return null, Failed to get the connection <br/> A value is a successful connection
*/
public static Connection getConnection(){
Connection conn = null;
try {
conn = dataSource.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
/**
* Close the connection , Put back the database connection pool
* @param conn
*/
public static void close(Connection conn){
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
4.4、JdbcUtils test
public class JdbcUtilsTest {
@Test
public void testJdbcUtils(){
for (int i = 0; i < 100; i++){
Connection connection = JdbcUtils.getConnection();
System.out.println(connection);
JdbcUtils.close(connection);// Remember to turn it off after use
}
}
}

This indicates that the connection is successful
5、 To write BaseDao
5.1、 Guide pack
Remember to guide before use DBUtils Of jar package
5.2、 To write BaseDao:
public abstract class BaseDao {
// Use DbUtils Operating the database
private QueryRunner queryRunner = new QueryRunner();
/**
* update() Method to execute :Insert\Update\Delete sentence
*
* @return If you return -1, Description the number of other rows that are affected by the execution failure
*/
public int update(String sql, Object... args) {
Connection connection = JdbcUtils.getConnection();
try {
return queryRunner.update(connection, sql, args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(connection);
}
return -1;
}
/**
* The query returns a javaBean Of sql sentence
*
* @param type Object type returned
* @param sql Executive sql sentence
* @param args sql The corresponding parameter value
* @param <T> The generic type of the returned type
* @return
*/
public <T> T queryForOne(Class<T> type, String sql, Object... args) {
Connection con = JdbcUtils.getConnection();
try {
return queryRunner.query(con, sql, new BeanHandler<T>(type), args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(con);// Closed flow
}
return null;
}
/**
* The query returns multiple javaBean Of sql sentence
*
* @param type Object type returned
* @param sql Executive sql sentence
* @param args sql The corresponding parameter value
* @param <T> The generic type of the returned type
* @return
*/
public <T> List<T> queryForList(Class<T> type, String sql, Object... args) {
Connection con = JdbcUtils.getConnection();
try {
return queryRunner.query(con, sql, new BeanListHandler<T>(type), args);
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtils.close(con);
}
return null;
}
/**
* Execution returns row by column sql sentence
* @param sql Executive sql sentence
* @param args sql The corresponding parameter value
* @return
*/
public Object queryForSingleValue(String sql, Object... args){
Connection conn = JdbcUtils.getConnection();
try {
return queryRunner.query(conn, sql, new ScalarHandler(), args);
} catch (Exception e) {
e.printStackTrace();
} finally {
JdbcUtils.close(conn);
}
return null;
}
6、 To write UserDao And testing
6.1、UserDao Interface :
public interface UserDao {
/**
* Query user information according to user name
* @param username user name
* @return If you return null, It means that there is no such user . vice versa
*/
public User queryUserByUsername(String username);
/**
* according to User name and password query user information
* @param username
* @param password
* @return If you return null, User name or password error , vice versa
*/
public User queryUserByUsernameAndPassword(String username,String password);
/**
* Save user information
* @param user
* @return return -1 Indicates that the operation failed , The others are sql The number of lines affected by the statement
*/
public int saveUser(User user);
}
6.2、UserDaoImpl Implementation class
public class UserDaoImpl extends BaseDao implements UserDao {
// According to the inquiry username
@Override
public User queryUserByUsername(String username) {
String sql = "select username,password,email from t_user where username = ?";
return queryForOne(User.class, sql, username);
}
@Override
public User queryUserByUsernameAndPassword(String username, String password) {
String sql = "select id,username,password,email from t_user where username = ? and password = ?";
return queryForOne(User.class, sql, username,password);
}
// Save the data
@Override
public int saveUser(User user) {
String sql = "insert into t_user(username,password,email) values(?,?,?)";
return update(sql, user.getUsername(),user.getPassword(),user.getEmail());
}
}
6.3UserDao test :
public class UserDaoTest {
UserDao userDao=new UserDaoImpl();
@Test
public void queryUserByUsername() {
if(userDao.queryUserByUsername("admin")==null){
System.out.println(" User available !");
}else{
System.out.println(" The user already exists ");
}
}
@Test
public void saveUser() {
System.out.println();
}
@Test
public void queryUserByUsernameAndPassword() {
if(userDao.queryUserByUsernameAndPassword("admin","123")==null){
System.out.println(" User password error , Login failed ");
}else{
System.out.println(" The query is successful ");
}
}
7、 To write UserService Sum measurement
7.1UserService Interface
public interface UserService {
// Registered users
public void registUser(User user);
// Sign in
public User login(User user);
// Check whether the user is available
//true Indicates that the user name exists
public boolean existsUsername(String username);
}
7.2、UserServiceImpl Implementation class :
public class UserServiceImpl implements UserService{
UserDao userDao=new UserDaoImpl();
@Override
public void registUser(User user) {
userDao.saveUser(user);
}
@Override
public User login(User user) {
return userDao.queryUserByUsernameAndPassword(user.getUsername(),user.getPassword());
}
@Override
public boolean existsUsername(String username) {
if (userDao.queryUserByUsername(username)==null) {
// be equal to null That means we didn't find , conversely
return false;
}
return true;
}
}
7.3、UserService test :
public class UserServiceTest {
UserService userService=new UserServiceImpl();
@Test
public void registUser() {
userService.registUser(new User(null,"pjh","666","[email protected]"));
userService.registUser(new User(null,"zjt","555","[email protected]"));
}
@Test
public void login() {
System.out.println(userService.login(new User(null,"pjh","666","[email protected]")));
}
@Test
public void existsUsername() {
if (userService.existsUsername("pjh168")) {
System.out.println(" User name already exists !");
} else {
System.out.println(" User name available !");
}
}
8、 To write web layer
8.1、 Realize the function of user registration
8.1.1、 Illustrate the process of user registration :
![[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-3qk9sxKp-1655786599875)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/923c4af974284258b04bfde5f0bb7bb5~tplv-k3u1fbpfcp-watermark.image?)]](/img/3a/8787dd84261d8f47095f7b72c58947.png)
8.1.2、 modify regist.html and regist_success.html page
1、 add to base mark
<!-- Write base label , Always fix the result of relative path jump -->
<base href="http://localhost:8080/book/">
2、 modify base The effect of tags on all relative paths in the page ( browser F12, Which report red , Which one )
<link type="text/css" rel="stylesheet" href="static/css/style.css" >
<script type="text/javascript" src="static/script/jquery-1.7.2.js"></script>
3、 Modify the submission address and request method of the registration form

8.1.3、 To write RegistServlet Program
public class RegistServlet extends HttpServlet {
private UserService userService=new UserServiceImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get the requested parameters
String username = req.getParameter("username");
String password = req.getParameter("password");
String email = req.getParameter("email");
String code = req.getParameter("code");
// The verification code is required to be ABCD
if("abcd".equalsIgnoreCase(code)){
// correct
// Check if the user name is available
if(userService.existsUsername(username)){
// Unavailable
System.out.println(" user name ["+username+"] Already exists ");
// Jump back to the registration page
req.getRequestDispatcher("/pages/user/regist.html").forward(req,resp);
}else{
// You can use , call service Save to database
userService.registUser(new User(null,username,password,email));
// Jump to registration succeeded register——success.html
req.getRequestDispatcher("/pages/user/regist_success.html").forward(req,resp);
}
}else{
// Jump back to the registration page
System.out.println(" Verification Code ["+code+"] error ");
req.getRequestDispatcher("/pages/user/regist.html").forward(req,resp);
}
}
}
8.2、IDEA in Debug Debug the
8.2.1、Debug Debugging code , First, you need two elements : The breakpoint + Debug Start the server
1、 The breakpoint , Just click to the left of the line where the code needs to stop , You can add and cancel
2、Debug start-up Tomcat
8.2.2、 Test toolbar :

8.2.3、 Other commonly used debugging related buttons :
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-RmvlwHn4-1655786599880)(https://p9-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/90cbef1cc21440d298e409ba1d5e4beb~tplv-k3u1fbpfcp-watermark.image?)]
8.3、 The realization of user login function :
8.3.1、 Graphical user login
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Y1WrD7Rn-1655786599882)(https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f59a48a310d8419ba6f25d47783f2c3c~tplv-k3u1fbpfcp-watermark.image?)]
8.3.2、 modify login.html Page and login_success.html page
1、 add to base mark
<!-- Write base label , Always fix the result of relative path jump -->
<base href="http://localhost:8080/book/">
2 modify login.html Form submission address and request method

8.3.3、LoginServlet Program
public class LoginServlet extends HttpServlet {
private UserService userService = new UserServiceImpl();
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 1、 Get the requested parameters
String username = req.getParameter("username");
String password = req.getParameter("password");
// call userService.login() Log in to handle business
User loginUser = userService.login(new User(null, username, password, null));
// If it is equal to null, Description login Failure !
if (loginUser == null) {
// Jump back to the login page
req.getRequestDispatcher("/pages/user/login.html").forward(req, resp);
} else {
// Sign in success
// Skip to success page login_success.html
req.getRequestDispatcher("/pages/user/login_success.html").forward(req, resp);
}
}
}
summary
2. Project phase II : Implementation of user registration and login .
demand 1: User registration
Requirements are as follows :
1) Visit the registration page
2) Fill in registration information , Submit to server
3) The server should save the user
4) When the user already exists ---- Prompt the user to register Failure , User name already exists
5) When the user doesn't exist ----- Registered successfully
demand 2: The user login
Requirements are as follows :
1) Visit the landing page
2) Fill in the user name and password and submit
3) The server determines whether the user exists
4) If login fails —>>>> Return user name or password error information
5) If login is successful —>>>>
边栏推荐
- 练习:仿真模拟福彩双色球——中500w巨奖到底有多难?跑跑代码就晓得了。
- [harmony OS] [ark UI] basic ETS context operations
- Development of trading system (IX) -- dark pool technology
- Text keyword extraction: ansj
- 【LeetCode】143. 重排链表
- PHP代码审计1—PHP.ini的那些事
- BSC parsing input data of transaction
- 【LeetCode】148. 排序链表
- How to use crawlers to capture bullet screen and comment data of station B?
- 2. play the chromatic harmonica
猜你喜欢

讲座记录《捷联惯导解算的历史及发展》

How to use crawlers to capture bullet screen and comment data of station B?

1. first knowledge of chromatic harmonica

长沙“求才”:“下力气”与“出实招”并进,“快发展”和“慢生活”兼得

How to draw an industry investment map

1.初识半音阶口琴

Deveco studio 3.0 editor configuration tips

9 necessary soft skills for program ape career development

opencv 红色区域在哪里?

Hello CTP (II) -- Introduction to CTP
随机推荐
Jilin University 22 spring March "official document writing" assignment assessment-00029
《悉达多》:一生之书,可以时常反刍
How to use crawlers to capture bullet screen and comment data of station B?
PHP code audit 2 - these functions must be known and understood
Crawler grabs the data of Douban group
Jilin University 22 spring March "automatic control principle" work assessment-00050
Understand (DI) dependency injection in PHP
【组队学习】SQL编程语言笔记——Task04
(ultra detailed onenet TCP protocol access) arduino+esp8266-01s accesses the Internet of things platform, uploads real-time collected data /tcp transparent transmission (and how to obtain and write Lu
2D 照片变身 3D 模型,来看英伟达的 AI 新“魔法”!
General steps for QT compiling database plug-ins
List rendering in wechat applet
“语法糖”——我的编程新知
opencv最大能打开多少图像?
SQL, CTE, FLG CASE问题
Development of trading system (XI) -- Introduction to quickfix
How much do you know about the use value of WMS warehouse management system
Development of trading system (XIII) -- Analysis of quickfix source code
Development of trading system (VII) -- Analysis of trading delay
代表多样性的彩色 NFT 系列上线 The Sandbox 市场平台