path till WEB-INF inside web application - java

I am parsing the HttpRequest inside a web application. My servlet extends HttpServlet
I need to find the path till WEB-INF inside a WAR file so that file present inside WEB-INF can be accessed.
I cannot use Realpath so there has to be some alternative.
tried using
ServletContext servletContext = getServletContext();
InputStream input = servletContext.getResourceAsStream("/WEB-INF");
but everytime
Sysem.out.println(input) returns null
Please suggest.

You can get the root web directory of your application like this:
servletContext.getRealPath(File.separator));
So assuming your WEB-INF is in there, you could do this:
servletContext.getRealPath(File.separator + "/WEB-INF/whatever.file"));
It returns a String path, so to actually get the file:
new File(servletContext.getRealPath(File.separator + "/WEB-INF/whatever.file")));

Related

Servlet image filter doesn't work on online host [duplicate]

In the following snippet:
ServletContext context = request.getServletContext();
String path = context.getRealPath("/");
What does / in the method getRealPath() represent? When should I use it?
Introduction
The ServletContext#getRealPath() is intented to convert a web content path (the path in the expanded WAR folder structure on the server's disk file system) to an absolute disk file system path.
The "/" represents the web content root. I.e. it represents the web folder as in the below project structure:
YourWebProject
|-- src
| :
|
|-- web
| |-- META-INF
| | `-- MANIFEST.MF
| |-- WEB-INF
| | `-- web.xml
| |-- index.jsp
| `-- login.jsp
:
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/some.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("/") + "index.jsp"; // Wrong!
or even
String absolutePathToIndexJSP = servletContext.getRealPath("") + "index.jsp"; // Wronger!
instead of
String absolutePathToIndexJSP = servletContext.getRealPath("/index.jsp"); // Right!
Don't ever write files in there
Also note that even though you can write new files into it using FileOutputStream, all changes (e.g. new files or edited files) will get lost whenever the WAR is redeployed; with the simple reason that all those changes are not contained in the original WAR file. So all starters who are attempting to save uploaded files in there are doing it wrong.
Moreover, getRealPath() will always return null or a completely unexpected path when the server isn't configured to expand the WAR file into the disk file system, but instead into e.g. memory as a virtual file system.
getRealPath() is unportable; you'd better never use it
Use getRealPath() carefully. There are actually no sensible real world use cases for it. Based on my 20 years of Java EE experience, there has always been another way which is much better and more portable than getRealPath().
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("/index.jsp")); // Wrong!
But instead do:
InputStream input = servletContext.getResourceAsStream("/index.jsp"); // Right!
Or if you intend to obtain a list of all available web resource paths, use ServletContext#getResourcePaths() instead.
Set<String> resourcePaths = servletContext.getResourcePaths("/");
You can obtain an individual resource as URL via ServletContext#getResource(). This will return null when the resource does not exist.
URL resource = servletContext.getResource(path);
Or if you intend to save an uploaded file, or create a temporary file, then see the below "See also" links.
See also:
getResourceAsStream() vs FileInputStream
Recommended way to save uploaded files in a servlet application
Simple ways to keep data on redeployment of Java EE 7 web application
A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.
This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).
There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?
My Method:
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String path = request.getRealPath("/WEB-INF/conf.properties");
Properties p = new Properties();
p.load(new FileInputStream(path));
String StringConexion=p.getProperty("StringConexion");
String User=p.getProperty("User");
String Password=p.getProperty("Password");
}
catch(Exception e){
String msg = "Excepcion " + e;
}
}

Save file with relative path from javabean or servlet

I need to save file from javabean or servlet, and I'm having trouble finding relative path, I tried:
(from servlet)
ServletContext servCont = this.getServletContext();
String contextPath = servCont.getRealPath(File.separator);
System.out.println("REAL PATH: "+ contextPath);
this gives me:
REAL PATH: E:\Web\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\Saloni\
and project folder is:
E:\Web\Saloni
and from bean (bean is called Salon)
String path = Salon.class.getResource("Salon.class").getPath();
and got basically the same thing
/E:/Web/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/Saloni/WEB-INF/classes/beans/Salon.class
If I just put file name into FileOutputStream file gets saved in eclipse workspace.
I read somewhere that I'm supposed to get to WEB-INF somehow but can't do that ..

Understanding MultipartFile transferTo() method in Spring MVC

I am using Spring Framework's MultipartFile to allow a user to upload a picture to a profile. I've configured DispatcherServlet in a servlet initializer class that extends AbstractAnnotationConfigDispatcherServletInitializer. In that class, I've overridden the customizeRegistration() method as follows:
#Override
protected void customizeRegistration(Dynamic registration) {
registration.setMultipartConfig(new MultipartConfigElement("/tmp/practicewellness/uploads", 2097152, 4194304, 0));
}
The MultipartFile's transferTo() method calls for a file location in the filesystem where the uploaded file will be written temporarily. Can this location be anywhere? When I used the following location in the method:
profilePicture.transferTo(new File("tmp/practicewellness/" + employee.getUsername() + ".jpg"));
... I get the following error:
Request processing failed; nested exception is org.springframework.web.multipart.MultipartException: Could not parse multipart servlet request; nested exception is java.io.IOException: The temporary upload location [C:\Users\kyle\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp2\work\Catalina\localhost\practicewellness\tmp\practicewellness\uploads] is not valid
So I can see that it's looking for this file location deep inside one of my Eclipse plugins. I don't understand why it looks there. When I look there, the "tmp" directory is not there. But regardless, is it okay for me to go into that plugin and create the directory there? Or is there a better way to smooth this out?
I've uploaded files using Spring mvc, but never used transferTo(), I just assume that your problem is due to "No existence of specified path" because there wont be a path ending with .jpg. Try it like this.
String path = "/tmp/practicewellness/";
File dirPath = new File(path);
if (!dirPath.exists()) {
dirPath.mkdirs();
}
And then execute the transferTo() code.
Also do not set the path directly like you've done. Since you're doing it in spring, so I assume you want the folder to be in your Project path not the eclipse's metadata path. So change your path to this.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness/");
It will create a folder inside your Project's Webapp folder using mkdir. If you want to save differentiate the files for each user, you can create a folder for each user by using this below path.
String path = request.getSession().getServletContext().getRealPath("/tmp/practicewellness")+"/"+employee.getUsername()+"/";

Finding path to JSF resource

I am working on a JSF website and I need some help. I have an XML file that I am trying to read from by backing bean but I don't know how to find the path to it. It is in my resources folder (resources/movies.xml). How do I do this?
If it is indeed the /resources folder of the public web content where you usually store the static web resources like CSS/JS/images, then you can use ExternalContext#getResourceAsStream() to get an InputStream of it.
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
InputStream input = externalContext.getResourceAsStream("/resources/movies.xml");
// ...
This is how I get path of folder in webapp resources folder:
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String resHomeImgPath = servletContext.getRealPath("resources/img/home");

get absolute path to apache webcontents folder from a java class file [duplicate]

This question already has answers here:
Recommended way to save uploaded files in a servlet application
(2 answers)
Closed 6 years ago.
Need to get absolute path in java class file, inside a dynamic web application...
Actually i need to get path of apache webapps folder... where the webapps are deployed
e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg
Need to get this in a java class file, not on jsp page or any view page...
any ideas?
Actually i need to get path of apache webapps folder... where the webapps are deployed
e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg
As mentioned by many other answers, you can just use ServletContext#getRealPath() to convert a relative web content path to an absolute disk file system path, so that you could use it further in File or FileInputStream. The ServletContext is in servlets available by the inherited getServletContext() method:
String relativeWebPath = "/images";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath, "imagetosave.jpg");
// ...
However, the filename "imagetosave.jpg" indicates that you're attempting to store an uploaded image by FileOutputStream. The public webcontent folder is the wrong place to store uploaded images! They will all get lost whenever the webapp get redeployed or even when the server get restarted with a cleanup. The simple reason is that the uploaded images are not contained in the to-be-deployed WAR file at all.
You should definitely look for another location outside the webapp deploy folder as a more permanent storage of uploaded images, so that it will remain intact across multiple deployments/restarts. Best way is to prepare a fixed local disk file system folder such as /var/webapp/uploads and provide this as some configuration setting. Finally just store the image in there.
String uploadsFolder = getItFromConfigurationFileSomehow(); // "/var/webapp/uploads"
File file = new File(uploadsFolder, "imagetosave.jpg");
// ...
See also:
What does servletcontext.getRealPath("/") mean and when should I use it
Where to place and how to read configuration resource files in servlet based application?
Simplest way to serve static data from outside the application server in a Java web application
If you have a javax.servlet.ServletContext you can call:
servletContext.getRealPath("/images/imagetosave.jpg")
to get the actual path of where the image is stored.
ServletContext can be accessed from a javax.servlet.http.HttpSession.
However, you might want to look into using:
servletContext.getResource("/images/imagetosave.jpg")
or
servletContext.getResourceAsStream("/images/imagetosave.jpg")
String path = MyClass.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
This should return your absolute path based on the class's file location.
Method -1 :
//step1 : import java.net.InetAddress;
InetAddress ip = InetAddress.getLocalHost();
//step2 : provide your file path
String filepath="GIVE YOUR FILE PATH AFTER WEB FOLDER something like /images/grid.png"
//step3 : grab all peices together
String a ="http://"+ip.getHostAddress()+":"+request.getLocalPort()+""+request.getServletContext().getContextPath()+filepath;
Method - 2 :
//Step : 1-get the absolute url
String path = request.getRequestURL().toString();
//Step : 2-then sub string it with the context path
path = path.substring(0, path.indexOf(request.getContextPath()));
//step : 3-provide your file path after web folder
String finalPath = "GIVE YOUR FILE PATH AFTER WEB FOLDER something like /images/grid.png"
path +=finalPath;
MY SUGGESTION
keep the file which you want to open in the default package of your source folder and open the file directly to make things simple and clear.
NOTE : this happens because it is present in the class path of your IDE if you are coding without IDE then keep it in the place of your java compiled class file or in a common folder which you can access.
HAVE FUN
I was able to get a reference to the ServletContext in a Filter. What I like best about this approach is that it occurs in the init() method which is called upon the first load the web application meaning the execution only happens once.
public class MyFilter implements Filter {
protected FilterConfig filterConfig;
public void init(FilterConfig filterConfig) {
String templatePath = filterConfig.getServletContext().getRealPath(filterConfig.getInitParameter("templatepath"));
Utilities.setTemplatePath(templatePath);
this.filterConfig = filterConfig;
}
I added the "templatepath" to the filterConfig via the web.xml:
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.myapp.servlet.MyFilter</filter-class>
<init-param>
<param-name>templatepath</param-name>
<param-value>/templates</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
You can get path in controller:
public class MyController extends MultiActionController {
private String realPath;
public ModelAndView handleRequest(HttpServletRequest request,
HttpServletResponse response) throws Exception {
realPath = getServletContext().getRealPath("/");
String classPath = realPath + "WEB-INF/classes/" + MyClass.ServletContextUtil.class.getCanonicalName().replaceAll("\\.", "/") + ".java";
// add any code
}
You could write a ServletContextListener:
public class MyServletContextListener implements ServletContextListener
{
public void contextInitializedImpl(ServletContextEvent event)
{
ServletContext servletContext = event.getServletContext();
String contextpath = servletContext.getRealPath("/");
// Provide the path to your backend software that needs it
}
//...
}
and configure it in web.xml
<listener>
<listener-class>my.package.MyServletContextListener</listener-class>
</listener>

Categories