Jquery+ajax+json+servlet原理和Demo

10 篇文章 0 订阅
Jquery+ajax+json+servlet原理和Demo

大致过程:
用户时间点击,触发js,设置$.ajax,开始请求。服务器响应,获取ajax传递的值,然后处理。以JSON格式返回给ajax。ajax在sucess对应的函数中将返回的json数据进行解析,然后输出到jsp页面。


1.前台index.jsp

[html]  view plain copy
  1.   
[html]  view plain copy
  1. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>  
  2. <%  
  3.     String path = request.getContextPath();  
  4.     String basePath = request.getScheme() + "://"  
  5.             + request.getServerName() + ":" + request.getServerPort()  
  6.             + path + "/";  
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.     <head>  
  12.         <base href="<%=basePath%>">  
  13.   
  14.         <title>Jquery Ajax Json Servlet Demo</title>  
  15.         <meta http-equiv="pragma" content="no-cache">  
  16.         <meta http-equiv="cache-control" content="no-cache">  
  17.         <meta http-equiv="expires" content="0">  
  18.         <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.         <meta http-equiv="description" content="This is my page">  
  20.         <!-- 
  21.     <link rel="stylesheet" type="text/css" href="styles.css"> 
  22.     -->  
  23.         <script type="text/javascript" src="js/jquery.min.js"></script>  
  24.         <script type="text/javascript">  
  25.            function jsonAjaxPost(){  
  26.              var userNameObj=$("#username").val();  
  27.              var contentObj=$("#content").val();  
  28.              $.ajax({  
  29.                type:"post",//请求方式  
  30.                url:"jsonAjaxAction?userName="+encodeURI(encodeURI(userNameObj))  
  31.                    +"&content="+encodeURI(encodeURI(contentObj)),//发送请求地址  
  32.                timeout:30000,//超时时间:30秒  
  33.                dataType:"json",//设置返回数据的格式  
  34.                //请求成功后的回调函数 data为json格式  
  35.                success:function(data){  
  36.                   $("#resultJsonText").text("你的名字:"+data.yourName+"  你输入的内容:"+data.yourContent);  
  37.               },  
  38.               //请求出错的处理  
  39.               error:function(){  
  40.                         alert("请求出错");  
  41.               }  
  42.            });  
  43.           }  
  44.     </script>  
  45.     </head>  
  46.     <body>  
  47.     <form id="form1" method="post">  
  48.         <p>  
  49.             评论:  
  50.         </p>  
  51.         <p>  
  52.             姓名:  
  53.             <input type="text" name="username" id="username" />  
  54.         </p>  
  55.         <p>  
  56.             内容:  
  57.             <textarea name="content" id="content" rows="2" cols="20"></textarea>  
  58.         </p>  
  59.         <p>  
  60.             <input type="button" id="send" value="提交" onclick="jsonAjaxPost()" />  
  61.         </p>  
  62.     </form>  
  63.     <div class="comment">  
  64.         返回数据:  
  65.         <p id="resultJsonText"></p>  
  66.     </div>  
  67.     <div id="resText">  
  68.     </div>  
  69.     </body>  
  70. </html>  


2.后台Servlet

[java]  view plain copy
  1.   
[java]  view plain copy
  1. /* 
  2.  * $filename: JsonAjaxServlet.java,v $ 
  3.  * $Date: Sep 1, 2013  $ 
  4.  * Copyright (C) ZhengHaibo, Inc. All rights reserved. 
  5.  * This software is Made by Zhenghaibo. 
  6.  */  
  7. package com.njupt.zhb.test;  
  8.   
  9. import java.io.IOException;  
  10. import java.io.PrintWriter;  
  11. import java.net.URLDecoder;  
  12.   
  13. import javax.servlet.ServletException;  
  14. import javax.servlet.http.HttpServlet;  
  15. import javax.servlet.http.HttpServletRequest;  
  16. import javax.servlet.http.HttpServletResponse;  
  17.   
  18. /* 
  19.  *@author: ZhengHaibo   
  20.  *web:     http://blog.csdn.net/nuptboyzhb 
  21.  *mail:    zhb931706659@126.com 
  22.  *Sep 1, 2013  Nanjing,njupt,China 
  23.  */  
  24. public class JsonAjaxServlet extends HttpServlet{  
  25.   
  26.     /** 
  27.      *  
  28.      */  
  29.     private static final long serialVersionUID = 1L;  
  30.   
  31.     @Override  
  32.     protected void doGet(HttpServletRequest request, HttpServletResponse response)  
  33.             throws ServletException, IOException {  
  34.         // TODO Auto-generated method stub  
  35.         doPost(request, response);  
  36.     }  
  37.   
  38.     @Override  
  39.     protected void doPost(HttpServletRequest request, HttpServletResponse response)  
  40.             throws ServletException, IOException {  
  41.         // TODO Auto-generated method stub  
  42.         request.setCharacterEncoding("utf-8");  
  43.           
  44.         String userName = request.getParameter("userName");  
  45.         userName=URLDecoder.decode(userName, "UTF-8");  
  46.           
  47.         String content = request.getParameter("content");  
  48.         content=URLDecoder.decode(content, "UTF-8");  
  49.           
  50.         System.out.println("userName:"+userName);  
  51.         System.out.println("content:"+content);  
  52.           
  53.         response.setCharacterEncoding("utf-8");  
  54.         PrintWriter out = response.getWriter();  
  55.         //将数据拼接成JSON格式  
  56.         out.print("{\"yourName\":\"" + userName + "\",\"yourContent\":\""+content+"\"}");  
  57.         out.flush();  
  58.         out.close();  
  59.     }  
  60. }  


3.配置文件web.xml

[html]  view plain copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  7.   <welcome-file-list>  
  8.     <welcome-file>index.jsp</welcome-file>  
  9.   </welcome-file-list>  
  10.   <servlet>  
  11.         <servlet-name>jsonAjaxAction</servlet-name>  
  12.         <servlet-class>com.njupt.zhb.test.JsonAjaxServlet</servlet-class>  
  13.     </servlet>  
  14.     <servlet-mapping>  
  15.         <servlet-name>jsonAjaxAction</servlet-name>  
  16.         <url-pattern>/jsonAjaxAction</url-pattern>  
  17.     </servlet-mapping>  
  18. </web-app>  


4.其他
1.需要导入jquery.min.js
2.注意乱码的解决方案:
 2.1:js中对字符串进行编码,即:encodeURI(encodeURI(userNameObj))
 2.2:在Servlet中需要用java.net.URLDecoder解码
5.结果演示
在浏览器中输入:http://localhost:8080/AjaxServletJson/
先输入,然后点击按钮:

源代码下载:http://download.csdn.net/detail/nuptboyzhb/6193851
参考资料

1.jquery $.ajax参考手册:http://www.w3school.com.cn/jquery/ajax_ajax.asp

未经允许不得用于商业目的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值