It is possible. Just create an imageservlet like this example here. To the point just obtain the image as InputStream
from DB by ResultSet#getBinaryStream()
and write it to the OutputStream
of the response as obtained by HttpServletResponse#getOutputStream()
the usual Java IO way. Don't forget to add the HTTP content type and content length headers. If you omit the content type, the browser don't know what to do with the information. If you omit the content length, it will be sent with chunked transfer encoding, which is a tad less efficient.
As to referencing the servlet in the CSS file, just specify the URL relative to the CSS file. This way you don't need to worry about the context path. Determining the relative URL isn't that hard, it works the same way as with accessing local disk filesystem paths in the command console. cd ../../foo/bar/file.ext
and so on. You've ever learnt that at schools, yes?
OK, assume that the imageservlet is located at http://example.com/context/image?id=x
and that the CSS file is located at http://example.com/context/css/globalstyle.css
(thus, the current folder is css
), then the right relative URL to the imageservlet from inside the CSS file would be:
background-image: url('../image?id=123');
The ../
goes a step backwards in the directory structure so that you go from the folder http://example.com/context/css
to http://example.com/context
. If you still have a hard time in figuring the right relative path, then let us know the absolute URL of both the servlet and the CSS file, then we'll extract the correct relative path for you.