Joe
Joe

Reputation: 7919

Why can't I use an if-else statement inside a scriptlet expression, whereas a ternary operator works fine

We know that the scripting variable state is true.

Why is this scriptlet expression wrong? How would it be the code into _jspService method after translation?

<%=
if(state) {
  "yes";
} else {
  "no";
}
%>

And this is correct

<%= state ? "yes" : "no" %>

because returns a value and it would appear into _jspService as

public void _jspService(...){
   out.println("yes");
}

Upvotes: 1

Views: 6870

Answers (2)

Joe
Joe

Reputation: 7919

Roel de Nijs said:

The JSP expressions <%= ... %> are placed inside a out.print()

So <%= state ? "yes" : "no" %> is converted into out.println(state ? "yes" : "no");, which compiles without any problem. But with the if-statement the resulting code won't compile. That's also why semicolon in a jsp expression is not allowed.

Upvotes: 0

Ian McLaird
Ian McLaird

Reputation: 5585

The if / else version is syntactically different from the ternary operator. It doesn't "return" anything.

In order to make something like that work you'd need to do this

<%
    if (state) {
        out.print("yes");
    } else {
        out.print("no");
    }
%>

If statements need something to do. They can't just have a string as their only statements. The ternary operator chooses and returns the selected value.

Scriptlet blocks with the <%= %> syntax have to be a single expression that produces a value to output. Basically they have to evaluate to something. Even if the if statement were syntactically valid, it still wouldn't return a value.

Upvotes: 2

Related Questions