尚未发现Flex中有可以直接渲染HTML代码的组件, 但可通过服务器端配合实现预览.
原理: Flex(尤指AIR环境), 使用URLLoader发送POST请求, 将要预览的HTML代码发送到服务器端Servlet, 服务器端收到请求后创建临时文件, 将HTML存到临时文件中. Flex端收到URLLoader Complete事件后, 使用navigateToURL navigate到Servlet上(使用GET), Servelet 返回文件内容 —- 在上述过程中, Flex端生成UUID作为代码读写的key.
Flex端代码:
protected var uuidPriview:String; /** * 在浏览器中预览邮件, 解决方法: 生成uuid, 连同邮件内容发送到服务器端, 服务器端创建文件, 完毕后携带uuid Navigat到服务器端, 服务器端返回邮件内容, 实现预览. * 在AIR中, 会将POST视为GET: * in Adobe AIR, when using the navigateToURL() function, the runtime treats a URLRequest that uses the POST method (one that has its method property set to URLRequestMethod.POST) as using the GET method. * @see http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/package.html#navigateToURL() **/ protected function priviewInBroswer():void { var urlReq:URLRequest = new URLRequest(PRIVIEW_URL); urlReq.method = URLRequestMethod.POST; var data:URLVariables = new URLVariables; data.content = "html codes...."; // 放入要预览的代码 data.uuid = uuidPriview = UIDUtil.createUID(); // 生成UUID, 作为Java端文件名. urlReq.data = data; var urlLoader:URLLoader = new URLLoader(); urlLoader.addEventListener(Event.COMPLETE, onPriviewSendSuccess); urlLoader.load(urlReq); } /** 预览请求发送结束后响应. */ protected function onPriviewSendSuccess(e:Event):void { var urlReq:URLRequest = new URLRequest(PRIVIEW_URL); var data:URLVariables = new URLVariables; data.uuid = uuidPriview; // Get中携带uuid. urlReq.data = data; navigateToURL(urlReq); // 打开浏览器 }
Java端代码:
/** * 接收到Get请求后, 读取uuid, 读取uuid对应文件的内容, 写到response中, 客户端实现预览. */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String uuid = req.getParameter("uuid"); String content = FileUtil.getStringFromFile("E:\\temp\\priview\\" + uuid); // 读取内容 resp.getWriter().write(content); } @Override /** * 接受请求, 创建文件, 文件名称为创建的uuid. */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String content = req.getParameter("content"); String uuid = req.getParameter("uuid"); String filePath = "E:\\temp\\priview\\" + uuid; File pf = new File(filePath); pf.createNewFile(); FileUtil.saveStringToFile(content, pf, "utf-8"); // 创建并写入文件 resp.getWriter().write("get it"); }
乌拉泊 Ulanbay <->
// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.