你的位置:首页 > Java教程

[Java教程]JSON表单提交(ajax异步刷新)


JSON简介:

JSON: JavaScript Object Notation(JavaScript 对象表示法)

JSON 是存储和交换文本信息的语法。类似

JSON 比

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 

 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();	}}