How can I randomly display blocks of text in a .jsp file?
February 25, 2007 1:44 PM   Subscribe

How do I output random blocks of text in a JSP include? I am not in any way a java/jsp programmer.

I have an application that uses JSP includes to display advertising (Google AdSense) to visitors. Currently, the ads are fairly static in size and content...I'd like to mix it up a little, have different sizes displayed, and occasionally have no ads at all.

Is there a way to do this just inside the .jsp file? Ideally I'd like to be able to specify what percentage of displays each will get (roughly...doesn't need to be perfect), like one ad block showing up 10% of the time and another 90%. That's not a requirement for this though.

Thanks!
posted by Kickstart70 to Computers & Internet (8 answers total)
 
Best answer: You can do something like this:

<%
double d = Math.random();

if(d < 0.2){%>text block one<%}
else if(d < 0.4){%>text block 2%<%}
else {%>text block three<%}%>
posted by delmoi at 2:02 PM on February 25, 2007


Yes, that posted correctly!
posted by delmoi at 2:02 PM on February 25, 2007


(Oh wait, there is an extra "%" on the second line.)

Anyway, the numbers 0.2 and 0.4 control how often each block of text will be printed. The first block will be printed 20% of the time, the second block also 20% of the time (it will only print if d > .2 and d < 0.2) and the last block will print 60% of the time.br>
Also, that's just off the top of my head, so I don't know if the syntax is perfect.
posted by delmoi at 2:06 PM on February 25, 2007


Here's one that will work regardless of the number of text blocks you have:

< %br> ArrayList l = new ArrayList();
l.add("First string");
l.add("Second string");
l.add("Add as many of these as you want");

Response.getWriter().print(l.get(Math.random()*l.size()));
posted by comwiz at 3:04 PM on February 25, 2007


Can't you just do something like:

<%= "This is some text." %>
posted by Civil_Disobedient at 3:44 PM on February 25, 2007


Sorry, missed the "random" part of the question.
posted by Civil_Disobedient at 3:45 PM on February 25, 2007


You're attempting to change how Google AdSense ads display on your page? I'd say that was against their terms of service and therefore a Bad Idea.
posted by AmbroseChapel at 4:09 PM on February 25, 2007


Response by poster: I'm not trying to change the way they display on the page...I just want different size ads to display, and occasionally some self-advertising, which isn't against the rules. Ie. sometimes I want a 336x280 ad, and sometimes I want a 300x250 ad.
posted by Kickstart70 at 7:58 PM on February 25, 2007


« Older Atmel ATmega not programming over DAPA   |   Do compact florescents change maximum wattage... Newer »
This thread is closed to new comments.