ajax代码
var obj1={
"name":"张三",
"age":30
};
alert(JSON.stringify(obj1))
function sendJson() {
$.ajax({
type:"post",
url: "json?method=check",
<!-- 这里contentType没加,servlet读取出来的是null!!!! -->
contentType: "application/json",
data: JSON.stringify(obj1),
success: function(data){
alert("success")
}
})
}
servlet代码
@WebServlet("/json")
public class JsonController extends BaseServlet {
public void check(HttpServletRequest request, HttpServletResponse response) throws IOException {
//先创建字符流来读取json
String collect = request.getReader().lines().collect(Collectors.joining());
//这里用fastjson来解析
JSONObject jo = JSON.parseObject(collect);
//获取name和age对应的值
String name = jo.getString("name");
int age = jo.getInteger("age");
System.out.println("name: "+name+";"+"age: "+age);
}
}
用了ajax后,在servlet无论是请求转发还是重定向都会没用,两者冲突,一般在前台进行页面跳转
JSON转换
//把对象转换为json格式,json的键就是类的成员变量名
JSONObject json;
Message message = new Message(code, msg);
String s = JSON.toJSONString(message);
json = JSON.parseObject(s);
//将map格式转换为json
HashMap<String, Object> userInfo = (HashMap<String, Object>) session.getAttribute("userInfo");
JSONObject json = new JSONObject();
String s = JSON.toJSONString(userInfo);
json = JSON.parseObject(s);
//将json数据转化为对象
String collect = request.getReader().lines().collect(Collectors.joining());
JSONObject json = new JSONObject();
json = JSON.parseObject(collect);
//json是有数据的
User user = JSON.toJavaObject(json, User.class);