1. Requirements
The user visits the login page, enters the user name and password, and clicks to log in. If the login is successful, it will jump to the main page. If the login fails, it will jump to the login page and an error message will be displayed on the page.
If the user chooses to remember the username and password on the login page, after successful login, they do not need to enter the username and password when logging in again in the future. Click the login button to directly access the main page.
2. Technical requirements
Done with Servlet + Cookie + Jdbc + MySQL!
3. Database design
Create a new database with the database name XXX and create the XXX table.
Table name: T_USER | ||
---|---|---|
Field name | Type | Constraint |
id | int | Primary key |
username | varchar(100) | |
password | varchar(20) |
4. Environment setup
4.1 Create Java Enterprise project
4.2 Import related jar packages
Create lib under the WEB-INF package and add it (there are Druid jar packages and jar packages for operating databases)
4.3 Create package structure
4.4 Writing pojo entity classes
public class User { private Integer id; private String username; private String password; public User() { } public User(Integer id, String username, String password) { this.id = id; this.username = username; this.password = password; } 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; } @Override public String toString() { return "User{" + "id=" + id + ", username='" + username + ''' + ", password='" + password + ''' + '}'; } }
4.5 Writing database tool classes
public class Fengconnectionpool { public static DruidDataSource dataSource=null; static{ //1. Get the data source dataSource = new DruidDataSource(); //1.2 Basic 4 items // 1) Driver dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); // 2) Connect dataSource.setUrl("jdbc:mysql://localhost:3306/javaweblogin?useSSL=false & amp;characterEncoding=utf-8 & amp;serverTimezone=Asia/Shanghai"); // 3) User dataSource.setUsername("root"); // 4) Password dataSource.setPassword("123456"); //1.3 Special items [optional] // 1) Initialize size dataSource.setInitialSize(5); // 2) Maximum number of activities dataSource.setMaxActive(10); // 3) Minimum idle number dataSource.setMinIdle(2); } //Encapsulate the obtained connection into a method, write it statically and call it directly with the class name public static Connection getConnection() { try { //2. Get connection DruidPooledConnection conn = dataSource.getConnection(); return conn; } catch (SQLException e) { e.printStackTrace(); return null; } } //Encapsulate the release of resources into the method public static void close(PreparedStatement ps,Connection connection){ if (ps !=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if (connection !=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
4.6 Writing dao layer interfaces and implementation classes
public interface UserDao { User getUserBy(String username,String password); }
public class UserDaoImpl implements UserDao{ @Override public User getUserBy(String username, String password) { Connection connection=null; PreparedStatement ps=null; User user=null; try { connection = Fengconnectionpool.getConnection(); String sql="select * from login1 where username=? and password=?"; ps = connection.prepareStatement(sql); ps.setString(1,username); ps.setString(2,password); ResultSet resultSet = ps.executeQuery(); while (resultSet.next()) { int id = resultSet.getInt("id"); String username1 = resultSet.getString("username"); String password1 = resultSet.getString("password"); user = new User(id, username1, password1); } } catch (SQLException e) { e.printStackTrace(); } finally { Fengconnectionpool.close(ps,connection); } return user; } }
4.7 Write service layer interface and implementation class
public interface UserService { User login(String username,String password); }
public class UserServiceImpl implements UserService { private UserDao userDao=new UserDaoImpl(); @Override public User login(String username, String password) { return userDao.getUserBy(username,password); } }
5. Login page implementation (remember password)
@WebServlet("/loginPage") public class LoginPageServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter(); if(req.getAttribute("msg") != null){ writer.write("<font color='red'>" + req.getAttribute("msg") + "</font>"); } writer.write("<form action='log' method='post'>"); // After the last successful login, log in to the password-free page again String username = ""; String password = ""; String isRemember = ""; //Get the cookies stored in the browser Cookie[] cookies = req.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { if(cookie.getName().equals("username")){ username = cookie.getValue(); } if(cookie.getName().equals("password")){ password = cookie.getValue(); } } } if(!username.equals("") & amp; & amp; !password.equals("")){ isRemember = "1"; } writer.write("Account: <input type='text' name='username' value='" + username + "'><br>"); writer.write("Password: <input type='password' name='password' value='" + password + "'><br>"); if(isRemember.equals("1")){ writer.write("Remember password: <input type='checkbox' checked='checked' name='isRemember' value='1'><br>"); }else{ writer.write("Remember password: <input type='checkbox' name='isRemember' value='1'><br>"); } writer.write("<input type='submit' value='Login'><br>"); writer.write("</form>"); writer.write("</body>"); writer.write("</html>"); } }
6. Main page function implementation
@WebServlet("/main") public class MainServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setContentType("text/html;charset=utf-8"); PrintWriter writer = resp.getWriter(); writer.write("<html>"); writer.write("<head>"); writer.write("<meta charset='utf-8'>"); writer.write("<title>Welcome to the system</title>"); writer.write("</head>"); writer.write("<body>"); writer.write("<h1>Login successful!!<br>Welcome to the Big Brother login system</h1><br>"); writer.write("</body>"); writer.write("</html>"); } }
7. Login function implementation
@WebServlet("/log") public class LoginServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //Get the value submitted by the request page and get the value based on the name attribute String username = req.getParameter("username"); String password = req.getParameter("password"); String isRemember = req.getParameter("isRemember"); try { UserService userService = new UserServiceImpl(); User user = userService.login(username, password); if(user != null){ //After successful login, if remember password is checked, then we will create a cookie if("1".equals(isRemember)){ Cookie cookie = new Cookie("username", username); Cookie cookie2 = new Cookie("password", password); cookie.setMaxAge(60*60*24*7); cookie2.setMaxAge(60*60*24*7); resp.addCookie(cookie); resp.addCookie(cookie2); }else{ //When the next request comes, if it is not checked, get the cookie that exists in the request object and let the cookie die immediately. Cookie[] cookies = req.getCookies(); if(cookies != null){ for (Cookie cookie : cookies) { if(cookie.getName().equals("username") || cookie.getName().equals("password")){ cookie.setMaxAge(0); resp.addCookie(cookie); } } } } //Page redirected after successful login resp.sendRedirect(req.getContextPath() + "/main"); }else{ //The login failure request is forwarded back to the login page (with the data of the login failure setting) req.setAttribute("msg", "Wrong username or password!"); req.getRequestDispatcher("/loginPage").forward(req, resp); } } catch (Exception e) { e.printStackTrace(); } } }