1、import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import com.px1987.webajax.model.*;i
2、mport java.io.*;public class SearchAction extends Action public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) String cityName = request.getParameter(cityName); try cityName = new String(cityName.getBytes(ISO-8859-1), gb2312 ca
3、tch (UnsupportedEncodingException e) / TODO 自动生成 catch 块 e.printStackTrace(); CreateXMLInterface createXML=new CreateXMLBean(); /它代表我们的业务功能方法 String xmtFileResult=createXML.createXMLText(cityName); response.setContentType(text/xml; charset=GBK/*将 Cache-Control 设为 no-cache 将确保浏览器不会从缓存相同的URL(包括参数)返回的应
4、答。*/ response.setHeader(Cache-Control, no-cache PrintWriter out; out = response.getWriter(); out.write(xmtFileResult); / out.print(sb.toString(); out.close(); catch (IOException e) return null; 注意:重要的是把响应的内容类型设置为text/xml,否则 XMLHttpRequest 不会把响应内容解析成 XML DOM。4、创建业务类的接口和业务类的实现类(1)业务类的接口CreateXMLInterf
5、ace,包名称为com.px1987.webajax.model;(2)在该接口中定义下面的方法package com.px1987.webajax.model;public interface CreateXMLInterface public String createXMLText(String inputCityName);(3)业务类的实现类CreateXMLBean,包名称为com.px1987.webajax.model5、编程该业务组件类public class CreateXMLBean implements CreateXMLInterface public CreateX
6、MLBean() /* 产生的XML文档为 data XXX /message */ public String createXMLText(String inputCityName) StringBuffer oneStringBuffer=new StringBuffer( /实际应该利用DAO进行数据库访问来获得 oneStringBuffer.append(+inputCityName+ oneStringBuffer.append( return oneStringBuffer.toString();1.1.2 测试本示例的目前实现的应用效果1、配置服务器2、部署本Web项目3、启动
7、服务器4、执行该页面 http:/127.0.0.1:8080/StrutsAJAXWebApp/index.jsp5、将产生出下面的结果6、注意中文乱码的解决的方法public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) request.setCharacterEncoding( /对异步请求无效 String cityName = request.getParameter( cityName = new String(cityName.getBytes( /。7、再执行,将不会出现中文乱码8、理解和体验“无刷新”的效果尽管也是get提交,但与正常的get提交的不同点在于浏览器的URL地址栏中不出现查询字符串。同时在服务器的控制台中产生出下面的结果9、如果用户没有输入,则出现下面的错误提示10、如果出现运行时的错误,提示为
copyright@ 2008-2023 冰点文库 网站版权所有
经营许可证编号:鄂ICP备19020893号-2