本章简单实现了一下利用数据库实现用户的登录和注册
IntelliJ IDEA使用Maven搭建项目
https://blog.csdn.net/weixin_43895377/article/details/89440301
配一下pom.xml依赖
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!-- Mysql -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
数据库配置文件配置参数
为了不要硬编码,习惯性的用了下外部引入
因为是远程服务器配的远程数据库,就打了个码,不然有些调皮的就要乱连了
自定义一个JDBCUtils工具类
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
public class JDBCUtils {
private static Properties prop = null;
private static Connection conn = null;
static {
try {
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");
prop = new Properties();
prop.load(is);
Class.forName(prop.getProperty("driver"));
conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("username"),
prop.getProperty("password"));
}catch (Exception e){
e.printStackTrace();
}
}
public static Connection getConn() {
return conn;
}
}
navicat创建好后导出的标准sql语句
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
创建实体类
public class User {
private Integer id;
private String username;
private String password;
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
创建Dao接口,这一步最为繁琐冗余,但是为了理解一下痛处,还是悲愤的一个个敲了出来
import com.day.pojo.User;
import com.day.utils.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 conn = JDBCUtils.getConn();
private PreparedStatement ps;
/**
* 添加用户
* @param user
* @return
* @throws SQLException
*/
public int add(User user) throws SQLException {
String sql = "insert into student(username,password) values(?,?)";
ps = conn.prepareStatement(sql);
ps.setObject(1, user.getUsername());
ps.setObject(2, user.getPassword());
return ps.executeUpdate();
}
/**
* 删除
* @param id
* @return
* @throws SQLException
*/
public int delete(int id) throws SQLException {
String sql = "delete from user where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, id);
return ps.executeUpdate();
}
/**
* 修改
* @param user
* @return
* @throws SQLException
*/
public int update(User user) throws SQLException {
String sql = "update user set username=? , password=? where id=?";
ps = conn.prepareStatement(sql);
ps.setObject(1, user.getUsername());
ps.setObject(2,user.getPassword());
ps.setObject(3,user.getId());
return ps.executeUpdate();
}
/**
* 查询所有
* @return
*/
public List<User> findAll() throws SQLException {
String sql = "select * from student";
ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
List<User> users = new ArrayList<User>();
while (rs.next()){
int id = rs.getInt("id");
String username = rs.getString("username");
String password = rs.getString("password");
User u = new User(id,username,password);
users.add(u);
}
return users;
}
/**
* 根据Id查询
* @param id
* @return
* @throws SQLException
*/
public User findById(int id) throws SQLException {
String sql = "select * from user where id=?";
ps = conn.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 student where username=? and password=?";
ps = conn.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类,这里练习的较为简单,service接口和事务等没有添加,不然也是一个头疼的地方
import com.day.dao.UserDao;
import com.day.pojo.User;
import java.sql.SQLException;
import java.util.List;
public class UserService {
private UserDao userDao = new UserDao();
/**
* 添加用户
* @param user
* @return
* @throws SQLException
*/
public int add(User user) throws SQLException {
return userDao.add(user);
}
/**
* 删除
* @param id
* @return
* @throws SQLException
*/
public int delete(int id) throws SQLException {
return userDao.delete(id);
}
/**
* 修改
* @param user
* @return
* @throws SQLException
*/
public int update(User user) throws SQLException {
return userDao.update(user);
}
/**
* 查询所有
* @return
*/
public List<User> findAll() throws SQLException {
return userDao.findAll();
}
/**
* 根据Id查询
* @param id
* @return
* @throws SQLException
*/
public User findById(int id) throws SQLException {
return userDao.findById(id);
}
public User login(User user) throws SQLException {
return userDao.login(user);
}
}
登录和注册功能控制类,使用了@WebServlet,一个方法一个类,巨难受,代码修改、冗余,等功能多了写一个项目就要把头发掉光
import com.day.pojo.User;
import com.day.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 javax.servlet.http.HttpSession;
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);
} catch (SQLException e) {
e.printStackTrace();
}
//跳转
if(u==null){
req.setAttribute("mess","账号或密码错误");
req.getRequestDispatcher("login.jsp").forward(req,resp);
}else{
HttpSession session = req.getSession();
session.setAttribute("user",u.getUsername());
resp.sendRedirect("main.jsp");
}
}
}
import com.day.pojo.User;
import com.day.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("/reg")
public class RegUserServlet 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();
int i = 0;
try {
i = us.add(user);
} catch (SQLException e) {
e.printStackTrace();
}
//跳转
if(i>0){
req.setAttribute("mess","注册成功");
req.getRequestDispatcher("reg.jsp").forward(req,resp);
}else{
req.setAttribute("mess","注册失败");
req.getRequestDispatcher("reg.jsp").forward(req,resp);
}
}
}
登录注册界面来测试了
<%--
Created by IntelliJ IDEA.
User: 77923
Date: 2019/4/21
Time: 19:15
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>
<hr>
<form action="/login" method="post">
<p>
用户名:<input type="text" name="username">
</p>
<p>
密码:<input type="password" name="password">
</p>
<p>
<input type="submit" value="登录">
</p>
</form>
${mess}
</body>
</html>
<%--
Created by IntelliJ IDEA.
User: 77923
Date: 2019/4/21
Time: 19:15
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>
<hr>
<form action="/reg" method="post">
<p>
用户名:<input type="text" name="username">
</p>
<p>
密码:<input type="password" name="password">
</p>
<p>
<input type="submit" value="注册">
</p>
</form>
${mess}
</body>
</html>
小小的总结一下,这样写下去巨难受,语言总结没有说服力,有兴趣的小伙伴可以亲手把代码打出来体验一下,不懂得地方可以查询api,友情奉献
链接:https://pan.baidu.com/s/1Aj3hfS3IMXBFM9ipkJRqWg
提取码:ge9s