发布网友 发布时间:2022-04-10 08:45
共5个回答
懂视网 时间:2022-04-10 13:06
"#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":password, } }) }else{ alert("请检查您的输入!"); } }) </script> </html>后端Servlet代码:
package com.jquery.register; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class add extends HttpServlet { public void destroy() { super.destroy(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, 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后台交互成功"); try{ Class.forName(drive); conn = DriverManager .getConnection("jdbc:mysql://localhost:3306/test?user=root&password=123"); System.out.println("数据库连接成功"); 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 { //注意关闭原则:从里到外 if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } public void init() throws ServletException { // Put your code here } }
截图:
html,jquery,ajax,servlet,mysql实现前端数据写入数据库
标签:encoding response imp word man web amp http pack
热心网友 时间:2022-04-10 10:14
ajax是异步更新,不需要刷新页面的。 用jquery里面的ajax。热心网友 时间:2022-04-10 11:32
你会用jquery么,不会的话就太麻烦了。默认当你会了热心网友 时间:2022-04-10 13:07
这种其实可以不用Ajax都可以啊 放数据进request就行了 再用EL表达式什么的 拿出来热心网友 时间:2022-04-10 14:58
jsp页面:<jsp:useBean id="s" beanName="这里写s对象是那个类的对象" type="这里写对象返回值类型">