0

I have a little problem with Struts 2 when I try to get the context path :

ServletActionContext.getServletContext().getRealPath("\\WebContent\\resources\\img\\");

I got this path:

C:\Users\killian\workspace.metadata.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SiteWebAdministrable\WebContent\resources\imgicone.jpg

Why the exact source path ?

Because i need to upload and save images for an admin website to control background and without the actual path i cannot save images in the resources path... So i save the path with the name and extension in the database (no problem), and i need to save the image in the resource directory (image problem...)

Can someone help me please ? Did i forgot something ?

This question is the answer ?

How do you get the project path in Struts 2?

Community
  • 1
  • 1

2 Answers2

0
servletContext.getServletContext().getRealPath("/resources/img/name_of_image.png")

So, passing the "/" to getRealPath() would return you the absolute disk file system path of the /web folder of the expanded WAR file of the project. Something like /path/to/server/work/folder/demo.war/ which you should be able to further use in File or FileInputStream.

Note that most starters don't seem to see/realize that you can actually pass the whole web content path to it and that they often use

String absolutePathToIndexJSP = servletContext.getRealPath("/") + "demo.png";

instead of

String absolutePathToIndexJSP = servletContext.getRealPath("/demo.png");

getRealPath() is unportable; you'd better never use it

Use getRealPath() carefully.

If all you actually need is to get an InputStream of the web resource, better use ServletContext#getResourceAsStream() instead, this will work regardless of the way how the WAR is expanded. So, if you for example want an InputStream of index.jsp, then do not do:

InputStream input = new FileInputStream(servletContext.getRealPath("/demo.png")); // Wrong!

But instead do:

InputStream input = servletContext.getResourceAsStream("/demo.png"); // Right!

Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.

Set<String> resourcePaths = servletContext.getResourcePaths("/");
Saurabh Mehta
  • 228
  • 1
  • 4
  • 15
0

I try .\File in eclipse struts debug mode, and get eclipse folder:

private String localDirectory = ".\\File";
File localFile = new File(localDirectory, FileName);
System.out.println(localFile.getAbsolutePath());
yu yang Jian
  • 6,680
  • 7
  • 55
  • 80