package Servlet; import java.sql.Connection; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.swing.*; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; @WebServlet(name = "LoginServlet") public class RegisterServlet extends HttpServlet { public RegisterServlet() { super(); } @Override public void destroy() { super.destroy(); } public void ww() { String msg = "注册成功!"; int type = JOptionPane.YES_NO_OPTION; JOptionPane.showMessageDialog(null, msg, title, type); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { JDBC jdbc = new JDBC(); Connection con = null; PreparedStatement ps = null; String username=new String(request.getParameter("username").getBytes("ISO-8859-1"),"UTF-8"); String PASSWORD=new String(request.getParameter("userpassword").getBytes("ISO-8859-1"),"UTF-8"); String email=new String(request.getParameter("Email").getBytes("ISO-8859-1"),"UTF-8"); try { con = jdbc.getConnection(); String sql = "insert into Usersd(username,PASSWORD,email) values (?,?,?)"; ps = con.prepareStatement(sql); ps.setString(1, username); ps.setString(2,password); ps.setString(3, email); int row = ps.executeUpdate(); wrong1(); } catch (SQLException e) { e.printStackTrace(); }finally { jdbc.closeAll(con,ps,null); } } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } }
package cn; import java.sql.*; public class JDBC { //获取连接 public Connection getConnection() { Connection conn = null; try { Class.forName("com.mysql.jdbc.Driver"); // 建立连接 conn = DriverManager.getConnection( "jdbc:mysql://localhost:3306/mysql", "root", "root"); } catch (Exception e) { e.printStackTrace(); } return conn; } public void closeAll(Connection con, PreparedStatement ps, ResultSet rs) { //关闭资源,释放资源 if (rs != null) { try { rs.close(); } catch (SQLException e) { rs = null; } } if (ps != null) { try { ps.close(); } catch (SQLException e) { ps = null; } } if (con != null) { try { con.close(); } catch (SQLException e) { rs = null; } } } }