使用servlet+jsp+mysql实现一个简单的用户登录注册案例。
大家在学习javaweb时,与数据库互交是必不可少的,这里就用一个常见的登录注册案例来实现与mysql数据库的一个简单互交。
前端(JSP)页面提交表单数据(发送请求给Servlet)到Servlet,Servlet获取请求内容根据method参数执行注册或登录方法。用户注册就是把用户输入的数据放入数据库中存储,用户登录在把用户输入的数据与数据库中的数据对比,对比成功则登录。
所需要的jar包:
jsp-api.jar
servlet-aip.jar
c3p0-0.9.1.2.jar
commons-dbutils-1.6.jar
mysql-connector-java-8.0.19.jar
创建一个数据库s_user,在s_user里创建一个user表
结构:
CREATE DATABASE IF NOT EXISTS `s_user`;
USE `s_user`;
CREATE TABLE IF NOT EXISTS `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '用户名',
`password` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '密码',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
INSERT INTO `user` (`id`, `username`, `password`) VALUES
(1, 'user1', '123456'),
这里我们用c3p0连接数据库。
在src目录下新建c3p0-config.xml文件
在里面写入以下内容:
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/s_user?serverTimezone=Asia/Shanghai&useSSL=false
<property name="user">root</property>
<property name="password">你的数据库密码</property>
</default-config>
</c3p0-config>
新建tools文件夹,在里面创建一个MySQLTools工具类用来操作数据库。
代码如下:
/**
* 数据库工具类
*/
public class MySQLTools {
private static ComboPooledDataSource dataSource = null;
private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
//1.加载配置文件
// 2.创建DataSource
static {
dataSource = new ComboPooledDataSource();
}
public static DataSource getDataSource(){
return dataSource;
}
public static Connection getConnection(){
Connection conn = tl.get();
try {
if(conn == null){
conn = dataSource.getConnection();
}
} catch (SQLException e) {
e.printStackTrace();
}
tl.set(conn);
return conn;
}
/**
* 开始事务
* @throws SQLException
*/
public static void startTransaction(){
Connection conn = getConnection();
try {
conn.setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 回滚事务
* @throws SQLException
*/
public static void rollback(){
Connection conn = getConnection();
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 提交事务
* @throws SQLException
*/
public static void commit(){
Connection conn = getConnection();
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 关闭Connection,并移除线程中的连接
* @throws SQLException
*/
public static void closeConnection(){
close(getConnection());
tl.remove();
}
public static void close(Connection conn){
try {
if(conn != null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement stm){
try {
if(stm != null){
stm.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs){
try {
if(rs != null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
代码如下:
public class userBean {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setId(int id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "userBean{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
在service下创建userService类
代码如下:
public interface userService {
//注册
void register(userBean user) throws SQLException;
//登录
Boolean login(userBean user) throws SQLException;
}
然后在service文件夹下创建impl文件夹,在impl下面创建userServiceimpl 继承userService
代码如下:
public class userServiceImpl implements userService {
userDao userDao = new userDaoImpl();
//注册方法
@Override
public void register(userBean user) throws SQLException {
userDao.register(user);
}
//登录方法
@Override
public Boolean login(userBean user) throws SQLException {
userBean userBean = userDao.login(user);
System.out.println(userBean);
if (userBean == null){ //用户不存在
return false;
}
return true;
}
在dao下面创建userDao类
代码如下:
public interface userDao {
//注册
void register(userBean user) throws SQLException;
//登录
userBean login(userBean user) throws SQLException;
}
然后在dao文件夹下创建impl文件夹,在impl下面创建userDaoimpl 继承userDao
代码如下:
public class userDaoImpl implements userDao {
QueryRunner queryRunner = new QueryRunner(MySQLTools.getDataSource());
//数据库操作把用户名密码插入到mysql中
@Override
public void register(userBean user) throws SQLException {
queryRunner.update("INSERT INTO user VALUES(?,?,?)",null,user.getUsername(),user.getPassword());
}
//用户名密码对比
@Override
public userBean login(userBean user) throws SQLException {
return queryRunner.query("SELECT * FROM user WHERE username = ? AND password = ?",new BeanHandler<userBean>(userBean.class),user.getUsername(),user.getPassword());
}
在servlet下面创建一个userServlet类继承HttpServlet,添加@WebServlet注解, 在类中写入doPost和doGet方法
代码如下:
@WebServlet(name = "user",urlPatterns = "/user")
public class userServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doPost(request,response);
}
}
在开发中我们一个Servlet往往会需要处理多个请求,用if一层一层循环效率太低,于是我们可以优化一下,使用java反射来出来多个请求问题.此代码可继续优化,我这里不做过多描述。
doPost中写入:
代码如下:
//指定一个方法名,找到这个方法并直接调用
//获取调用的方法名称
String method = request.getParameter("method");
System.out.println(method);
try {
// getDeclaredMethod(方法名,参数列表(传的是各个参数的类))
// 通过反射找到该方法并调用
Method declaredMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
System.out.println(declaredMethod);
// 把方法权限设大
declaredMethod.setAccessible(true);
// invoke(对象,参数) 执行该方法
declaredMethod.invoke(this,request,response);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
登录方法:
代码如下:
//登录
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
userBean userBean = new userBean();
//获取表单数据
String username = request.getParameter("username");
String password = request.getParameter("password");
userBean.setUsername(username);
userBean.setPassword(password);
//验证
if(!userService.login(userBean)){ //登录失败
//转发
request.getRequestDispatcher("err.jsp").forward(request, response);
}
request.getRequestDispatcher("loginsuccess.jsp").forward(request, response);
}
注册方法:
代码如下:
//注册
private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
userBean userBean = new userBean();
//获取表单数据
String username = request.getParameter("username");
String password = request.getParameter("password");
String password1 = request.getParameter("password1");
//判断密码是否相等
if(!password1.equals(password)){
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("两次输入密码不一致");
}else { //注册成功
userBean.setUsername(username);
userBean.setPassword(password);
userService.register(userBean);
request.getRequestDispatcher("regsuccess.jsp").forward(request, response);
}
}
完整代码:
代码如下:
@WebServlet(name = "user",urlPatterns = "/user")
public class userServlet extends HttpServlet {
userService userService = new userServiceImpl();
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
//反射:你指定一个方法名,我找到这个方法并直接调用)
//获取调用的方法名称
String method = request.getParameter("method");
System.out.println(method);
try {
// getDeclaredMethod(方法名,参数列表(传的是各个参数的类))
// 通过反射找到该方法并调用
Method declaredMethod = this.getClass().getDeclaredMethod(method, HttpServletRequest.class, HttpServletResponse.class);
System.out.println(declaredMethod);
// 把方法权限设大
declaredMethod.setAccessible(true);
// invoke(对象,参数) 执行该方法
declaredMethod.invoke(this,request,response);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doPost(request,response);
}
//注册
private void register(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
userBean userBean = new userBean();
//获取表单数据
String username = request.getParameter("username");
String password = request.getParameter("password");
String password1 = request.getParameter("password1");
//判断密码是否相等
if(!password1.equals(password)){
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("两次输入密码不一致");
}else { //注册成功
userBean.setUsername(username);
userBean.setPassword(password);
userService.register(userBean);
request.getRequestDispatcher("regsuccess.jsp").forward(request, response);
}
}
//登录
private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, SQLException, ServletException {
userBean userBean = new userBean();
//获取表单数据
String username = request.getParameter("username");
String password = request.getParameter("password");
userBean.setUsername(username);
userBean.setPassword(password);
//验证
if(!userService.login(userBean)){ //登录失败
//转发
request.getRequestDispatcher("err.jsp").forward(request, response);
}
request.getRequestDispatcher("loginsuccess.jsp").forward(request, response);
}
到这里我们的后台代码就完了,接下来就是我们前台的页面了,由于用来测试,就写了简陋一点。
register.jsp:
代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>注册</title>
</head>
<body>
<div class="container" style="margin: auto">
<form action="/user?method=register" method="post">
<div class="tit">注册</div>
<input type="text" name="username" placeholder="账号"><br><br>
<input type="password" name="password" placeholder="密码"><br><br>
<input type="password" name="password1" placeholder="确认密码"><br>
<input type="submit" value="注册">
</form>
<span>已有账号?<a href="login.jsp">去登录</a></span>
</div>
</body>
</html>
login.jsp:
代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>登录</title>
</head>
<body>
<div class="container" style="height: 600px;width: 600px;margin: auto 0">
<form action="/user?method=login" method="post">
<div class="tit">登录</div><br>
<input type="text" name="username" placeholder="账号"><br><br>
<input type="password" name="password" placeholder="密码"><br>
<input type="submit" value="登录">
</form>
<span>没有账号?<a href="register.jsp">去注册</a></span>
</div>
</body>
</html>
其他页面都是差不多的,比如注册成功页面,大家随意发挥。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span>注册成功!<a href="login.jsp">返回登录</a></span>
</body>
</html>
以上就是今天要讲的内容,本文仅仅简单介绍了servlet+jsp和mysql的一个简易的登录注册案例,大家可以根据这个思路去创作更好看更优秀的项目,每个人都在不断的成长,成长的路上难免有一些跌跌撞撞,我们也正是在这样的环境下才能磨练自己。今天的内容结束啦,感谢大家。另外有问题可以问我哦!需要源代码的小伙伴关注公众号 “俊俊同学的笔记”,免费发给大家哦!