Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


Question: How can I use a JSP to decide what HTML code to print?

Answer:

When using JavaServer Pages, you can use your usual Java if-then statements to determine when to print HTML code, and when not to. In this example, I'll show you how to print one set of HTML tags if the user's browser is Netscape, and another set of HTML if the browser is not Netscape.

Using the JSP 0.92 specification, your JSP code might look something like this:

<%@ import="java.io.*,java.util.*,java.lang.Object,java.text.Format" %>

<%
// using Java, determine if the browser is Netscape or MSIE
boolean isNetscape = false;

String userAgent = request.getHeader("User-Agent");
if ( userAgent.toLowerCase().indexOf("msie") ==-1   &&  
   userAgent.toLowerCase().indexOf("spoofer")==-1 )
{
   isNetscape = true;	// browser is Netscape
} 
else
{
   isNetscape = false;	// browser is NOT Netscape
}
%>
    
<% if ( isNetscape ) { %>

   <!-- Here's some HTML embedded in a Java decision -->
   <H1>Welcome Netscape User!</H1>

<% } else { %>

   <!-- Here's the HTML printed by Java's 'else' clause -->
   <H1>Welcome NON-Netscape User!</H1>

<% } %>

Notice that you don't need all of the <% and %> tags that I use. Many times I just add these tags to make the JSP/HTML code easier to read.

As a last note, I tested this code on a JSP 0.92, but it should work equally well on a JSP 1.0 (and beyond) server.


 

404 - page not found

return to alvinalexander.com