Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JSP / Servler Random Photo 1

Status
Not open for further replies.

tommyc7

Programmer
Feb 3, 2007
33
US
What I'm trying to do is probably very simple, but for some reason I'm drawing a complete blank on how to do it.

I am working on a web site that uses JSP / Servlets using Tomcat.

I have an image folder and let's say there are 5 images named photo1, photo2 ... photo5.

All I want to do is randomly display a different photo each time the page draws.

In Java, I understand how to use the File class and how to make things Random. I am pretty new at JSP, so I'm not sure if there's something there I can use.

The part that I'm stuck on, is how to structure the directory path so the File object can read the image directory inside the web server. (I've tried using a URI object, but have had no luck.)

Or, I don't mind dropping the whole File idea, if there's a better solution.


Thanks!

 
Hi

tommyc7 said:
All I want to do is randomly display a different photo each time the page draws.
You can just generate the image name in the JSP file :
Code:
[highlight bisque]   anything.jsp   [/highlight]
<html>
<body>
<% out.println("<img src=\"/path/to/image/photo"+((int) (Math.random()*5+1))+".jpg\">"); %>
</body>
</html>
Or generate it in the servlet and use it in the JSP :
Code:
[highlight bisque]   Anything.java   [/highlight]
[gray]//...[/gray]
request.setAttribute("imgNr",new Integer((int) (Math.random()*5+1)));
[gray]//...[/gray]



[highlight bisque]   anything.jsp   [/highlight]
<html>
<body>
<% out.println("<img src=\"/path/to/image/photo"+request.getAttribute("imgNr")+".jpg\">"); %>
</body>
</html>


[highlight bisque]   anything.jsp ( alternative using Struts Bean )  [/highlight]
<%@ taglib uri="struts-bean" prefix="bean" %>
<html>
<body>
<img src="/path/to/image/photo<bean:write name="imgNr"/>.jpg">
</body>
</html>


[highlight bisque]   anything.jsp ( alternative using Expression Language )  [/highlight]
<%@ page isELIgnored="false" %>
<html>
<body>
<img src="/path/to/image/photo${imgNr}.jpg">
</body>
</html>

Feherke.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top