扫一扫
分享文章到微信
扫一扫
关注官方公众号
至顶头条
在本页阅读全文(共9页)
读入文件
准备好 VXML 可供使用后,您也就为开始编码作好了最终的准备。首先从一个仅载入 VXML 文件的 Servlet 开始。清单 3 是一个实现此功能的 Servlet ―― 载入 清单 2 中开发的 VXML。这段代码没有任何输出,所以期望值暂时不要太高。
package com.ibm.vxml;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;
public class VoiceXMLServlet extends HttpServlet {
private static final String VXML_FILENAME =
"simple-voice_recog.xml";
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String vxmlDir = getServletContext().getInitParameter("vxml-dir");
BufferedInputStream bis = null;
ServletOutputStream out = null;
try {
// Load the VXML file
File vxml = new File(vxmlDir + "/" + VXML_FILENAME);
FileInputStream fis = new FileInputStream(vxml);
bis = new BufferedInputStream(fis);
// Output the VXML file
int readBytes = 0;
while ((readBytes = bis.read()) != -1) {
// output the VXML
}
} finally {
if (out != null) out.close();
if (bis != null) bis.close();
}
}
}
|
这段代码非常直观。它载入一个 XML 文件 ―― 通过 servlet 的配置上下文中的目录和一个常量文件名指定,然后遍历文件内容。您要将文件的路径硬编码到 servlet 中,但至少将目录名存储到 Web.xml 文件中是一个非常不错的主意,此文件位于 servlet 上下文的 WEB-INF/ 目录下。清单 4 展示了 Web.xml 中的上下文参数。
<context-param>
<param-name>vxml-dir</param-name>
<param-value>/path-to-your-voicexml-dir/voicexml</param-value>
</context-param>
|
若编译 servlet 并尝试在 Web 浏览器中载入它,您只会看到一个空白的屏幕,同样,您应确保至少会看到这样的空白屏幕。如果得到错误,就需要予以更正。例如,常常会出现文件访问问题或 VXML 文件路径录入错误。一旦得到了空白屏幕,也就准备好实际输出 VXML 文件了。
首先,您需要访问一个输出对象,这样才能向浏览器发送内容。这非常简单:
// Load the VXML file
File vxml = new File(vxmlDir + "/" + VXML_FILENAME);
FileInputStream fis = new FileInputStream(vxml);
bis = new BufferedInputStream(fis);
// Let the browser know that XML is coming
out = res.getOutputStream();
|
从文件提取内容也非常简单,只要使用一行代码即可:
// Output the VXML file
int readBytes = 0;
while ((readBytes = bis.read()) != -1) {
// output the VXML
out.write(readBytes);
}
|
虽然上述代码看似已经足够,但您依然需要告知浏览器您正在向它发送 XML。切记,浏览器用于 HTML,某些浏览器可能无法顺利接收 XML。您可设置内容类型,也可设置内容的长度,只要再次使用 HttpServletResponse 对象即可:
// Let the browser know that XML is coming
out = res.getOutputStream();
res.setContentType("text/xml");
res.setContentLength((int)vxml.length());
|
如果您非常迫切的想了解IT领域最新产品与技术信息,那么订阅至顶网技术邮件将是您的最佳途径之一。