这个例子可以比较基础。高手请跳过。本人刚学ajax,觉得好强大。
1:首先我们写一个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> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <script type="text/javascript" src="scripts/jquery-1.4.4.js"></script> <script type="text/javascript"> $(function(){ $("#button1").click(function(){ $.ajax({ type: "GET", url: "Myservlet", dateType: "html", data:{'param1':$("#param1").val(), 'param2':$("#param2").val()}, success: function(returnedData){ $("#result").val(returnedData); } }); }); }); </script> </head> <body> <input type="text" id="param1">+ <input type="text" id="param2">= <input type="text" id="result"> <input type="button" value="get content from server" id="button1"> </body> </html>
2:在web.xml(这里没有用struts,如果用了也可以在那里配置)中配置一个action。
<servlet> <servlet-name>Myservlet</servlet-name> <servlet-class>servlet.Myservlet</servlet-class> </servlet> <servlet> <servlet-mapping> <servlet-name>Myservlet</servlet-name> <url-pattern>/Myservlet</url-pattern> </servlet-mapping>
package servlet; 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; public class Myservlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { int param1=Integer.parseInt(req.getParameter("param1")); int param2=Integer.parseInt(req.getParameter("param2")); resp.setHeader("pragma", "no-cache"); resp.setHeader("cache-control", "no-cache"); PrintWriter out = resp.getWriter(); //把该结果返回到ajax.jsp页面中的result文本框 //out.println("helloworld");//用于测试 out.println(String.valueOf(param1+param2)); out.flush(); } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req,resp); } }