Java EE web-application file creation - java

I'm developing a web application in java to control my stock and do some other things. I upload files through a JSF component. This files are images. Anyway, my question is, I want these images to be stored in the web application's resource folder. More specifically in a subfolder named "userUploads". I create a File object but how do I a get a String representing that path?

If you want your files to be stored in your "web application's resource folder" I'm guessing you mean a folder called 'resources' inside the 'webroot'. While this is not really the best approach, you can achieve this by using the ServletContext:
ServletContext sc = httpRequest.getSession().getServletContext();
String path = sc.getPath("resources");
or
File file = new File(sc.getPath("resources"))
Personally, I'd recommend creating your 'uploads' folder outside of your web app's directory, so that it is not replaced during deployment etc.
"I create a File object but how do I a get a String representing that path?"
If you have a File object, you can call myFile.getAbsolutePath() to get a string representation of the path.

Do the following:
Get the HttpSession from the HttpServletRequest.
Get the ServletContext from the HttpSession.
Get the absolute path to your installation using the ServletContext.getRealPath() method. The parameter to this method is a path that is relative to your context root.
Here is a link: ServletContext

Related

Java rest service with JSON file

I have done a project with a simple Java Rest service and Ajax calls.
Unfortanely if i set the path to the json file as something general (fileName.json), it will not open my file.
If i set a complete path like C:\Users\Username\workspace\RestApplication\fileName.json, it works but when i will submit the project for review, it wont have the same path on my teachers computer.
The file currently resides in the main folder of the project. How can i make a general path that will work on whatever computer opens the project?
Thanks!
you should put the file you want to load in the classpath.
The class path is the path that the Java runtime environment searches for classes and other resource files.
Put your file inside your src or resources folder (I don't know your project structure)
and try to load it with:
InputStream is = TestResource.class.getResourceAsStream("/fileName.json");
or put the file under WEB-INF
#Context ServletContext servletContext;
InputStream is = servletContext.getResourceAsStream("/WEB-INF/fileName.json");
Although numerous different options you most likely want to refer to it on the classpath. See https://en.wikipedia.org/wiki/Classpath_(Java)

How to get file system path of the context root of any application

I am working on web application.I invoke on my jsp request.getContextPath(), but strangely I got address /streetshop.
Then I am appending some path as request.getContextPath() + "abc" and create folder.
Then its creating folder in D:// instead of my webapplication folder.
Please, tell me, I want to upload an image in put it in my web-application root/images/images.gif.
You mix things up here. HttpServletRequest.getContextPath() returns your web application root path. In your example this is /streetshop, so your URL may look similar to www.myapp.com/streetshop. If you want to access the internal file system path, you must obtain it from the ServletContext using request.getServletContext().getRealPath("/"). This should return the location of your WAR files' WebContent folder.
Keep in mind that if you modify contents of this path during runtime, you're going to loose everything when redeploying your application.

Java: how to verify image file on localhost exists

This is driving me bonkers. I'm writing a web app in Java and all I want to do is verify the existence of an image that's saved to an /images folder right under the web root.
The 1,000,000 google searches I did seemed to indicate that the File.exists(path) method is the way to go. But for obvious reasons, I don't want to hard code the path.
Physically, the test image file I'm working with exists on my D-drive at, let's say, D:\documents\images\myimage.jpg. GlassFish is my local server and I don't think my image files are replicated to a "GlassFish folder" when my app is deployed, so I think the only physical copy is the one on the D: drive.
The only way I can get:
boolean fileExists = new File(somePath).exists();
to return TRUE is using the string "D:\documents\images\myimage.jpg". What I was after is a test like exists() that maybe uses a URL that I could couple with some other method or parameter that references the site root and I could build the rest of the URL relative to that.
Any help is much appreciated.
Since documents is the web root, you should be able to use the ServletContext.getRealPath(String) method.
ServletContext context = servletRequest.getSession().getServletContext();
// Or if you have the servlet instead of request, use this:
// ServletContext = servlet.getServletContext(); // see comment by BalusC
String virtualPath = "/images/myimage.jpg";
String realPath = context.getRealPath(virtualPath);
// realPath will be D:\documents\images\myimage.jpg
http://download.oracle.com/javaee/5/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
Returns a String containing the real path for a given virtual path. For
example, the path "/index.html" returns the absolute file path on the server's
filesystem would be served by a request for "http://host/contextPath/index.html",
where contextPath is the context path of this ServletContext..
The real path returned will be in a form appropriate to the computer and
operating system on which the servlet container is running, including the proper
path separators. This method returns null if the servlet container cannot translate
the virtual path to a real path for any reason (such as when the content is being
made available from a .war archive).
Maybe you can put your images in the war file and use getResourceAsStream to get the file?
In that case the path would be relative to the root of the war file

Create a file and store in Java web application folder

I would like to create an xml file and store in a folder within my spring Mvc web application.
I can get the root of my application with request.getContextPath()
but
how do i get the application's relative path so it will work on any machine indipendently by the location of the application's folder?
Like C:/folder/folder/MYAPPLICATIONROOTFOLDER
You want to do this.
First, you need to get the ServletContext. I don't know how this is done in Spring MVC, but it's there somewhere.
Then you can do:
ServletContext ctx = getServletContextFromSpringSomehow();
String path = ctx.getRealPath("/folder/filename.txt");
FileWriter fw = new FileWriter(path);
The key here is ServletContext.getRealPath. It gives you the local file system path of a resource from within your webapp. Observer that you use "/" here, as it's a URL, not a file name. The container will give you a valid file name in return. Note, this only works if your container explodes your WAR, or you deploy an exploded WAR. If the WAR is NOT exploded, you will get a null back from the container.
Also note, this WILL work for non-existent files. The container does not check for the actual existence of the file. But it will be up to you to actually create any missing intermediate directories, etc.
Finally, of course, that even if you get a file path back, doesn't mean you can actually write to that path. That's a OS permission issue outside of the scope of the container.
One solution is to bundle the XML with the clases in the JAR/WAR and then use the getResourceAsStream() to leverage the ClassLoader to locate the file.
If I put the file foo.xml with the classes in com/stackoverflow/example, I could then locate the resources from objects in that bundle with
InputStream is = MyClass.getResourceAsStream( "com/stackoverflow/example" );
and from here process the file with a XML parser or whatever else you wanted to do to read the file.

How can I get the filename of a servlet resource?

I'm writing a java servlet that calls a function in a jar. I have no control over the code in this jar. The function being called wants the filename of a configuration file as an argument.
I'd like to bundle this file with my war file. If I put it in the war somewhere, what filename can I pass the function in the jar?
Note that only a filename can be used with the jar's API. So ServletContext.getResourceAsStream() is not helpful.
Use ServletContext.getRealPath(). This returns the filesystem path for a given servlet context resource. You pass it the same argument as you would pass to ServletContext.getResourceAsStream()
Better yet, use Spring's Resource abstraction:
Resource resource = new ServletContextResource(servletContext, "/path/to/file");
File resourceFile = resource.getFile();
If it's in your .war file, you won't be able to access it as a file. Some servlet containers will explode a .war file into components, but I don't think you can rely on it.
Have you thought about extracting it (via getResourceAsStream()), writing it to a temp file/directory, and then referencing that ?

Categories