简体   繁体   English

如何在 JSP 中保存 XML 文件?

[英]How to save a XML file in JSP?

In my project I need to save XML file in JSP.在我的项目中,我需要将 XML 文件保存在 JSP 中。 I'm using Eclipse as IDE and want to save XML file within project so that XML file can be used by Fusioncharts to generate a graph. I'm using Eclipse as IDE and want to save XML file within project so that XML file can be used by Fusioncharts to generate a graph. I cannot give any local path as JSP runs on server.由于 JSP 在服务器上运行,我无法提供任何本地路径。

StreamResult result = new StreamResult(new File("C:\\graph.xml"));

This won't work in that case, so what can I do in this case?在这种情况下这不起作用,那么在这种情况下我该怎么办?

Use File#createTempFile() .使用File#createTempFile() It's platform independent and in case of a JSP/Servlet webapp it'll be created in the container-managed default temp folder.它独立于平台,如果是 JSP/Servlet webapp,它将在容器管理的默认临时文件夹中创建。

File file = File.createTempFile("graph", ".xml");
// ...

You need to use the servlet context to get a web-server independent fiel location in a servlet.您需要使用 servlet 上下文在 servlet 中获取独立于 Web 服务器的字段位置。 I like this way of doing things:我喜欢这种做事方式:

public String getCachePath( ServletContext sc, HttpServletRequest request )
{
    //get cache dir from web.xml
    String cacheDir = getInitParameter( "cache.dir");
    //String fileName = File.separator +"tmp"+File.separator +
    String fileName = sc.getRealPath( request.getContextPath() ) + File.separator + "WEB-INF" + File.separator +
    cacheDir + File.separator;
    return fileName; 
}//met

And then you can define cache.dir in your web.xml like this:然后您可以在 web.xml 中定义 cache.dir ,如下所示:

<servlet>
    <servlet-name>server</servlet-name>
    <servlet-class>fully qualified name of your class</servlet-class>
    <init-param>
        <param-name>cache.dir</param-name>
        <param-value>cache</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

As @BalusC pointed out, my first answer is maybe tied to using jetty as it expands war.正如@BalusC 指出的那样,我的第一个答案可能与使用码头有关,因为它会扩大战争。

So, a mechanism that would work whatever server you use would be introspection:因此,一种可以在您使用的任何服务器上工作的机制是自省:

 InputSream is = YouClass.getResourceAsStream( "file.xml" );

This will always work as long as file.xml is in the same folder (when deployed, in a war or not) as the folder containing the class file YourClass.class.只要 file.xml 与包含 class 文件 YourClass.class 的文件夹位于同一文件夹中(部署时,无论是否处于战争中),这将始终有效。

Eclipse as a special resource folder, enforced in maven, than you can use to put resources and ensure they will be deployed with your class files when you build your projects. Eclipse 作为特殊的资源文件夹,在 maven 中强制执行,您可以使用它来放置资源并确保在构建项目时将它们与 class 文件一起部署。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM