基于servlet以及MySQL实现登录及注册功能
第一步建表
1.创建表格有来储存用户的注册相关信息,方便后面进行获取
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;
第二步创建数据库连接类JdbcUtils及bean类
1.JdbcUtils类
public class JdbcUtils {
//程序启动,优先运行
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private static Connection conn;
//设置成static可以直接调用
public static Connection getConnect() {
try {
if (conn == null || conn.isClosed()) {
//最后一个是自己的数据库名
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类
用来向通过bean来向数据库进行储存或者获取相关信息
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.创建Dao类用来写入进行登录或者注册的方法,以方便后续使用,减少代码重复
public class UserDao {
private Connection conn;
private Statement st;
private PreparedStatement pst;
private ResultSet rs;
//检查账号和密码是否正确
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;
}
//将账号,密码还有邮箱放到数据库中
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);
}
}
}
创建servlet类以及jsp页面
1.登录的servlet以及jsp页面
注意注释配置servlet与在web.xml中配置不能有冲突,下面的代码中包含了对于管理员登录的验证
@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);
//利用session储存异常信息
HttpSession session = req.getSession();
//利用session检查是否登录
HttpSession check = req.getSession();
//去除空格导致的错误
if (username == null || "".equals(username.trim())) {
session.setAttribute("error", "用户名输入错误");
//能使用请求转发和重定向,优先使用重定向,防止恶意占用资源
resp.sendRedirect(req.getContextPath() + "/login.jsp");
return;
}
if (password == null || "".equals(password.trim())) {
session.setAttribute("error", "密码输入错误");
//能使用请求转发和重定向,优先使用重定向,防止恶意占用资源
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", "用户名或密码错误");
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);
}
}
}
登录的 jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录/注册</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>请登录</h1>
</div>
<div class="login">
<form action="${pageContext.request.contextPath}/LoginServlet" method="post">
<center>
${error}<br>
<table>
<tr>
<th>
用户名:
</th>
<th>
<input type="text" name="username" style="width: 200px">
</th>
</tr>
<tr>
<th>密码:</th>
<th>
<input type="password" name="password" style="width: 200px">
</th>
</tr>
<tr>
<th>
<input type="submit" value="登录" style="width: 60px;height: 30px;border-radius: 10%">
</th>
<th>
<div class="rigister">
<a href="${pageContext.request.contextPath}/register.jsp">注册</a>
</div>
</th>
<th>
<div class="exist">
<a href="${pageContext.request.contextPath}/index.jsp">退出</a>
</div>
</th>
</tr>
</table>
</center>
</form>
</div>
</body>
</html>
2.注册的servlet以及jsp页面
@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);
//写入数据库的方法
UserDao userDao = new UserDao();
userDao.insertIt(user);
resp.sendRedirect(req.getContextPath() + "/login.jsp");
} else {
message = "密码不一致!";
req.setAttribute("Message", message);
req.getRequestDispatcher("/Message.jsp").forward(req, resp);
}
}
}
注册的jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>注册</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>请登录</h1>
</div>
<div class="login">
<center>
<form action="${pageContext.request.contextPath}/RegisterServlet" method="post">
<table>
<tr>
<th>
用户名:
</th>
<th>
<input type="text" name="username" style="width: 200px">
</th>
</tr>
<tr>
<th>密码:</th>
<th>
<input type="password" name="password" style="width: 200px">
</th>
</tr>
<tr>
<th>再次输入密码:</th>
<th>
<input type="password" name="s_password" style="width: 200px">
</th>
</tr>
<tr>
<th>
邮箱:
</th>
<th>
<input type="text" name="email" style="width: 200px">
</th>
</tr>
<tr>
<th>
<input type="submit" value="注册" style="width: 60px;height: 30px;border-radius: 10%">
</th>
</tr>
</table>
</form>
</center>
</div>
</body>
</html>