处理 JSP 的 XML 数据
我有一个表单/计算器,它向自身发送一些数据,然后通过调度 servlet 来计算该数据,并将结果作为 xml 输出。调度程序代码如下所示:
//create instance
ServletContext sc = this.getServletContext();
//create dispatcher
RequestDispatcher rd = sc.getRequestDispatcher("/ProCalcServlet");
rd.include(request, response);
不过,我目前所做的事情存在一些问题。首先,是否可以使用远程 URL 而不是仅在本地?我如何处理数据,因为我假设因为它是一个 servlet,所以我不能只将其称为 XML 文档并使用 DOM 来获取我想要的数据。
对于 Java 的东西还很陌生,甚至不知道到底要在 google 上搜索什么,所以我用我目前的方法在黑暗中拍摄。任何帮助或指示将不胜感激:P干杯
I have a form/calculator, which posts to itself some data, this data is then calculated by dispatching a servlet and the results are output as xml. The dispatcher code is shown below:
//create instance
ServletContext sc = this.getServletContext();
//create dispatcher
RequestDispatcher rd = sc.getRequestDispatcher("/ProCalcServlet");
rd.include(request, response);
Have a few problems with what I'm doing at the moment though. Firstly, is it possible to use a remote URL as opposed to just locally? And how do I process the data, since I'm assuming that because it's a servlet, I can't just call it an XML document and use the DOM to grab the data I want.
Quite new to this Java stuff, don't even know what to google for exactly, so I'm kind of shooting in the dark with my current methods. Any help or directions would be greatly appreciated :P cheers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我希望我正确理解你的问题。
可以使用远程 URL。在这种情况下,您需要通过 Web 服务方式调用 URL。您可以使用 HttpClient 来调用该 URL。然后,该 URL 将以 XML 形式(在一个大字符串中)返回给您数据。
对于处理 XML,有许多库可以让您轻松地执行此操作。您可以坚持 JDK 的 DOM 或 SAX 解析器,但在我看来这很混乱。考虑使用 Castor、JDom,或 Dom4J...其中一些允许您查询数据也使用 XPath 。
I hope I understand your questions correctly.
It is possible to use remote URL. In that case, you need to invoke the URL through web service style. You can use HttpClient to call the URL. The URL will then return you data in XML form (in one big string).
For you to process the XML, there are many libraries that allow you to easily to do so. You can stick JDK's DOM or SAX parser, but in my opinion that's messy. Consider using Castor, JDom, or Dom4J... some of them allows you to query the data using XPath too.
您不能使用 RequestDispatcher 将请求转发到不同的 URL。这只允许您将请求转发到同一容器上的同一 Web 应用程序。但是,您可以使用
response.sendRedirect()
向浏览器发送到另一个站点/URL 的重定向。但是,这样做将无法传递任何对象——您必须依赖实参参数。我不确定我是否理解您使用 XML 所做的事情。您的第一个语句似乎暗示您希望将响应输出为 XML,这当然很简单,只需使用:
You cannot use a RequestDispatcher to forward a request to a different URL. This only allows you to forward requests to the same web application on the same container. You can, however, use
response.sendRedirect()
to send the browser a redirect to another site/URL. Doing this, however, you will not be able to pass any objects -- you'll have to rely on argument parameters.I'm not sure I understand what you're doing with XML. Your first statement seems to imply that you want to output the response as XML, that's certainly easy enough, just use: