Ajax基础教程(4)- 实现基本Ajax技术 4.7 动态更新Web页面

http://tech.ddvip.com   2007年11月21日    社区交流

内容摘要:如前所述,如果页面中只有一小部分需要修改,此时Ajax技术最适用。换句话说,以前实现一些用例时,为了更新页面中的一小部分总是需要使用完全页面刷新,这些用例就很适合采用Ajax技术。

  点击Add按钮启动数据库插入操作。基于Add按钮的onclick事件将调用addEmployee函数。addEmployee函数使用createAddQueryString来建立查询串,其中包括用户输入的员工姓名、职位和部门信息。创建XMLHttpRequest对象并设置onreadystatechange事件处理程序后,请求提交到服务器。

  代码清单4-14列出了处理请求的Java servlet,当接收到请求时将调用servlet的doGet方法。这个方法获取查询串action参数的值,并把请求指向适当的方法。如果是增加信息,请求指向addEmployee方法。

  代码清单4-14 EmployeeListServlet.java

  package ajaxbook.chap4;
  import java.io.*;
  import java.net.*;
  import java.util.Random;
  import javax.servlet.*;
  import javax.servlet.http.*;
  public class EmployeeListServlet extends HttpServlet {
  protected void addEmployee(HttpServletRequest request
   , HttpServletResponse response)
  throws ServletException, IOException {
  //Store the object in the database
  String uniqueID = storeEmployee();
  //Create the response XML
  StringBuffer xml = new StringBuffer("<result><uniqueID>");
  xml.append(uniqueID);
  xml.append("</uniqueID>");
  xml.append("</result>");
  //Send the response back to the browser
  sendResponse(response, xml.toString());
  }
  protected void deleteEmployee(HttpServletRequest request
   , HttpServletResponse response)
  throws ServletException, IOException {
  String id = request.getParameter("id");
  /* Assume that a call is made to delete the employee from the database */
  //Create the response XML
  StringBuffer xml = new StringBuffer("<result>");
  xml.append("<status>1</status>");
  xml.append("</result>");
  //Send the response back to the browser
  sendResponse(response, xml.toString());
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {
  String action = request.getParameter("action");
  if(action.equals("add")) {
  addEmployee(request, response);
  }
  else if(action.equals("delete")) {
  deleteEmployee(request, response);
  }
  }
  private String storeEmployee() {
  /* Assume that the employee is saved to a database and the
  * database creates a unique ID. Return the unique ID to the
  * calling method. In this case, make up a unique ID.
  */
  String uniqueID = "";
  Random randomizer = new Random(System.currentTimeMillis());
  for(int i = 0; i < 8; i++) {
  uniqueID += randomizer.nextInt(9);
  }
  return uniqueID;
  }
  private void sendResponse(HttpServletResponse response, String responseText)
  throws IOException {
  response.setContentType("text/xml");
  response.getWriter().write(responseText);
  }
  }

来源:CSDN    责编:豆豆技术应用

正在加载评论...