Simple login case

Keywords: Java Database Druid JDBC

preparation:
Import the required jar package, import it into the lib package under the web directory and WEB-INF directory, and add it into the module
The following picture:

Configuration database file druid.properties

driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///Day14 you can create your own database for the database name
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/anliLogin/loginServlet" method="post">
        User name:<input type="text" name="username"> <br>
        Password:<input type="password" name="password"><br>

        <input type="submit" value="Sign in">

    </form>
</body>
</html>

Note that the path written in the action in from should be / virtual path / Servlet path of login
1. Create User class

public class User {
    private int id;
    private String username;
    private String password;


    public int getId() {
        return id;
    }

    public void setId(int 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 + '\'' +
                '}';
    }
}

2. Create JDBC tool class and use Druid connection pool

public class JDBCUtils {
    private static DataSource ds;

    static {
        try {
            /**
             * 1.Load profile
             */
            Properties pro=new Properties();
            //Use ClassLoader to load configuration file and get byte input stream
            InputStream is=JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            pro.load(is);
            //2. Initialize connection pool object
            ds=DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //Get connection pool object
    public static DataSource getDataSource(){
        return ds;
    }

    //Get Connection connection
    public static Connection getConnection() throws SQLException {
        return ds.getConnection();
    }
}

3. Create the UserDao class and operate the User class in the database

public class UserDao {
    private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
    /**
     * Login method
     * @param loginUser
     * @return
     */
    public User login(User loginUser){
        try {
            String sql="select * from user where username=? and password=?";
            User user = template.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), loginUser.getUsername(), loginUser.getPassword());
            return user;
        }catch (Exception e){  //If the account password cannot be found, an exception will be thrown
            e.printStackTrace();  //Log
            return null;
        }
    }
}

4.Servlet:

1. LoginServlet.java
2. If the user name and password are correct, go to successServlet.java. Otherwise, FailServlet.java

LoginServlet section:

@WebServlet("/loginServlet")
public class loginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. Set code
        req.setCharacterEncoding("utf-8");
        //2. Get request parameters
        /*String username=req.getParameter("username");
        String password=req.getParameter("password");
        //3.Encapsulating user objects
        User loginUser = new User();
        loginUser.setUsername(username);
        loginUser.setPassword(password);*/

        Map<String,String[]> map=req.getParameterMap();
        User loginUser=new User();

        try {
            BeanUtils.populate(loginUser,map);    //Can encapsulate multiple data
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //4. Call the login method of UserDao
        UserDao dao = new UserDao();
        User user=dao.login(loginUser);

        //5. judge user
        if(user==null){
            req.getRequestDispatcher("/failServlet").forward(req,resp);
        }else {
            req.setAttribute("user",user);
            req.getRequestDispatcher("/successServlet").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req,resp);
    }
}

SuccessServlet.java

@WebServlet("/successServlet")
public class SuccessServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Get the user object shared in the request domain
        User user = (User) req.getAttribute("user");
        if (user != null) {
            //Set encoding
            resp.setContentType("text/html;charset=utf-8");
            //output
            resp.getWriter().write("Login successfully!" + user.getUsername() + ",Welcome");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}

FailServlet.java

@WebServlet("/failServlet")
public class FailServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //Set encoding
        resp.setContentType("text/html;charset=utf-8");
        //output
        resp.getWriter().write("Login failed, wrong user name or password!");

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
Published 23 original articles, won praise 16, visited 9721
Private letter follow

Posted by Lukey on Sun, 09 Feb 2020 07:52:08 -0800