开发者

Curly brackets in JSP code

开发者 https://www.devze.com 2022-12-14 06:58 出处:网络
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:

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?


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.


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.


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".


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消