JSON作为轻量级的数据传输格式,在很多时候可以作为XML文件格式之外的另一个选择。使用json-lib-2.4-jdk15.jar 在后台对JSON数据进行解析
lib下必须添加json所需的jar包:
json-lib-2.4-jdk15及其依赖jar包
相关jar包:
commons-beanutils-1.8.0.jar
commons-collections-3.1.jar
commons-lang-2.5.jar
commons-logging-1.1.1.jar
ezmorph-1.0.6.jar
json-lib-2.4-jdk15.jar
json-lib-2.4-jdk15-javadoc.jar
json-lib-2.4-jdk15-sources.jar
服务器端:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ page import="java.io.BufferedReader" %>
<%@ page import="net.sf.json.*" %>
<%
BufferedReader in=request.getReader();
StringBuffer jsonStr=new StringBuffer();
String str="";
while((str=in.readLine())!=null){
jsonStr.append(str);
}
JSONObject jsonObj=JSONObject.fromObject(jsonStr.toString());
String userName=jsonObj.getString("userName");
String password=jsonObj.getString("password");
String msg="";
if(userName.equals("11")&&password.equals("11")){
msg="登陆成功'json方式'";
}else{
msg="登陆失败'json方式'";
}
response.getWriter().write(msg);
%>
客户端:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'jsonrequest.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link rel="stylesheet" type="text/css" href="resources/css/ext-all.css">
<script type="text/javascript" src="ext-all.js" ></script>
<script type="text/javascript" src="locale/ext-lang-zh_CN.js"></script>
</head>
<body>
<form id="jsonloginForm">
用户名:<input name="username" type="text">
密码:<input type="password" name="password" >
<input type="button" value="登录" onclick="jsonlogin()">
</form>
<script type="text/javascript">
function jsonlogin(){
var requestConfig={
url:"extajax/loginServerJson.jsp", //请求的服务器地址
jsonData:getJson(), //发送JSON对象
callback:function(options,success,response){
var msg=["请求是否成功:",success,"\n","服务器返回值:",response.responseText];
alert(msg.join(''));
}
}
Ext.Ajax.request(requestConfig);
}
function getJson(){
var name=document.forms[0].username.value;
var pwd=document.forms[0].password.value;
var jsonObj={
userName:name,
password:pwd
}
return jsonObj; //将JSON对象返回
}
</script>
</body>
</html>