这几天在学习Extjs中,需要用到后台与前台作数据交互,所以用了简单的servlet作后台业务处理,基于此,扩展了一下servlet的设计.
下面是JAVA代码:
package com.zwr.app.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zwr.app.model.WebSiteModel;
import com.zwr.app.util.RequestParamUtil;
/**
* extjs前台AJAX与后台交互测试Servlet
*
* @author zhu wei rong
* @since 2008-08-25
*/
@SuppressWarnings( { "serial", "unused" })
public class UserServlet extends HttpServlet {
private final String encoding = "utf-8";
private HttpServletRequest request;
private HttpServletResponse response;
protected void doBusiness() throws ServletException, IOException {
String method = request.getParameter("method");
if (method.equals("save")) {
doSave();
} else if (method.equals("list")) {
doList();
}
}
/**
* 测试grid分页显示数据,所有数据以json格式在JSP页面显示
*/
private void doList() throws ServletException, IOException {
int start = RequestParamUtil.getIntParam(request, "start", 0);
int limit = RequestParamUtil.getIntParam(request, "limit", 0);
String sort = RequestParamUtil.getParam(request, "sort", null);
String dir = RequestParamUtil.getParam(request, "dir", null);
System.out.println(start + "\t" + limit + "\t" + sort + "\t" + dir);
List<WebSiteModel> list = new ArrayList<WebSiteModel>();
for (int i = 1; i <= 10; i++) {
WebSiteModel model = new WebSiteModel();
model.setId(i);
model.setName("站点_" + i);
model.setUrl("url--" + i);
list.add(model);
}
int totalCount = list.size(); // 总数
request.setAttribute("count", totalCount);
request.setAttribute("entites", list.subList(start, (start + limit) < totalCount ? (start + limit) : totalCount));
forward("/scripts/app/data.jsp");
}
private void doSave() throws ServletException, IOException {
String name = request.getParameter("name");
String password = request.getParameter("password");
System.out.println("前台AJAX传递过来的参数:\t" + name + "\t" + password);
forward("/");
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding(encoding);
response.setCharacterEncoding(encoding);
this.request = request;
this.response = response;
doBusiness();
}
@Override
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
this.doGet(arg0, arg1);
}
public void forward(String url) throws ServletException, IOException {
getServletContext().getRequestDispatcher(url).forward(request, response);
}
}