在Java中,實現用戶注冊和登錄需要使用數據庫和Web框架。以下是常用的方法:
Step 1: 創建數據庫
CREATE TABLE `user` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(50) NOT NULL, `password` varchar(50) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Step 2: 創建Java Bean
public class User { private int id; private String username; private String password; // 省略getter和setter }
Step 3: 創建DAO
public class UserDao { public int addUser(User user) { int result = 0; try { Connection connection = DBUtil.getConnection(); String sql = "INSERT INTO user (username, password) VALUES (?, ?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, user.getUsername()); preparedStatement.setString(2, user.getPassword()); result = preparedStatement.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(); } return result; } public User getUser(String username, String password) { User user = null; try { Connection connection = DBUtil.getConnection(); String sql = "SELECT * FROM user WHERE username=? AND password=?"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setString(1, username); preparedStatement.setString(2, password); ResultSet resultSet = preparedStatement.executeQuery(); if (resultSet.next()) { user = new User(); user.setId(resultSet.getInt("id")); user.setUsername(resultSet.getString("username")); user.setPassword(resultSet.getString("password")); } } catch (SQLException e) { e.printStackTrace(); } finally { DBUtil.close(); } return user; } }
Step 4: 創建Servlet
public class RegisterServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); User user = new User(); user.setUsername(username); user.setPassword(password); UserDao userDao = new UserDao(); if (userDao.addUser(user) == 1) { response.sendRedirect("/login.jsp"); } else { request.setAttribute("message", "注冊失敗"); request.getRequestDispatcher("/register.jsp").forward(request, response); } } } public class LoginServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); UserDao userDao = new UserDao(); User user = userDao.getUser(username, password); if (user != null) { HttpSession session = request.getSession(); session.setAttribute("user", user); response.sendRedirect("/index.jsp"); } else { request.setAttribute("message", "用戶名或密碼錯誤"); request.getRequestDispatcher("/login.jsp").forward(request, response); } } }
上一篇left函數PHP