基于servlet,jsp以及MySQL实现登录及注册功能

基于servlet以及MySQL实现登录及注册功能

  • 第一步建表
    • 第二步创建数据库连接类JdbcUtils及bean类
      • 创建servlet类以及jsp页面

第一步建表

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" %>


    登录/注册
    


请登录

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" %>


    注册
    


请登录

你可能感兴趣的:(后端,mysql,数据库,java)