登录注册案例(Servlet+JSP+Maven)
案例代码
设计表
pom.xml
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
</dependencies>
jdbc
JDBCUtils.java
package jdbc;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class JDBCUtils {
public static Connection connection;
private static String url="jdbc:mysql://localhost:3306/aaa?useUnicode=true&characterEncoding=utf-8";
private static String username="root";
private static String password="root";
static{
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
return connection;
}
@Test
public void test(){
Connection connection = JDBCUtils.getConnection();
System.out.println(connection);
}
}
entity
User.java
package entity;
public class User {
private int id;
private String username;
private String password;
public User() {
}
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public int getId() {
return id;
}
public void setId(int 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;
}
}
dao
UserDao.java
package dao;
import entity.User;
import jdbc.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class UserDao {
private Connection connection = JDBCUtils.getConnection();
private PreparedStatement ps;
/*
*添加用户
* */
public int add(User user) throws Exception{
String sql = "insert into user(username,password) values(?,?)";
ps=connection.prepareStatement(sql);
ps.setObject(1,user.getUsername());
ps.setObject(2,user.getPassword());
int exe = ps.executeUpdate();
return exe;
}
public int delete(int id) throws SQLException {
String sql = "delete from user where id=?";
ps = connection.prepareStatement(sql);
/*
* 删除用户
* */
ps.setObject(1,id);
int exe = ps.executeUpdate();
return exe;
}
/*
* 修改用户
* */
public int update(User user) throws SQLException {
String sql = "update user set username=? , password=? where id=?";
ps = connection.prepareStatement(sql);
ps.setObject(1,user.getUsername());
ps.setObject(2,user.getPassword());
ps.setObject(3,user.getId());
return ps.executeUpdate();
}
/*
* 查询所有用户
* */
public List<User> findAll() throws SQLException {
String sql = "select * from user";
ps=connection.prepareStatement(sql);
ResultSet rs =ps.executeQuery();
List<User> list = new ArrayList<User>();
while(rs.next()){
//以 Java 编程语言中 int 的形式获取此 ResultSet 对象的当前行中指定列的值。
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
User u = new User(id,username,password);
list.add(u);
}
return list;
}
/*
* 通过id查询用户
* */
public User findById(int id) throws SQLException {
String sql = "select * from user where id=?";
ps=connection.prepareStatement(sql);
ps.setInt(1,id);
ResultSet rs = ps.executeQuery();
User u = null;
while (rs.next()){
int uid = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
u = new User(uid,username,password);
}
return u;
}
/*
* 用户登录
* */
public User login(User user) throws SQLException {
String sql = "select * from user where username=? and password=?";
ps = connection.prepareStatement(sql);
ps.setObject(1,user.getUsername());
ps.setObject(2,user.getPassword());
ResultSet rs = ps.executeQuery();
User u = null;
while (rs.next()){
int uid = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
u = new User(uid,username,password);
}
return u;
}
}
service
UserService.java
package service;
import dao.UserDao;
import entity.User;
import java.sql.SQLException;
import java.util.List;
public class UserService {
private UserDao userDao = new UserDao();
public int add(User user) throws Exception {
return userDao.add(user);
}
public int delete(int id) throws SQLException {
return userDao.delete(id);
}
public int update(User user) throws SQLException {
return userDao.update(user);
}
public List<User> findAll() throws SQLException {
return userDao.findAll();
}
public User findByID(int id) throws SQLException {
return userDao.findById(id);
}
public User login(User user) throws SQLException {
return userDao.login(user);
}
}
servlet
LoginServlet.java
package servlet;
import entity.User;
import service.UserService;
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 java.io.IOException;
import java.sql.SQLException;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//接受请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
User user = new User();
user.setUsername(username);
user.setPassword(password);
//查询数据
UserService us = new UserService();
User u = null;
try {
u=us.login(user);
//跳转
if (u==null){
req.setAttribute("mess","账号或密码错误");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}else {
req.getSession().setAttribute("user",u);
resp.sendRedirect("main.jsp");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
RegServlet.java
package servlet;
import dao.UserDao;
import entity.User;
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 java.io.IOException;
@WebServlet("/reg")
public class RegServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
//接受请求参数
String username = req.getParameter("username");
String password = req.getParameter("password");
User u = new User();
u.setUsername(username);
u.setPassword(password);
UserDao dao = new UserDao();
int i = 0;
try {
i=dao.add(u);
} catch (Exception e) {
e.printStackTrace();
}
//跳转
if(i>0){
req.setAttribute("mess","注册成功");
resp.sendRedirect("login.jsp");
}else{
req.setAttribute("mess","注册失败");
req.getRequestDispatcher("regist.jsp").forward(req,resp);
}
}
}
jsp
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>regist.jsp</welcome-file>
</welcome-file-list>
</web-app>
regist.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>注册</title>
</head>
<body>
<h1>用户注册</h1>
<hr>
<form action="reg" method="post">
<p>
用户名:<input type="text" name="username">
</p>
<p>
密码:<input type="text" name="password">
</p>
<p>
<input type="submit" value="注册">
</p>
</form>
${mess}
</body>
</html>
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<h1>用户登录</h1>
<hr>
<form action="login" method="post">
<p>
用户名:<input type="text" name="username">
</p>
<p>
密码:<input type="text" name="password">
</p>
<p>
<input type="submit" value="登录">
</p>
</form>
${mess}
</body>
</html>
main.jsp
<%--
Created by IntelliJ IDEA.
User: Lenovo
Date: 2019/4/25
Time: 9:11
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>主页</title>
</head>
<body>
<h1>欢迎使用本系统</h1>
当前用户:${sessionScope.user.username}
</body>
</html>
*****************************************************************************************************
我的博客园地址:https://www.cnblogs.com/zyx110/
![](https://img2023.cnblogs.com/blog/1640688/202310/1640688-20231012163445590-1187111631.png)
作者:泰斗贤若如
微信公众号:去有风的地方飞翔
Github:https://github.com/zyx110
有事微信:zyxt1637039050
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接,否则保留追究法律责任的权利。
![](https://img2020.cnblogs.com/blog/1640688/202012/1640688-20201211232610620-1651706581.png)
我不能保证我所说的都是对的,但我能保证每一篇都是用心去写的,我始终认同: “分享的越多,你的价值增值越大”,我们一同在分享中进步,在分享中成长,越努力越幸运。再分享一句话“十年前你是谁,一年前你是谁,甚至昨天你是谁,都不重要。重要的是,今天你是谁,以及明天你将成为谁。”
人生赢在转折处,改变从现在开始!
支持我的朋友们记得点波推荐哦,您的肯定就是我前进的动力。