tags:

views:

169

answers:

5

I have a JSP page I am working on and I am confused by some of the formatting/coding.

There are sections where it's obvious what's going on:

<%
        if (.....)
        {
%>
      <input type=hidden name="blahblah" value="moreblah">
<%
        }
%>

But now I see sections where I have no idea how or why it works/compiles:

<%
    {
     // do stuff here
     String sClass = "blahblah"
     if ( sClass.equals("") )
     {
      sClass = "blah";
     }
    }
%>

There's no if or while or for or anything at the start of those curly brackets. Why does that compile and produce a good jsp page?

+8  A: 

They're scope limiting, as per normal Java behavior, as in this other/similar question.

In essence they define a block, and sClass is only available in that particular block.

Mark E
Is this a good thing to be doing? I am trying to bring this code up to date and had never seen this before.
Steven Wright
Well that depends -- if you want to ensure that `sClass` is only used within the scope of the braces then it can be helpful, but it's certainly not required.
Mark E
+2  A: 

i believe like other languages curly braces are just a way of telling the compiler/code interpreter that you have sectioned off multiple lines into a particular scope. Scope meaning the area that the current running code has access to variables, functions, and other resources declared inside the current "scope".

jon
+3  A: 

I would recommend that you NOT learn how to write scriptlets in JSPs. They're ugly at best and unmaintainable at worst.

A better strategy is to learn JSTL and keep scriptlets out of your pages. I think Hans Bergsten's JSP book from O'Reilly is the best there is. Read that, and don't write scriptlet code. You'll be glad you did.

duffymo
+1  A: 

Don't worry about that. Writing raw Java code in a JSP file is considered bad practice. Replace that (sorry for the word) nasty stuff by JSTL and EL. The core taglib supports pretty much of all what you need.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> 

<c:if test="${ ... }">
    <input type=hidden name="blahblah" value="moreblah">
</c:if>

<c:set var="sClass" value="blahblah" />
<c:set var="sClass" value="${sClass == '' ? 'blah' : sClass}" />

Although the last example doesn't make any sense, but this should give you the picture.

BalusC
A: 

You don't need to put any keywords like if, for, while etc before beginning of any code block. Whatever variables you define in the block will be visible only in that block.

fastcodejava