您的位置:首页 > Web前端 > JQuery

JQuery、JSON、Ajax在Servlet中的应用

2016-05-21 11:32 423 查看
1、在Java中正确得到JSONObject,需要导入JSON的JAVA支持包“json-lib-2.3-jdk15.jar”,同时需导入 JSON依赖包“commons-logging-1.0.4.jar”,“commons-lang.jar”,“commons- collections.jar”,“commons-beanutils.jar”,“ezmorph-1.0.4.jar”;

2、由于在客户端脚本中要用到JQuery与JSON,需引入"JQuery.js"与"json2.js"。 
JAVA 代码如下:

package example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class JasonServlet extends HttpServlet {

/**
* Constructor of the object.
*/
public JasonServlet() {
super();
}

public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
String userStr = readJSONString(request);//得到requestContext
JSONObject jsonObj = JSONObject.fromObject(userStr);//转换成JSONObject
System.out.println(jsonObj.getInt("userId"));//得到JSONObject的userId值
System.out.println(jsonObj.getString("name"));

JSONObject resultJSON = new JSONObject();//构建一个JSONObject
resultJSON.accumulate("errNum", 1);
resultJSON.accumulate("errInfo", "成功");

response.setContentType("application/x-json");//需要设置ContentType 为"application/x-json"
PrintWriter out = response.getWriter();
out.println(resultJSON.toString());//向客户端输出JSONObject字符串
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* Initialization of the servlet. <br>
*
* @throws ServletException
* if an error occure
*/
public void init() throws ServletException {
// Put your code here
}
public String readJSONString(HttpServletRequest request){
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while((line = reader.readLine()) != null) {
json.append(line);
}
}
catch(Exception e) {
System.out.println(e.toString());
}
return json.toString();
}

}

JSP代码: 
<%@ 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>

<title>My JSP 'JasonTest.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">
-->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/json2.js"></script>
</head>

<body>
<script type="text/javascript">
function User(userId, name) {
this.userId = userId;
this.name = name;
}
function requestServlet()
{
var urlStr="http://192.168.1.118:8080/AjaxTest/servlet/JasonServlet";
var user = JSON.stringify(new User(101,"阿猫"));

//调用JQuery提供的Ajax方法
$.ajax({
type:"POST",
url:urlStr,
data:user,
dataType: "jason",//此处要设置成jason
success: callback});//回调函数
}
function callback(jasonObj)
{
var str = jasonObj;
var obj = JSON.parse(str);//调用Json2.js中提供的JSON解析器来解析成JSONObject
alert(obj.errNum);
}
requestServlet();
</script>
</body>
</html>

from:http://xinkong1010.iteye.com/blog/635743
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery servlet ajax json