Reputation: 343
I'm not sure if I can do this, but I'm trying to print a string with Expression Language only (no JSTL). The string is going to often-times be null, and I want an empty string printed to HTML instead of the word "null". This is what I'm trying (without success):
<%
myString = "";
myString = someMethodThatMayReturnNull(); // returns string or null
%>
<b>${myString}</b><br />
<b>${ (empty myString) ? "myString-is-empty" : "myString-is-NOT-empty" }</b><br />
The reason I don't want to use JSTL is because I'm trying to make the minimum changes to a fairly good sized system.
Upvotes: 0
Views: 2698
Reputation: 5563
EL print the variables only when its available in pageContext scope. Here the variables are in page scope. If the variable is in some other scope, you have to specify the scope while using it. Do something like this to print the value of 'mystring' variable.
<%
myString = "stackoverflow";
pageContext.setAttribute("myString",myString);
%>
${myString}
It will print the value of myString, if myString is 'null' it will print empty string(nothing will be printed).
suppose if put the variable in request scope, you have to use "requestScope"
<%
myString = "stackoverflow";
request.setAttribute("myString",myString);
%>
${requestScope.myString}
Upvotes: 1
Reputation: 583
why do u want to check String null in jsp code?
If you do not want to use scriptlet then you can check string null in mentod itself and return empty string in case of null.
myString = someMethodThatMayReturnNull(); // it should never return null.
And method is from other code then you can wrap this with your java code.
Upvotes: 0
Reputation: 1109875
Scriptlets and EL doesn't share the same variable scope. You need to prepare EL variables as attributes of page, request, session or application scope. As you have right now, it is always empty.
<%
myString = "";
myString = someMethodThatMayReturnNull(); // returns string or null
request.setAttribute("myString", myString); // It's now available by ${myString}
%>
Note that you normally do that Scriptlet part inside a Servlet. Also note that EL is null-safe, so anything which is truly null
, i.e. if (object == null)
passes, then it simply won't be printed at all.
Or, if your concrete problem is that it prints literally ${myString}
and so on in the browser, while it worked with JSTL <c:out>
, then it means that you aren't using a JSP 2.0 compatible servletcontainer or that your webapp's web.xml
is not declared conform at least Servlet 2.4, or that you have isElIgnored
set to true
. Verify and fix it all.
Upvotes: 1