Struts2 对Ajax提供了很好的支持,使用的是DOJO,如果你不会使用DOJO DWR的话,其实使用Struts2 提供的Ajax JSP tags 也是可以的,使用很简单。
使用名为Stream的Result 即可。
配置文件
- <actionname="ajaxAction"class="com.yaxing.action.UnitInfoAction"
- method="findByUU">
- <resulttype="stream">
- <paramname="contentType">text/html</param>
- <paramname="inputName">inputStream</param>
- </result>
- </action>
<action name="ajaxAction" class="com.yaxing.action.UnitInfoAction" method="findByUU"> <result type="stream"> <param name="contentType">text/html</param> <param name="inputName">inputStream</param> </result> </action>
Action:
- publicStringfindByUU()throwsException{
- try{
- Mapsession=ActionContext.getContext().getSession();
- Stringids=session.get("userId").toString();
- listUnitInfo=this.unitInfoService.findByUU(java.net.URLDecoder.decode(userName,"UTF-8"),ids);
- if(listUnitInfo.size()>0){
- inputStream=newByteArrayInputStream(
- "true".getBytes("utf-8"));
- }else{
- inputStream=newByteArrayInputStream(
- "此单位帐号可以使用!".getBytes("utf-8"));
- }
- }catch(Exceptione){
- e.printStackTrace();
- returnINPUT;
- }
- returnSUCCESS;
- }
public String findByUU() throws Exception { try { Map session = ActionContext.getContext().getSession(); String ids = session.get("userId").toString(); listUnitInfo = this.unitInfoService.findByUU(java.net.URLDecoder.decode(userName,"UTF-8"),ids); if (listUnitInfo.size() > 0) { inputStream = new ByteArrayInputStream( "true".getBytes("utf-8")); } else { inputStream = new ByteArrayInputStream( "此单位帐号可以使用!".getBytes("utf-8")); } } catch (Exception e) { e.printStackTrace(); return INPUT; } return SUCCESS; }
页面:
- <tr>
- <tdheight="15"bgcolor="#FFFFFF">
- <divalign="center"class="STYLE1">
- <divalign="center">单位名称</div>
- </div>
- </td>
- <tdheight="15"bgcolor="#FFFFFF">
- <divalign="center">
- <spanclass="STYLE1"><inputtype="text"id="name"
- name="unitInfo.name"style="width:120px"/></span>
- </div></td>
- <tdheight="15"bgcolor="#FFFFFF">
- <divalign="center">
- <spanclass="STYLE1">
- <divid="nameTip"style="width:120px"></div></span>
- </div></td>
- </tr>
JS:
- <scriptlanguage="javascript">
- varmyRequest;
- varflag;
- functiont1(){
- //准备向后台传输的数据
- varuserName=document.getElementById("userName1").value;
- alert(userName);
- url=encodeURI(userName);
- url=encodeURI(url);
- //Ajax
- myRequest=newActiveXObject("Msxml2.XMLHTTP");
- myRequest.onreadystatechange=t2;
- myRequest.open("GET","unitInfo/ajaxAction.action?userName="+url,true);
- myRequest.send(null);
- }
- functiont2(){
- if(myRequest.readyState==4){
- varret=myRequest.responseText;
- //后续处理
- if(ret=="true"){
- flag=false;
- document.getElementById("userName1Tip").innerHTML="单位帐号重复,无法使用";
- }else{
- flag=true;
- document.getElementById("userName1Tip").innerHTML="此单位帐号可以使用";
- }
- }
- }
- functioncheckForm(){
- returnflag;
- }
- </script>