Difference between jsp expression tags <% and <%=

rocklandcitizen picture rocklandcitizen · Apr 29, 2013 · Viewed 46.4k times · Source

I more or less know the difference between <%! and <%, but I can't seem to find the difference between <%= and <%. I'm trying to avoid a null value error by introducing some logic into my expression that currently uses <%= ... %>. I get an error unless I replace the tags with <%...%>. However after my build I get a jsp error instead of the servlet error. I can't really paste my original code in here but the code inside <%= ... %> essentially retrieves a nested array object (more like array object within another array object) passed as a servlet argument in a Struts 1 project. I just want to add a try...catch statement in case the object's property isn't instantiated yet.

<%=((package.package.package.ClassName)session.getAttribute("attrName")).getObjectList()[0].getSecondObject.length%>; 

Is this a jsp issue, or is it a Struts 1 issue? And again, what is the difference between the 2 tags?

Answer

Dan Dinu picture Dan Dinu · Apr 29, 2013

Between <%...%>you can write any logic that you want in java.

Using <%=...%> will output the result of the expression between the brackets to the screen. So instead of writing for example

<% System.out.println("Hello World") %> 

you can simply write

<%= "Hello world" %> 

Basically, what <%= %> does is to call the toString() method of the expression that is being evaluated.

If you need to add null check logic as you said you need you can use

 <%..%>

Here's a link you can refer to:

http://www.easywayserver.com/jsp/JSP-example.htm http://www.tutorialspoint.com/jsp/jsp_syntax.htm