1. 浏览器发送json数据到服务器:
(1)先将提交的数据封装成js对象。再使用JSON.stringfiy(对象名)转换为json对象,再通过ajax发送就好了;
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
<title>index</title>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("登录成功");
//跳转等
// document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","test_json",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(login());
}
function login(){
var u_name = $("#username").val();
var u_pwd = $("#password").val();
var u_age = $("#age").val();
var user={"username":u_name,"password":u_pwd,"age":u_age};
return JSON.stringify(user);
}
</script>
</head>
<body>
<div id="send">
<input id = "username" type= "text"/>
<input id = "password" type= "password"/>
<input id = "age" type= "text"/>
<button οnclick="loadXMLDoc()">提交</button>
</div>
</body>
</html>
POJO类:
package cn.ltp.bean;
public class User {
private String username;
private String password;
private Integer age;
public User() {
super();
}
public User(String username, String password, Integer age) {
super();
this.username = username;
this.password = password;
this.age = age;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
获取用户信息的servlet:
protected void doPost(HttpServletRequest request, HttpServletResponse response){
try {
request.setCharacterEncoding("utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
response.setContentType("text/html;charset=utf-8");
String userInfo = null;
try {
userInfo = JsonUtils.jsonCastToString(request.getReader());
} catch (IOException e1) {
e1.printStackTrace();
}
JSONObject jsonObject = JSONObject.fromObject(userInfo);
System.out.println(((User)jsonObject.toBean(jsonObject, User.class)).getUsername());
}
fromObject方法是用来将json字符串转换为json对象。
toBean方法是用来将json对象转换成JavaBean对象
JSONArray.fromObject(list)方法用来将一个List<Bean>转换成一个Json数组。
jsonArray.toString()将数组转换成String。
其中JSONObject的使用需要引入jar包。
JsonUtils工具类用于将读取到的字符流信息转换为字符串:
package cn.ltp.utils;
import java.io.BufferedReader;
public class JsonUtils {
public static String jsonCastToString(BufferedReader reader){
StringBuffer jb = new StringBuffer();
String line = null;
try {
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return jb.toString();
}
}
服务器返回json数据给页面:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String jsonString = Service.getUser();
request.setAttribute("userInfo_json", jsonString);
request.getRequestDispatcher("/index.jsp").forward(request, response);
//System.out.println(jsonString);
}
页面接收json数据:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index</title>
<script type="text/javascript">
οnlοad=function showUser(){
var str = '${requestScope.userInfo_json}';
var jsonList = eval(str);
var show = document.getElementById("show");
for(var i = 0; i<jsonList.length; i++){
var username = jsonList[i].username;
var pwd = jsonList[i].password;
var age = jsonList[i].age;
show.innerHTML += username+pwd+age;
}
}
</script>
</head>
<body>
<div id="show">
用户信息列表
</div>
</body>
</html>