package Servlet; import JDBC.JDBC; 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 wrong1() { String msg = "注册成功!"; int type = JOptionPane.YES_NO_OPTION; String title = "信息提示"; 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); } }
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/RegisterServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>RegisterServlet</servlet-name> <servlet-class>Servlet.RegisterServlet</servlet-class> </servlet> </web-app>
package JDBC; 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; } } } }