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> 

from: http://xinkong1010.iteye.com/blog/635743
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值