当前位置:网站首页>Login and registration based on servlet, JSP and MySQL

Login and registration based on servlet, JSP and MySQL

2022-06-11 06:02:00 Not bald

Step 1 create table

1. Create a form to store user registration information , It is convenient to obtain later

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;

 Insert picture description here

Step 2: create a database connection class JdbcUtils And bean class

1.JdbcUtils class

public class JdbcUtils {
// Program started , Priority operation 
    static {
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static Connection conn;
// Set to static Can be called directly 
    public static Connection getConnect() {
        try {
            if (conn == null || conn.isClosed()) {
            // The last one is your own database name 
                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 class
Used to pass through bean To store or obtain relevant information from the database

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. establish Dao Class is used to write methods for login or registration , For the convenience of subsequent use , Reduce code duplication

public class UserDao {
    private Connection conn;
    private Statement st;
    private PreparedStatement pst;
    private ResultSet rs;

    // Check whether the account number and password are correct 
    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;
    }

    // The account , The password and mailbox are put into the database 
    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);
        }
    }
}

establish servlet Class and jsp page

1. Logon servlet as well as jsp page
Note the annotation configuration servlet And in web.xml There must be no conflict in the configuration , The following code contains the authentication for the administrator login

@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);

        // utilize session Store exception information 
        HttpSession session = req.getSession();
        // utilize session Check if you are logged in 
        HttpSession check = req.getSession();
        // Remove errors caused by whitespace 
        if (username == null || "".equals(username.trim())) {
            session.setAttribute("error", " User name input error ");
            // Can use request forwarding and redirection , Use redirection first , Prevent malicious occupation of resources 
            resp.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }
        if (password == null || "".equals(password.trim())) {
            session.setAttribute("error", " Wrong password ");
            // Can use request forwarding and redirection , Use redirection first , Prevent malicious occupation of resources 
            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", " Wrong user name or password ");
            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);
        }
    }
}

Logon jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title> Sign in / register </title>
    <style>
        * {
            border: 0;
            margin: 0;
        }

        .top-toolbar {
            width: 100%;
            height: 90px;
            text-align: center;
            background-color: black;
            color: aliceblue;
        }

        .login {
            background-color: darkgrey;
            width: 100%;
            height: 100%;
        }

        .rigister {
            width: 60px;
            height: 30px;
            background-color: rgb(239, 239, 239);
            border-radius: 10%;
        }

        #rig {
            text-decoration: none;
            line-height: 28px;
            font-weight: normal;
        }
    </style>
</head>
<body>
<div class="top-toolbar">
    <h1> Please log in </h1>
</div>
<div class="login">
    <form action="${pageContext.request.contextPath}/LoginServlet" method="post">
        <center>
            ${error}<br>
            <table>
                <tr>
                    <th>
                         user name :
                    </th>
                    <th>
                        <input type="text" name="username" style="width: 200px">
                    </th>
                </tr>
                <tr>
                    <th> password :</th>
                    <th>
                        <input type="password" name="password" style="width: 200px">
                    </th>
                </tr>
                <tr>
                    <th>
                        <input type="submit" value=" Sign in " style="width: 60px;height: 30px;border-radius: 10%">
                    </th>
                    <th>
                        <div class="rigister">
                            <a href="${pageContext.request.contextPath}/register.jsp"> register </a>
                        </div>
                    </th>
                    <th>
                        <div class="exist">
                            <a href="${pageContext.request.contextPath}/index.jsp"> sign out </a>
                        </div>
                    </th>
                </tr>
            </table>
        </center>
    </form>
</div>
</body>
</html>

2. Registered servlet as well as jsp page


@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);
            // How to write to the database 
            UserDao userDao = new UserDao();
            userDao.insertIt(user);

            resp.sendRedirect(req.getContextPath() + "/login.jsp");

        } else {
            message = " Password inconsistency !";
            req.setAttribute("Message", message);
            req.getRequestDispatcher("/Message.jsp").forward(req, resp);
        }
    }
}

Registered jsp page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title> register </title>
    <style>
        * {
            border: 0;
            margin: 0;
        }

        .top-toolbar {
            width: 100%;
            height: 90px;
            text-align: center;
            background-color: black;
            color: aliceblue;
        }

        .login {
            background-color: darkgrey;
            width: 100%;
            height: 100%;
        }

        .rigister {
            width: 60px;
            height: 30px;
            background-color: rgb(239, 239, 239);
            border-radius: 10%;
        }

        #rig {
            text-decoration: none;
            line-height: 28px;
            font-weight: normal;
        }
    </style>
</head>
<body>
<div class="top-toolbar">
    <h1> Please log in </h1>
</div>
<div class="login">
    <center>
        <form action="${pageContext.request.contextPath}/RegisterServlet" method="post">
            <table>
                <tr>
                    <th>
                         user name :
                    </th>
                    <th>
                        <input type="text" name="username" style="width: 200px">
                    </th>
                </tr>
                <tr>
                    <th> password :</th>
                    <th>
                        <input type="password" name="password" style="width: 200px">
                    </th>
                </tr>
                <tr>
                    <th> Enter the password again :</th>
                    <th>
                        <input type="password" name="s_password" style="width: 200px">
                    </th>
                </tr>
                <tr>
                    <th>
                         mailbox :
                    </th>
                    <th>
                        <input type="text" name="email" style="width: 200px">
                    </th>
                </tr>
                <tr>
                    <th>
                        <input type="submit" value=" register " style="width: 60px;height: 30px;border-radius: 10%">
                    </th>
                </tr>
            </table>
        </form>
    </center>
</div>
</body>
</html>
原网站

版权声明
本文为[Not bald]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/03/202203020530435616.html