当前位置: 代码迷 >> JavaScript >> JQuery、JSON、Ajax在Servlet中的运用
  详细解决方案

JQuery、JSON、Ajax在Servlet中的运用

热度:396   发布时间:2012-11-22 00:16:41.0
JQuery、JSON、Ajax在Servlet中的应用
准备条件:

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>
1 楼 布衣九久 2010-07-13  
博主的这篇文章对我的帮助很大,谢谢
  相关解决方案