JSON表单提交(ajax异步刷新)
JSON简介:
JSON: JavaScript Object Notation(JavaScript 对象表示法)
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。
JSON 文本格式在语法上与创建 JavaScript 对象的代码相同。
由于这种相似性,无需解析器,JavaScript 程序能够使用内建的 eval() 函数,用 JSON 数据来生成原生的 JavaScript 对象。
1.新建一个实体类(student).
public class Student { private int number; private String name; private String address; public Student(){} public Student(int number, String name, String address) { this.number = number; this.name = name; this.address = address; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; }; }
2.新建Dao接口,给出两个方法(向数据库添加数据和取出数据)。
import java.util.List; import org.json.JSONObject; public interface Dao { public boolean insertDate(Student stu); public List<JSONObject> selectAll(); }
3.实现两个方法
import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.json.JSONObject; import cn.com.yong.Dao.Dao; import cn.com.yong.Util.DBConnection; public class Student implements Dao { @Override public boolean insertDate(cn.com.yong.pro.Student stu) { Connection con=DBConnection.getDBConnectionInstance().getDBConnection(); String sql="insert into student (number,name,address) value(?,?,?)"; try { java.sql.PreparedStatement ps=con.prepareStatement(sql); ps.setInt(1, stu.getNumber()); ps.setString(2, stu.getName()); ps.setString(3, stu.getAddress()); int i=ps.executeUpdate(); if(i>0){ return true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } @Override public List<JSONObject> selectAll() { Connection con=DBConnection.getDBConnectionInstance().getDBConnection(); List<JSONObject> list=new ArrayList<JSONObject>(); String sql="select number,name,address from student"; try { ResultSet rs=con.createStatement().executeQuery(sql); while(rs.next()){ Map<String, Object> map=new HashMap<String, Object>(); map.put("number", rs.getInt(1)); map.put("name",rs.getString(2)); map.put("address", rs.getString(3)); list.add(new JSONObject(map)); } } catch (SQLException e) { e.printStackTrace(); } return list; } }
4.新建用于表单提交的html文件(为方便提交和获取放在一块)。
<!DOCTYPE html> <html> <head> <title>show3.html</title> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="this is my page"> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <!--<link rel="stylesheet" type="text/css" href="./styles.css">--> <script type="text/javascript" src="js/student3.js"></script> </head> <body> <!-- json表单注册 -->> <form action="" method="post"></form> 编号:<input type="text" name="number" id="number"/><br> 姓名:<input type="text" name="name" id="name"/><br> 住址:<input type="text" name="address" id="address"/><br> <input type="button" value="提交" onclick="insertStu()"/> </form> <!-- 读取数据 --> <input type="button" onclick="insertStu()" value="获取信息"> <table border="1px" width="100%" align="center"> <thead><tr> <th>学号</th> <th>姓名</th> <th>住址</th> </tr></thead> <tbody id="main" align="center"> </tbody> </table> </body> </html>
5.新建js文件
//浏览器协议 var xmlHttp; function creatXMLHttpRequest(){ if(window.XMLHttpRequest){ xmlHttp=new XMLHttpRequest(); }else if(window.ActiveXObject){ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } } //触发函数 function insertStu(){ //向浏览器发出异步请求 creatXMLHttpRequest(); //获取表单数据 var number=document.getElementById("number").value; var name=document.getElementById("name").value; var address=document.getElementById("address").value; //若将多个表单数据转换成json格式,前提先把这些数据存储到js的对象中 var jsObject=new fromObject(number,name,address); //将对象转换成JSON格式的数据 json=JSON.stringify(jsObject); alert(json); //开启对服务器端的连接 var url="insertServlet"; xmlHttp.open("post", url, true); //向服务器发送请求,将json格式的数据传输到servlet中 xmlHttp.send(json); //回调匿名函数,接受服务器传来的数据 xmlHttp.onreadystatechange=function (){ //判断服务器响应状态和请求状态 200表示响应ok 4表示请求完成 alert("1"); if(xmlHttp.status==200 && xmlHttp.readyState==4){ var msg=xmlHttp.responseText; //javascript能够使用内置的eval()函数生成javascript对象 var stus=eval("("+msg+")"); tbody=document.getElementById("main"); for ( var i = 0; i < stus.length; i++) { var stu = stus[i]; alert(stu.name); var tr=document.createElement("tr"); var td1=document.createElement("td"); td1.innerHTML=stu.number; //td1.appendChild(document.createTextNode(stu.number)); tr.appendChild(td1); var td2=document.createElement("td"); //td2.appendChild(document.createTextNode(stu.name)); td2.innerHTML=stu.name; tr.appendChild(td2); var td3=document.createElement("td"); //td3.appendChild(document.createTextNode(stu.address)); td3.innerHTML=stu.address; tr.appendChild(td3); tbody.appendChild(tr); } } }; } //相当于我们的实体类,转化js对象时调用 function fromObject(number,name,address){ this.number=number; this.name=name; this.address=address; }
6.Servlet
import java.io.BufferedReader; import java.io.IOException; import java.io.PrintWriter; import java.util.List; 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 org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import cn.com.yong.ImplementDao.Student; @WebServlet("/insertServlet") public class insertServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("-----------"); request.setCharacterEncoding("UTF-8"); //创建带有缓冲区的字符串对象jsn,用来存储读取到的json StringBuffer jsn=new StringBuffer(); //用io流的方式读取js页面传过来的对象json BufferedReader br=request.getReader(); String line=null; while((line=br.readLine())!=null){ jsn.append(line); } //拆分json表单中的数据 try { JSONObject jo=new JSONObject(jsn.toString()); int number=jo.getInt("number"); String name=jo.getString("name"); String address=jo.getString("address"); System.out.println(number+name+address); cn.com.yong.pro.Student st=new cn.com.yong.pro.Student(number, name, address); Student stu=new Student(); stu.insertDate(st); } catch (JSONException e) { e.printStackTrace(); } System.out.println("-------------------------------------------------------"); Student stu=new Student(); List<JSONObject> list=stu.selectAll(); //转换成jeson格式 JSONArray ja=new JSONArray(list); System.out.println(ja.toString()); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); //以io流的方式返回 PrintWriter pw=response.getWriter(); pw.write(ja.toString()); pw.flush(); pw.close(); } }