参考原文:Jquery+ajax+json+servlet原理和Demo
本文使用JQuery实现PUT/GET例子。
启动一个Servlet实例
到目前为止,也只是启动了一个index.jsp,需要还没有启动一个servlet。要启动一个servlet,需要在HelloWeb中新建一个类JsonAjaxServlet,并将其设置到Server的web.xml中,这样就可以访问这个Servlet实例了。以下是详细过程。
<servlet>
<servlet-name>jsonAjaxAction</servlet-name>
<servlet-class>com.njupt.zhb.test.JsonAjaxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jsonAjaxAction</servlet-name>
<url-pattern>/jsonAjaxAction</url-pattern>
</servlet-mapping>
添加后如下图所示:
3. 运行结果截图
链接全路径:http://localhost:8080/HelloWeb/jsonAjaxAction?userName=tony&content=Sheldon
JQuery实现PUT GET
导入JQuery
这里使用的是1.4.3.min.js,位于https://code.jquery.com/jquery-1.4.3.min.js
将其保存于HelloWeb/WebContent/js目录下,目录结构如下:
index.jsp
<script type="text/javascript" src="js/jquery-1.4.3.min.js"></script>
<%@ page language="java" import="java.util.*"%>
<script type="text/javascript"> function query(name) { $.ajax({ type : "POST",url : "jsonAjaxAction?userName=" + name + "&content=Sheldon",timeout : 30000,dataType : "json",success : function(data) { alert("name: " + data.yourName); },}); } </script>
<table>
<tr>
<td><label>UserName:</label></td>
<td><input type="text" id="nameinput" name="name" /></td>
<td><input type="button" value="query" onClick="query(nameinput.value)" /></td>
</tr>
</table>
运行结果如下:
附1:JsonAjaxServlet.java内容
/* * $filename: JsonAjaxServlet.java,v $ * $Date: Sep 1,2013 $ * copyright (C) ZhengHaibo,Inc. All rights reserved. * This software is Made by Zhenghaibo. */
package com.njupt.zhb.test;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.servlet.servletexception;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/* *@author: ZhengHaibo *web: http://blog.csdn.net/nuptboyzhb *mail: zhb931706659@126.com *Sep 1,2013 Nanjing,njupt,China */
public class JsonAjaxServlet extends HttpServlet{
/** * */
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,HttpServletResponse response)
throws servletexception,IOException {
// Todo Auto-generated method stub
doPost(request,response);
}
@Override
protected void doPost(HttpServletRequest request,IOException {
// Todo Auto-generated method stub
request.setCharacterEncoding("utf-8");
String userName = request.getParameter("userName");
userName=URLDecoder.decode(userName,"UTF-8");
String content = request.getParameter("content");
content=URLDecoder.decode(content,"UTF-8");
System.out.println("userName:"+userName);
System.out.println("content:"+content);
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
//将数据拼接成JSON格式
out.print("{\"yourName\":\"" + userName + "\",\"yourContent\":\""+content+"\"}");
out.flush();
out.close();
}
}