简体   繁体   中英

How to save a XML file in JSP?

In my project I need to save XML file in 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 cannot give any local path as JSP runs on server.

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() . It's platform independent and in case of a JSP/Servlet webapp it'll be created in the container-managed default temp folder.

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

You need to use the servlet context to get a web-server independent fiel location in a servlet. 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:

<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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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