开发者

Is it possible to call a servlet from css?

I'm trying to move all the images stored in web application folder to a database. An开发者_运维百科d calling them with a servlet. Is it possible to call a servlet from my css ?? or is there any way to call a remotely stored image file from css??

I tried to call a servlet method from CSS.But couldn't succeed. Is it possible to call a method like this?

background-image: url(servlet/com.abc.servlet.GetImage?name=home&GetImage('abc','123'));


Yes. As long as the images have urls, you can use it in your css.

For example:

background-image:url('/getimage.ashx?id=3');

You can even go a step further an reroute their urls - you can even use the same urls you have today, but having your server handle the request and loading files from the database.

Another tip: make sure you set the right headers. You want to use the correct content type, and probably want the images cached properly on the client side.


Yes. A CSS rule that specifies an image can contain any kind of URL that the browser can parse and fetch:

body { 
 background-image:
 url(http://www.domain.com/servlets/my_servlet.jsp?argument=value)
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜