Ajax动态更新页面
业务逻辑:动态添加员工信息至列表,列表动态删除员工信息
页面:employeeList.jsp
员工列表
服务器:EmployeeListServlet.java
package ajaxbook.chap4;
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class EmployeeListServlet
extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GBK";
//Initialize global variables
public void init() throws ServletException {
}
//Process the HTTP Get request
public 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);
}
}
//增加员工
protected void addEmployee(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
//得到主键id
String uniqueID = storeEmployee();
//创建响应字串
StringBuffer xml = new StringBuffer("
xml.append(uniqueID);
xml.append("
xml.append("
xml.append("
//发送
sendResponse(response, xml.toString());
}
//删除员工
protected void deleteEmployee(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
//得到参数id
String id = request.getParameter("id");
//创建响应字串
StringBuffer xml = new StringBuffer("
xml.append("
xml.append("
//发送
sendResponse(response, xml.toString());
}
//发送响应字串
private void sendResponse(HttpServletResponse response, String responseText)throws IOException {
response.setContentType("text/xml");
response.getWriter().write(responseText);
}
//模拟数据库,得到主键id
private String storeEmployee() {
String uniqueID = "";
Random randomizer = new Random(System.currentTimeMillis());
for (int i = 0; i < 8; i++) {
uniqueID += randomizer.nextInt(9);
}
return uniqueID;
}
}
(责任编辑:海纳百川 qlmzl11268@hotmail.com TEL:(010)68476606-8007)







