public class RegisterServlet extends HttpServlet { private UsersService usersService = new UsersService(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 解決request的中文亂碼 request.setCharacterEncoding("UTF-8"); // 獲取用戶輸入的驗證碼 String checkcode = request.getParameter("checkCode"); // 獲取Session中的驗證碼 String code = (String) request.getSession().getAttribute("checkcode_session"); // 進行比較判斷 if (!checkcode.equals(code)) { //System.out.println("驗證碼錯誤!"); request.setAttribute("info", "驗證碼錯誤!"); request.getRequestDispatcher("/register.jsp").forward(request, response); return; } // 獲取全部請求參數的MAP集合 Map<String, String[]> map = request.getParameterMap(); // 建立users對象 Users users = new Users(); // 用BeanUtils中的方法將map集合中的參數封裝到Users對象中 // 原理:根據map中的key 跟user對象中的屬性名一一映射 try { BeanUtils.populate(users, map); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } // 封裝uid(隨機產生36位不重複的id) users.setUid(UUID.randomUUID().toString()); // 調Service方法 System.out.println(users); usersService.register(users); // 成功後,重定向到登陸頁面 response.sendRedirect(request.getContextPath() + "/login.jsp"); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
private UsersDao usersDao=new UsersDao(); //註冊 public void register(Users users){ try { usersDao.register(users); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
// 註冊 public void register(Users users) throws SQLException { /* * Connection conn = JDBCUtils.getConn(); String sql = * "insert into users(uid,username,password,email,name,sex,birthday) values(?,?,?,?,?,?,?)" * ; PreparedStatement pst=conn.prepareStatement(sql); pst.setString(1, * users.getUid()); pst.setString(2, users.getUsername()); * pst.setString(3, users.getPassword()); pst.setString(4, * users.getEmail()); pst.setString(5, users.getName()); * pst.setString(6, users.getSex()); pst.setString(7, * users.getBirthday()); //執行sql pst.executeUpdate(); //釋放資源 * JDBCUtils.close(conn, pst); */ QueryRunner qr = new QueryRunner(MyDBUtils.getDataSource()); String sql = "insert into users(uid,username,password,email,name,sex,birthday) values(?,?,?,?,?,?,?)"; qr.update(sql, new Object[] { users.getUid(), users.getUsername(), users.getPassword(), users.getEmail(), users.getName(), users.getSex(), users.getBirthday() }); }