日期:2014-05-16  浏览次数:20415 次

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" co