Sunday, November 7, 2010

Darn it JSPs!

I learned something really neat... well not so neat about JSPs and how they get compiled.  Say you have something like this:

<% if (request.isUserInRole("user")) { %>

<p>Hey, let's do something with this user role business</p>


<% } %>
<% else if( request.isUserInRole( "guest" ) ) { %>

<p>Let's do something with the guest role </p>

<% } %>

You would think it would work. There's an if statement, then an else if statement... Except, when the JSP compiles, it looks like so:


if (request.isUserInRole("user")) {
      out.write("\n");
      out.write("\n");
      out.write("
<p>Hey, let's do something with this user role business</p>\n");
      out.write("\n");
      out.write("\n");
 }
      out.write("\n");
      out.write("\n"); 
else if( request.isUserInRole( "guest" ) ) {
      out.write("\n");
      out.write("\n");
      out.write("<p>Let's do something with the guest role</p>\n");
}
 Because of those newlines, the if/else if doesn't look right and it throws errors when you run. The only way I was able to get it to work was to put the close brace and the else if in the same statement:

<% } else if( request.isUserInRole( "guest" ) ) { %>

Once that was done, the thing compiled properly and worked fine. A neat little thing to keep in mind when throwing scriptlets in the JSP.