首页 > 编程语言 > JavaWeb实现用户登录与注册功能(服务器)
2022
05-20

JavaWeb实现用户登录与注册功能(服务器)

本文实例为大家分享了JavaWeb实现用户登录与注册功能的具体代码,供大家参考,具体内容如下

用到的知识

客户端:HTML CSS JS (JQuery)

服务器:JAVA基础  JSP   Servlet  JDBC  Tomcat

数据库:MySQL

用到的Jar包 druid数据库连接池  dbutils JDBC数据库操作工具  MySQL jar包

 

总体结构:

客户端数据库部分网址

思路:

服务器部分采用JavaEE三层架构

(1)、表现层:通俗讲就是展现给用户的界面,即用户在使用一个系统的时候他的所见所得。
(2)、业务逻辑层:针对具体问题的操作,也可以说是对数据层的操作,对数据业务逻辑处理。
(3)、数据访问层:该层所做事务直接操作数据库,针对数据的增添、删除、修改、查找等。

先创建基本的文件夹架构,三层的文件夹依次为web ,servlet ,DAO。 此外还有其他相关文件夹工具类utils,JAVABean类pojo,测试类test 。依次实现从DAO层到Servce层再到Web层。

文件夹架构

资源文件 jdbc.properties

username=root
password=123456
url=jdbc:mysql://localhost:3306/book
driverClassName=com.mysql.jdbc.Driver
initialSize=5
maxActive=10

一、DAO层

0.写好JAVABean User类

package com.book.pojo;
 
public class User {
    private Integer id;
    private String username;
    private String password;
    private String email;
 
    public User() {
    }
 
    public User(Integer id, String username, String password, String email) {
        this.id = id;
        this.username = username;
        this.password = password;
        this.email = email;
    }
 
    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;
    }
 
    public String getEmail() {
        return email;
    }
 
    public void setEmail(String email) {
        this.email = email;
    }
 
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                '}';
    }
 
}

1.先实现数据连接

JDBCUtils

package com.book.utils;
 
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
 
 
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
 
public class JDBCUtils {
 
    private static DruidDataSource druidDataSource;
 
    //数据库连接池初始化
    static {
        try {
 
            InputStream resourceAsStream = JDBCUtils.class.getClassLoader().getResourceAsStream("jdbc.properties");//类加载器默认是从classPath路径加载资源
            Properties properties = new Properties();
            properties.load(resourceAsStream);
            //创建数据库连接池
            druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            System.out.println("数据库连接池初始化异常");
        }
    }
 
    //获取数据库连接池中的连接
    public static Connection getConnection() {
 
        Connection connection= null;
        try {
            connection = druidDataSource.getConnection();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return connection;
 
    }
 
    public static void close(Connection connection) {
        try {
            connection.close();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        JDBCUtils jdbcUtils=new JDBCUtils();
        System.out.println(jdbcUtils.getConnection());
    }
}

2.测试连接是否成功

3.编写BaseDAO 实现对数据库的基本通用操作

package com.book.DAO;
import com.book.utils.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public abstract class BaseDAO {
    private QueryRunner queryRunner=new QueryRunner();
    //数据库通用操作,使用dbutils来操作
    //用来执行updata,delete,insert
    public int updata(String sql,Object...objects){
        Connection connection= JDBCUtils.getConnection();
        try {
            return queryRunner.update(connection,sql,objects);//返回影响的行数
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return -1;
    }
    //用来执行查询操作
    public <T>T queryForOne(Class<T>clazz,String sql,Object...objects){
        Connection connection=JDBCUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new BeanHandler<T>(clazz),objects);
        } catch (Exception throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
    //查询多个结果
    public <T>List<T> queryForList(Class<T>clazz,String sql,Object...objects){
        Connection connection=JDBCUtils.getConnection();
        List<T>list=new ArrayList<>();
        try {
            list=queryRunner.query(connection,sql,new BeanListHandler<T>(clazz),objects);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }
    //查询单个数
    public Object queryForSingleValue(String sql,Object...objects){
        Connection connection= JDBCUtils.getConnection();
        try {
            return queryRunner.query(connection,sql,new ScalarHandler(),objects);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }
}

4.编写UserDAO接口确定需要的操作

package com.book.DAO;
 
import com.book.pojo.User;
public interface UserDAO {
    // 注册时判断是否该用户名已经被注册  根据用户名查询用户信息 如果返回null说明没有该用户
    public User queryUserByUsername(String username);
 
    //注册成功   保存用户信息
    public int saveUser(User user);
 
    //登录操作 根据用户名和密码查询用户 查不到返回null
    public User queryUserByUsernameAndPassword(String username,String password);
}

5.UserDAOImpl实现UserDAO接口

package com.book.DAO;
import com.book.pojo.User;
//所犯错误:继承的子类会有父类的全部方法,不要在子类中声明父类对象,调用父类方法
public class UserDAOimpl extends BaseDAO implements UserDAO{
 
    @Override
    public User queryUserByUsername(String username) {
        String sql="select * from users where username=?";
        User user =queryForOne(User.class,sql,username);
        return user;
    }
    //所犯错误:输入的邮箱不能重复
    @Override
    public int saveUser(User user) {
        String sql="INSERT INTO `users`(`username`,`password`,`email`) VALUES(?,?,?)";
        int n;
        n = updata(sql,user.getUsername(),user.getPassword(),user.getEmail());
        return n;
    }
    @Override
    public User queryUserByUsernameAndPassword(String username, String password) {
        String sql="select * from users where username=? and password=?";
        User user=queryForOne(User.class,sql,username,password);
        return user;
    }
}

二、Servlet层

1.UserServce接口确定业务需要的方法,用来与Web层进行交互

package com.book.servlet;
import com.book.pojo.User;
//业务层一个业务一个方法
public interface UserServce {
    //注册业务 注册成功将用户保存到数据库中
    public void registUser(User user);
    //登录业务
    public User login(User user);
    //检查用户名是否可用 返回true表示用户名已存在
    public boolean existUsername(String username);
}

2.UserServceImpl类实现UserServce接口

package com.book.servlet;
import com.book.DAO.UserDAO;
import com.book.DAO.UserDAOimpl;
import com.book.pojo.User;
 
public class UserServceImpl implements UserServce {
 
    private UserDAO userDAO=new UserDAOimpl();
    @Override
    public void registUser(User user) {
        userDAO.saveUser(user);
    }
 
    @Override
    public User login(User user) {
       return userDAO.queryUserByUsernameAndPassword(user.getUsername(),user.getPassword());
    }
 
    @Override
    public boolean existUsername(String username) {
        //用户名不存在
         if(userDAO.queryUserByUsername(username)==null){
             return false;
         }else {
             return true;
         }
    }
}

三、Web层

1.注册操作

package com.book.web;
import com.book.pojo.User;
import com.book.servlet.UserServce;
import com.book.servlet.UserServceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
public class RegistServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        UserServce userServce=new UserServceImpl();
       //获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        String code=req.getParameter("code");
        //判断验证码是否正确 忽略大小写
        if("6n6np".equalsIgnoreCase(code)){
            //判断是否存在用户名
            if(!userServce.existUsername(username)){
                //不存在则将注册信息写入数据库
                User user=new User(null,username,password,email);
                userServce.registUser(user);
                //请求转发到注册成功页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }else{
                System.out.println("用户名已存在");
                //跳转到注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
            }
        }else {
            System.out.println("验证码错误");
            //跳转到注册页面
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }
    }
}

2.登录操作

package com.book.web;
 
import com.book.pojo.User;
import com.book.servlet.UserServce;
import com.book.servlet.UserServceImpl;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
public class LoginServlet extends HttpServlet {
    private UserServce userServce=new UserServceImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        User user=new User(null,username,password,null);
        //判断用户的账号密码是否正确
        if(userServce.login(user)!=null){
            //登录成功跳转到登录成功页面
            System.out.println("登录成功");
            req.getRequestDispatcher("/pages/user/login_success.jsp").forward(req,resp);
        }else{
            //账号或密码不正确
            System.out.println("账号或密码不正确");
            req.getRequestDispatcher("/pages/user/login.jsp").forward(req,resp);
        }
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持自学编程网。

编程技巧