New WebProject Project under MyEclipse
The program only implements front-end data to the backend to write to the database
Front-end HTML code:
<! DOCTYPE html> $("#register"). Click (function () {var name=$ ("#name"). Val (); var password=$ ("#password"). Val (); if(name!= "" &&password!= ""{$.ajax ({type:"POST", URL:"Add", DataType:"JSON", data:{"Name": Name,"Password":p Assword,}}) }Else{alert ("Please check your input!" "); } }) </script>Back-end servlet code:
PackageCom.jquery.register;Importjava.io.IOException;ImportJava.io.PrintWriter;Importjava.sql.Connection;ImportJava.sql.DriverManager;Importjava.sql.PreparedStatement;ImportJava.sql.ResultSet;Importjava.sql.SQLException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classAddextendsHttpServlet { Public voiddestroy () {Super. Destroy (); } Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {doPost (request,response); } Public voidDoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html"); PrintWriter out=Response.getwriter (); Request.setcharacterencoding ("Utf-8"); Response.setcharacterencoding ("Utf-8"); Connection Conn=NULL; PreparedStatement stmt=NULL; ResultSet RS=NULL; String name=request.getparameter ("name"); String Password=request.getparameter ("Password"); String Drive= "Com.mysql.jdbc.Driver"; System.out.println ("Ajax Background Interactive Success"); Try{class.forname (drive); Conn=DriverManager. getconnection ("Jdbc:mysql://localhost:3306/test?user=root&password=123"); System.out.println ("Database connection succeeded"); String SQL= "INSERT into user_table (Name,password)"; SQL+ = "VALUES (?,?)"; stmt=conn.preparestatement (SQL); Stmt.setstring (1, name); Stmt.setstring (2, password); Stmt.executeupdate (); System.out.println ("Success");//Out.flush ();//out.close ();}Catch(ClassNotFoundException e) {e.printstacktrace (); } Catch(SQLException e) {e.printstacktrace (); }finally { Try { //Note the closing principle: from inside to outside if(rs! =NULL) {rs.close (); } if(stmt! =NULL) {stmt.close (); } if(Conn! =NULL) {conn.close (); } } Catch(SQLException e) {e.printstacktrace (); } } } Public voidInit ()throwsservletexception {//Put Your code here }}
:
Html,jquery,ajax,servlet,mysql implementing front-end data to the database