1.前言
相信刚学Javaweb的小伙伴第一个接触的个人小项目都是从项目的登录注册开始的。 下面一个小项目中的登录注册将会带大家从零开始学习怎么设计登录注册流程.
2.登录注册设计流程
3.注册的数据流程
那么我们的前端数据是怎么传向后端的? 1.首先这里我们是用 表单传递 通过form提交
2.在这里,我们输入自己的姓名和密码,点击注册按钮。此时输入的这三个数据,我们可以看做成是一个表单的数据,这些数据会提交到服务器上:
3.此时,一个叫Tomcat的东西会处理这个请求,
4.得到请求之后,Tomcat会将这个请求交由Servlet来进行处理
5.Servlet调用Dao层写的各种实现方法,与数据库进行交互(curd调用仔)
那么下面就是注册操作的主要调用流程图
register.jsp
registServlet
UserDB
第一步
第二步
第三步
4.登录的数据流程
登录操作的主要调用流程图
Login.jsp
LoginServlet
UserDB
第一步
第二步
第三步
第四步
5.部分代码的展示
5.1注册
register.jsp注册页面 通过表单实现跳转到servlet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width",initial->
<link rel="stylesheet" href="style.css">
<title>world message board of the future</title>
</head>
<body background="pictures/02.jpg">
<div class="form-wrapper">
<div class="header">
Register
</div>
<form action="RegistServlet" method = "post">
<!-- 浏览者单击发送按钮发送表单的时候,隐藏域的信息也被一起发送到服务器。 -->
<input type="hidden" name="action" value="regist">
<div class="input-wrapper">
<div class="border-wrapper">
<input type="text" name="username" placeholder="username" class="border-item">
</div>
<div class="border-wrapper">
<input type="text" name="password" placeholder="password" class="border-item">
</div>
<div class="border-wrapper">
<input type="password" name="password2" placeholder="Confirm password" class="border-item">
</div>
<div class="action">
<input type="submit" name="regist" class="btn" value="Regist" ><br>
</div>
</div>
</form>
<center>
<!-- 获取注册是否成功信息 -->
<p class="col">${message}</p>
</center>
</div>
</body>
</html>
复制代码
RegisterServlet.java
业务层:处理注册业务
package Sevlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javaBean.User;
import useBean.UserDB;
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String message ="";
public RegistServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//获取隐藏域的信息
String action = request.getParameter("action");
String url ="register.jsp";
if(action.equals("regist"))
url = registerUser(request,response);
getServletContext().getRequestDispatcher(url).forward(request, response);
}
//注册函数
private String registerUser(HttpServletRequest request,HttpServletResponse response) {
String username = request.getParameter("username");
String password = request.getParameter("password");
String password2 = request.getParameter("password2");
String message = "";
//得到HttpSession类型的对象
HttpSession session = request.getSession();
//将数据存储于User对象
User user = new User();
user.setusername (username);
user.setpassword(password);
String url = "/login.jsp";
if(password.equals(password2))
{
if( !UserDB.UserExists(username) ) {
message = "Registration successful! and login in";
session.setAttribute("message", message);
//将注册用户信息写入数据库
UserDB.insert(user);
return url;
}
else
{
message = "The user name already exists";
url = "/register.jsp";
session.setAttribute("message", message);
return url;
}
}
else
{
message = "The password is inconsistent";
session.setAttribute("message", message);
url = "/register.jsp";
return url;
}
}
}
复制代码
Dao层实现判断用户名是否存在和插入数据库的方法 UserDB.java
//注册时判断用户名是否存在
public static boolean UserExists(String username) {
//可以建立一个连接池保存一定数量的连接,当有对象需要数据库连接时,直接将这个连接返回给该对象,
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
String qr = "SELECT username FROM User "+ "WHERE username = ?";
try {
ps = connection.prepareStatement(qr);
ps.setString(1, username);
rs = ps.executeQuery();
return rs.next();
} catch (SQLException e) {
System.out.println(e);
return false;
} finally {
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
//将注册用户信息保存至数据库
public static int insert(User user) {
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
String qr = "INSERT INTO User (username, password)"+"VALUES (?, ?)";
try {
ps = connection.prepareStatement(qr);
ps.setString(1, user.getusername());
ps.setString(2, user.getpassword());
return ps.executeUpdate();
} catch (SQLException e) {
System.out.println(e);
return 0;
} finally {
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
复制代码
5.2登录
login.jsp登录界面 通过表单实现跳转到servlet
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width",initial->
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="style.css">
<title>world message board of the future</title>
</head>
<body background="pictures/01.jpg">
<div class="form-wrapper">
<div class="header">
login
</div>
<form action="LoginServlet" method = "post"><!--form表单,你提交后,会跳转到LoginServlet -->
<!-- 浏览者单击发送按钮发送表单的时候,隐藏域的信息也被一起发送到服务器。 -->
<input type="hidden" name="action" value="login">
<div class="input-wrapper">
<div class="border-wrapper">
<input type="text" name="username" placeholder="input username" class="border-item">
</div>
<div class="border-wrapper">
<input type="password" name="password" placeholder="password" class="border-item">
</div>
</div>
<div class="action">
<input type="submit" name="login" class="btn" value="Sign in" ><br>
<button type="submit" formaction="register.jsp" class="btn">register</button>
</div>
</form>
<center>
<!-- 获取登录是否成功信息 -->
<p class="col">${message}</p>
</center>
</div>
</body>
</html>
复制代码
LoginServlet.java 业务层:处理登录业务
package Sevlet;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javaBean.Message;
import javaBean.User;
import useBean.UserDB;
/**
* Servlet implementation class Login
*/
@WebServlet("/LoginServlet")//读取/LoginServlet完整路径
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
String message="";//定义一个变量
public LoginServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url ="/login.jsp";
String action = request.getParameter("action");
System.out.println("action: " + action);//打印测试
//设置编码
request.setCharacterEncoding("utf-8");
//检测页面是否完成提交
if(action == null)
url="/login.jsp";
else if(action.equals("login"))
//调用login()函数返回一个路径
url = login(request,response);
//设置登入是否成功的提示信息
request.setAttribute("message", message);
//调用forward()方法,转发请求
getServletContext().getRequestDispatcher(url).forward(request, response);
}
//login()函数
private String login(HttpServletRequest request, HttpServletResponse response) {
//获取登入的信息(姓名和密码)
String username = request.getParameter("username");
String password = request.getParameter("password");
//得到HttpSession类型的对象
HttpSession session = request.getSession();
String userid="";
//通过名字得出user的信息
User user = UserDB.selectUser(username);
String url = "/register.jsp";
if(user != null) {
//用户存在,比较密码
if(user.getpassword().equals(password)) {
//用于记录该用户状态
//cookie加入用户名
Cookie u = new Cookie("userid",username);
//设置有效期
u.setMaxAge(60*60*24*365*2);
//设置路径
u.setPath("/");
//将cookie加入浏览器
response.addCookie(u);
userid = user.getid();
session.setAttribute("userid", userid);
//调用selectU从message表中读出所有数据
List<Message> mL = UserDB.selectU();
//返回ml信息
request.setAttribute("MessageList", mL);
url="/MessageList.jsp";
}
else {
message = "Wrong password";
url="/login.jsp";
}
}
else {
message = "The user does not exist";
url = "/login.jsp";
}
return url;
}
}
复制代码
UserDB.java Dao层实现查找用户的方法DB.java
//登录时根据username读出user
public static User selectUser(String username) {
//可以建立一个连接池保存一定数量的连接,当有对象需要数据库连接时,直接将这个连接返回给该对象,
ConnectionPool pool = ConnectionPool.getInstance();
Connection connection = pool.getConnection();
PreparedStatement ps = null;
ResultSet rs = null;
//sql语句
String qr = "SELECT * FROM User "+ "WHERE username = ?";
try {
ps = connection.prepareStatement(qr);
//sql语句中问号的解释
ps.setString(1, username);
rs = ps.executeQuery();
User user = null;
if (rs.next()) {
user = new User ();
//设置userd的id,username,passward
user.setid(rs.getString("id"));
user.setusername(rs.getString("username"));
user.setpassword(rs.getString("password"));
}
return user;
} catch (SQLException e) {
System.out.println(e);
return null;
} finally {
//关闭PreparedStatement和ResultSet并释放连接池中此次连接
DBUtil.closeResultSet(rs);
DBUtil.closePreparedStatement(ps);
pool.freeConnection(connection);
}
}
复制代码
6.总结
以上所有登录注册源代码来自本人的一个项目,感兴趣的小伙伴可以在评论区留言。十分愿意与大家分享共同学习。欢迎批评指正!
作者:小吴爱编程
链接:https://juejin.cn/post/6955752139729666078
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。