3

I'm pretty new to Java and I apologize in advance if I'm wording this incorrectly. I've got a small code snippet that has multiple opening and closing delimiters because I've got some HTML mixed with JSP. Without the HTML this can be done in just a few lines of code but I need the HTML to render and it leads to almost double the lines of code. I'm wondering if there is a better way to do this as opposed to having so many opening and closing delimiters. I know I can use a templating library but I'm trying to stay away from that and would like if at all possible to do this inside a JSP (not a separate class). Thanks for the help!

<%
try {
  List<Page> children = properties.getPath("getChild", "");    
%>    
  <ul>       
<%      
  for (Page children : e) {
    if (children != null) {         
%>
   <li><a href="#">Show a link</a></li>
<%
   }//end if statement
  }//end for loop
%>
  <li><a href="<%= currentPage.getPath() %>" href="<%= currentPage.getPath() %>">Another link goes here</a></li>    
  </ul>
<% 
} catch (NullPointerException e){
%>
//show some content here
<% } %>
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Delmon Young
  • 2,013
  • 5
  • 39
  • 51

4 Answers4

2

Use JSTL instead of all that Java code you have in your JSP. You can read about JSTL here - http://docs.oracle.com/javaee/5/tutorial/doc/bnakc.html

SerotoninChase
  • 424
  • 11
  • 28
2

I think that this kind of problem can really be solved by using templating libraries or the included view convention for a framework.

These libraries were created to solve these kinds of problems and to organize the view as a whole. It will not only clear up the clutter in your view, it will also adhere to the MVC pattern.

In struts, for example, we will do something like this:

<s:textfield name="myParameter" /> 

and this:

<html:link page="/linkoutput.jsp" paramId="id" paramName="name"/>

For more reasons why you should be using templating or frameworks visit this question. As what Dave Newton said:

Attempting to do it all in jsp is precisely the wrong approach.

Hope this clears it up.

Community
  • 1
  • 1
nmenego
  • 846
  • 3
  • 17
  • 36
1
  1. Never catch NPE just to catch NPE.

  2. Consider using JSTL http://jstl.java.net/getStarted.html It provides plenty of tags for iteration and so on.

Vitaly
  • 2,760
  • 2
  • 19
  • 26
0

You'd be much better of using something like JSF. Just as JSP, this is also included in Java EE.

Mike Braun
  • 3,729
  • 17
  • 15