views:

54

answers:

3

I'm very new to servlets. I'd like to serve some static files, some css and some javascript. Here's what I got so far:

In web.xml:

<servlet>
    <description></description>
    <display-name>StaticServlet</display-name>
    <servlet-name>StaticServlet</servlet-name>
    <servlet-class>StaticServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>StaticServlet</servlet-name>
    <url-pattern>/static/*</url-pattern>
</servlet-mapping>

I'm assuming in the StaticServlet I'd have to work with request.getPathInfo to see what was requested, get a mime type, read the file & write it to the client.

If this is not the way to go, or is not a viable way of doing things, please suggest a better way. I'm not really sure where to place the static directory, because if I try to print new File(".") it gives me the directory of my Eclipse installation. Is there a way to find out the project's directory?

+2  A: 

You don't need to serve static content via a servlet, the servlet container can serve this directly from your war file.

The only time you would need a servlet to do this is if you would want to use the original item as a template which you would want to manipulate programmatically before returning it to the client browser.

crowne
Where would the war file be found? I'm currently running the project from eclipse, and I can't find it.
Geo
Generally if you're running the project straight from Eclipse an actual .war file isn't created, but that doesn't matter, your servlet container should still serve any files under your WebContent directory. This assumes that you don't had a servlet mapping overriding the path to the file. If you remove all the servlets from your web.xml and put a test.html directly in the WebContent dir and restart the server you should be able to see it by navigating to http://localhost:8080/{web-root}/test.html
Mike Deck
Thanks Mike! That did the trick!
Geo
+2  A: 

If you want to serve static files, you can just include them in the WAR. Whatever isn't handled by a Servlet will look in the root directory of the war by default.

Edwin Buck
+1  A: 

You can indeed just let the servletcontainer's DefaultServlet handle this.

To answer your actual question, even though it's just for learning purposes, you can use ServletContext#getRealPath() to convert a relative web path to an absolute local disk file system.

String relativeWebPath = "/static/file.ext";
String absoluteFilePath = getServletContext().getRealPath(relativeWebPath);
File file = new File (absoluteFilePath);
// ...
BalusC