Issue
I have the following doubt. I have a TomCat server instance and I need to expose some JPG images on Internet. In the past I always accomplished this type of task installing an Apache server and then putting my images into an htdocs subfolder. With Tomcat server it seems to be more complicated.
I found this post here on SO: How to config Tomcat to serve images from an external folder outside webapps?
But I am not sure about what I have to do so I want to ask you some question to clarify my doubts.
From what I know a JavaEE application is something like that, deployed, added functionality to the application server\servlet container (differently from Apache where a PHP application is only something that is runned).
So, reasoning on the example of the posted link it seems to me that:
I have to create a brand new JavaEE application that will be deployed into my Tomcat server.
This application will contain no classes because there is no logic that have to be implemented.
This application have only to contain the web.xml configuration file that will configure a single servlet that map to the directory where my images are contained, this one:
images com.example.images.ImageServlet images /images/*
My doubt is: is the previous example incomplete? Have I to write the ImageServlet class to do this work? What can I do?
Solution
HttpServlet will works perfect for your needs. You can define more servlets if needed.
use:
youraddress.xxx/images/filename.png
this is important @WebServlet("/images/*")
It will automatically leads to folder defined in PATH and retrieve the image based on the name.
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@WebServlet("/images/*")
public class ImageServlet extends HttpServlet {
public static final String PATH = "C:/"
/*
linux
public static final String PATH = "/home/images/"
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String filename = request.getPathInfo().substring(1);
File file = new File(PATH,filename);
response.setHeader("Content-Type", getServletContext().getMimeType(filename));
response.setHeader("Content-Length",String.valueOf(file.length()));
response.setHeader("Content-Disposition","inline; filename=\""+filename +"\"");
Files.copy(file.toPath(),response.getOutputStream());
}
}
Answered By - Milkmaid