Q:

Code To Refresh a Java Project

I'm working with Eclipse and I just built a servlet that will take in a file name, and a file from a form and create a new file in my eclipse directory with the file name that the user provided. So if the user said firstImage for the file name and got an image from their desktop called stackoverflow.png then my servlet would create a firstImage.png file in my directory and put the contents of stackoverflow.png into it.
The problem is let's say I fill out the form and write to the file gmustudent/images/firstImage.png. If I go to that url http://localhost:8086/gmustudent/images/firstImage.png nothing will be there. But once I go to the gmustudent project in eclipse, right click it and click Refresh then firstImage.png pops up in the directory and the url now works.
This is obviously a problem b/c I don't want to have to refresh my project each time I use this form. So can anyone tell me how I can add some code to the end of my servlet that will refresh the project each time the servlet is run. Thank you.

A:

Best way is to use a servlet and stream back images. Streaming is that we have a servlet that's reading files in the server and it's sending the bytes back in the response.
public class ImageServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("image/jpeg");

        String pathToWeb = getServletContext().getRealPath(File.separator);
        File f = new File(pathToWeb + "avajavalogo.jpg");
        BufferedImage bi = ImageIO.read(f);
        OutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        out.close();

    }

}

The web.xml.
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="tomcat-demo" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

    <servlet>
        <servlet-name>ImageServlet</servlet-name>
        <servlet-class>test.ImageServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ImageServlet</servlet-name>
        <url-pattern>/image</url-pattern>
    </servlet-mapping>

</web-app>

The reason why your web url link doesn't work is because you might have not mapped the directory in web.xml file. The best practice is to use a separate servlet like above to stream back images. Refer this question as well.

