struts1整合ajax技术

1.写一个继承ActionServlet的类A。在该类A中重写HttpServlet的service方法,然后调用ActionServlet中的process方法,然后从requst中得到要返回给前台的值value,如果不为空,则用response.getWriter().print(value);

2.修改web.xml中的名为action的servlet中servlet-class路径为类A的包名+A.

3.在业务Action中把execute方法的返回值设为null,把要返回到前台的对象存放到request中,使类A中的service方法能得到。

4.在写Struts-config.xml文件的action时,不用写forward。

需要下载json-lib包及其相关包。

重写httpServlet中的service方法:

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);
          }

}

}

创建一个测试action

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;
     }

}

bean:

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;
   }
     

}

web.xml文件内容如下

  
<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>

js如下:

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
}

index页面如下:

<body>
   <form action="login.do" method="post">
<input name="username" type="text" onblur="validateUser()" id="username"><br>
<input name="password" type="text"><br>
<input type="submit" value="submit"><br>
</form>

</body>

struts-config.xml内容如下:

<struts-config>
<data-sources />
<form-beans>
   <form-bean name="loginForm" type="com.cronie.struts.LoginActionForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings>
   <action path="/login" type="com.cronie.struts.Login" name="loginForm"
    scope="request" validate="false">
    <forward name="success" path="/logina.jsp" />
    <forward name="error" path="/logina.jsp" />
   </action>
   <action path="/validataUser" type="com.cronie.struts.validataUserAction"
    name="loginForm" scope="request" validate="false">

   </action>
</action-mappings>
<message-resources parameter="com.yourcompany.struts.ApplicationResources" />
</struts-config>

相关推荐