日期:2014-05-16 浏览次数:20683 次
public class ControllerServlet extends ActionServlet { private static final long serialVersionUID = -1967288521493475334L; protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { //调用ActionServlet 中的process方法 this.process(arg0, arg1); //从request中读取返回给ajax的数据JSONObject JSONObject ajaxResult = (JSONObject)arg0.getAttribute("ajaxResult"); //如果此数据存在,则返回 if(ajaxResult!=null){ arg1.getWriter().print(ajaxResult); } } }
public class validataUserAction extends Action{ private boolean succ=false; @Override public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { LoginActionForm actionForm=(LoginActionForm)form; //如果username等于kai则设succ为true; if(actionForm.getUsername().equalsIgnoreCase("kai")){ succ=true; } List aa=new ArrayList(); aa.add("kai"); aa.add("haha"); String[] bb = {"aaa","bbb"}; //创建返回的JSONObject对象 JSONObject result = new JSONObject(); result.put("succ", succ); result.put("name", aa); result.put("pass", bb); //把result放到request中,key值必需为ajaxResult request.setAttribute("ajaxResult", result); //一定要返回空值才能使servlet不跳转 return null; } }
public class LoginActionForm extends ActionForm{ private static final long serialVersionUID = -5121106589990012711L; private String username; private String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public static long getSerialversionuid() { return serialVersionUID; } }
<servlet> <servlet-name>struts1</servlet-name> <servlet-class>com.cronie.struts.ControllerServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>struts1</servlet-name> <!--在这我们只对*.aj格式的请求进行ajax处理--> <url-pattern>*.aj</url-pattern> </servlet-mapping>
var xmlHttp; function createXmlHttpRequest() { if (window.XmlHttpRequest) { xmlHttp = new XmlHttpRequest(); } else if (window.ActiveXObject) { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } } function validateUser() { createXmlHttpRequest(); xmlHttp.onreadystatechange = handleStateChange; xmlHttp.open("POST", "validataUser.aj", true); xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;"); var content = "username=" + document.getElementById("username").value; xmlHttp.send(content); } function handleStateChange() { if (xmlHttp.readystate == 4 && xmlHttp.status == 200) { var array; // 把返回结果转化为对象 eval("array=" + xmlHttp.responseText); //alert(array); alert(array.succ); alert(array.name); alert(array.pass); } 30 }