当前位置:网站首页>Login and registration based on servlet, JSP and MySQL
Login and registration based on servlet, JSP and MySQL
2022-06-11 06:02:00 【Not bald】
be based on servlet as well as MySQL Realize login and registration functions
Step 1 create table
1. Create a form to store user registration information , It is convenient to obtain later
create table user(
id int auto_increment,
username char(20) not null,
password char(20) not null,
email char(20) not null,
primary key(id)
) engine=innoDB default charset=utf8;

Step 2: create a database connection class JdbcUtils And bean class
1.JdbcUtils class
public class JdbcUtils {
// Program started , Priority operation
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Connection conn;
// Set to static Can be called directly
public static Connection getConnect() {
try {
if (conn == null || conn.isClosed()) {
// The last one is your own database name
String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
String username = "root";
String password = "root";
conn = DriverManager.getConnection(url, username, password);
}
return conn;
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
public static void close(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
if (st != null && !st.isClosed()) {
st.close();
}
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
2.bean class
Used to pass through bean To store or obtain relevant information from the database
public class User {
private String username;
private String password;
private String email;
public User() {
}
public User(String username, String password, String email) {
this.username = username;
this.password = password;
this.email = email;
}
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 String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
@Override
public String toString() {
return "User{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
3. establish Dao Class is used to write methods for login or registration , For the convenience of subsequent use , Reduce code duplication
public class UserDao {
private Connection conn;
private Statement st;
private PreparedStatement pst;
private ResultSet rs;
// Check whether the account number and password are correct
public User selectUserLogin(String username, String password) {
User user = null;
try {
conn = JdbcUtils.getConnect();
String sql = "select * from user where username=? and password=?";
pst = conn.prepareStatement(sql);
pst.setString(1,username);
pst.setString(2,password);
rs = pst.executeQuery();
if (rs.next()) {
user = new User();
user.setUsername(rs.getString("username"));
user.setPassword(rs.getString("password"));
user.setEmail(rs.getString("email"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.close(rs,pst,conn);
}
return user;
}
// The account , The password and mailbox are put into the database
public void insertIt(User user) {
conn = JdbcUtils.getConnect();
String sql = "insert into user(username,password,email) values(?,?,?)";
try {
pst = conn.prepareStatement(sql);
pst.setString(1,user.getUsername());
pst.setString(2, user.getPassword());
pst.setString(3, user.getEmail());
pst.executeUpdate();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
JdbcUtils.close(rs,pst,conn);
}
}
}
establish servlet Class and jsp page
1. Logon servlet as well as jsp page
Note the annotation configuration servlet And in web.xml There must be no conflict in the configuration , The following code contains the authentication for the administrator login
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
String username = req.getParameter("username");
String password = req.getParameter("password");
ServletContext application = req.getServletContext();
application.setAttribute("username", username);
// utilize session Store exception information
HttpSession session = req.getSession();
// utilize session Check if you are logged in
HttpSession check = req.getSession();
// Remove errors caused by whitespace
if (username == null || "".equals(username.trim())) {
session.setAttribute("error", " User name input error ");
// Can use request forwarding and redirection , Use redirection first , Prevent malicious occupation of resources
resp.sendRedirect(req.getContextPath() + "/login.jsp");
return;
}
if (password == null || "".equals(password.trim())) {
session.setAttribute("error", " Wrong password ");
// Can use request forwarding and redirection , Use redirection first , Prevent malicious occupation of resources
resp.sendRedirect(req.getContextPath() + "/login.jsp");
return;
}
UserDao userDao = new UserDao();
User user = userDao.selectUserLogin(username, password);
if (user == null || user.equals("")) {
session.setAttribute("error", " Wrong user name or password ");
resp.sendRedirect(req.getContextPath() + "/login.jsp");
} else if (username.equals("admin") && password.equals("admin")) {
req.setAttribute("admin", "admin");
req.getRequestDispatcher("/admin.jsp").forward(req, resp);
} else {
req.setAttribute("user", username);
req.getRequestDispatcher("/index.jsp").forward(req, resp);
}
}
}
Logon jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> Sign in / register </title>
<style>
* {
border: 0;
margin: 0;
}
.top-toolbar {
width: 100%;
height: 90px;
text-align: center;
background-color: black;
color: aliceblue;
}
.login {
background-color: darkgrey;
width: 100%;
height: 100%;
}
.rigister {
width: 60px;
height: 30px;
background-color: rgb(239, 239, 239);
border-radius: 10%;
}
#rig {
text-decoration: none;
line-height: 28px;
font-weight: normal;
}
</style>
</head>
<body>
<div class="top-toolbar">
<h1> Please log in </h1>
</div>
<div class="login">
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
<center>
${error}<br>
<table>
<tr>
<th>
user name :
</th>
<th>
<input type="text" name="username" style="width: 200px">
</th>
</tr>
<tr>
<th> password :</th>
<th>
<input type="password" name="password" style="width: 200px">
</th>
</tr>
<tr>
<th>
<input type="submit" value=" Sign in " style="width: 60px;height: 30px;border-radius: 10%">
</th>
<th>
<div class="rigister">
<a href="${pageContext.request.contextPath}/register.jsp"> register </a>
</div>
</th>
<th>
<div class="exist">
<a href="${pageContext.request.contextPath}/index.jsp"> sign out </a>
</div>
</th>
</tr>
</table>
</center>
</form>
</div>
</body>
</html>
2. Registered servlet as well as jsp page
@WebServlet("/RegisterServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("password");
String password1 = req.getParameter("s_password");
String email = req.getParameter("email");
String message = null;
if (password1.equals(password)) {
User user = new User(username, password, email);
user.setUsername(username);
user.setPassword(password);
user.setEmail(email);
// How to write to the database
UserDao userDao = new UserDao();
userDao.insertIt(user);
resp.sendRedirect(req.getContextPath() + "/login.jsp");
} else {
message = " Password inconsistency !";
req.setAttribute("Message", message);
req.getRequestDispatcher("/Message.jsp").forward(req, resp);
}
}
}
Registered jsp page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title> register </title>
<style>
* {
border: 0;
margin: 0;
}
.top-toolbar {
width: 100%;
height: 90px;
text-align: center;
background-color: black;
color: aliceblue;
}
.login {
background-color: darkgrey;
width: 100%;
height: 100%;
}
.rigister {
width: 60px;
height: 30px;
background-color: rgb(239, 239, 239);
border-radius: 10%;
}
#rig {
text-decoration: none;
line-height: 28px;
font-weight: normal;
}
</style>
</head>
<body>
<div class="top-toolbar">
<h1> Please log in </h1>
</div>
<div class="login">
<center>
<form action="${pageContext.request.contextPath}/RegisterServlet" method="post">
<table>
<tr>
<th>
user name :
</th>
<th>
<input type="text" name="username" style="width: 200px">
</th>
</tr>
<tr>
<th> password :</th>
<th>
<input type="password" name="password" style="width: 200px">
</th>
</tr>
<tr>
<th> Enter the password again :</th>
<th>
<input type="password" name="s_password" style="width: 200px">
</th>
</tr>
<tr>
<th>
mailbox :
</th>
<th>
<input type="text" name="email" style="width: 200px">
</th>
</tr>
<tr>
<th>
<input type="submit" value=" register " style="width: 60px;height: 30px;border-radius: 10%">
</th>
</tr>
</table>
</form>
</center>
</div>
</body>
</html>
边栏推荐
- NFC Development -- utility tools and development documents (IV)
- Quartz2d drawing technology
- Devsecops in Agile Environment
- 获取程序exit的值
- Summarize the five most common BlockingQueue features
- Control your phone with genymotion scratch
- ELK日志系统实战(六):技术选型之vector与filebeat对比
- Squid agent
- URL in flask_ for
- Solution to slow connection speed of ojdbc under Linux system
猜你喜欢

NDK learning notes (V)

20多种云协作功能,3分钟聊透企业的数据安全经

NDK R21 compiles ffmpeg 4.2.2+x264 and converts video files using ffmpeg

Do you know the functions of getbit and setbit in redis?

What happened to the young man who loved to write code -- approaching the "Yao Guang young man" of Huawei cloud

How to use perforce helix core with CI build server

Servlet

Sqli-libs post injection question 11-17 actual combat

Implementation of data access platform scheme (Youzu network)

Getting started with kotlin
随机推荐
Cenos7 builds redis-3.2.9 and integrates jedis
Slide the receleview horizontally to the far right to listen to the page loading function
DISM命令使用小结
Installing MySQL for Linux
Elk log system practice (VI): comparison between vector and filebeat for technology selection
使用Batch读取注册表
URL in flask_ for
NLP-D46-nlp比赛D15
NDK learning notes (IX) POSIX sockect connection oriented communication
ELK日志系统实战(五):安装vector并将数据输出到es、clickhouse案例
NDK R21 compiles ffmpeg 4.2.2+x264 and converts video files using ffmpeg
ELK日志系统实战(六):技术选型之vector与filebeat对比
How to use perforce helix core with CI build server
Sqli-libs range 23-24 filtration and secondary injection practice
Super explanation
Error:Execution failed for task ':app:buildNative'. & gt; A problem occurred'x/x/x/'NDK build' error resolution
Experimental report on information management and information system [information security and confidentiality] of Huazhong Agricultural University
Sword finger offer 32: print binary tree from top to bottom
[元数据]LinkedIn-DataHub
Using Internet of things technology to accelerate digital transformation