Search code examples
xmlstrutstiles

Is my jsp valid?


I am writing a navigation tile in my struts2 application. Based on some logic in the java code I want a navigation link to display with the 'selected' class. Lets say there are 3 links and I am currently on page B. See my html example below:

<nav>
   <a href="urlA">Page A</a>
   <a class="selected" href="urlB">Page B</a>
   <a href="urlC">Page C</a>
</nav>

This HTML code will be derived from a .jsp file with a struts2 if statement to decide if the link is currently selected:

<a 
  <s:if test="%{navigation == 'pageA'}">
    class="selected"
  </s:if>
href="linkA">PageA</a>
<a 
  <s:if test="%{navigation == 'pageA'}">
    class="selected"
  </s:if>
href="linkA">PageA</a>
<a 
  <s:if test="%{navigation == 'pageA'}">
    class="selected"
  </s:if>
href="linkA">PageA</a>

My question is - Is this technically a valid jsp? It works and produces the result I want. It's definitely not valid xml but does a jsp file have to validate as xml and can anyone think of any problems I might run into by doing this.

An alternative is to write:

<s:if test="%{navigation == 'pageB'}">
  <a class="selected" href="urlB">Page B</a>
</s:if>
<s:else>
  <a href="urlB">Page B</a>
</s:else>

As an example I'm 100% sure the alternative is better but there are some situations where the original style seems less convoluted.


Solution

  • If it works, it's valid, otherwise you'd get a JSP compilation error.

    Your mistake is thinking that HTML tags and JSP tags are equivalent; they're not. You can't nest JSP tags. Nesting HTML tags isn't relevant: the JSP matters only on the server side, and it's just a template. JSP doesn't care about HTML tags, only JSP tags.

    HTML matters only on the client side, and the JSP tags are gone by then.

    Unrelated, but the first example is essentially illegible. That should all be wrapped up in a custom tag, handled in JS, or anything, to reduce that mess.