Delmon Young
Delmon Young

Reputation: 2053

Formatting HTML in a JSP

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
<% } %>

Upvotes: 3

Views: 758

Answers (4)

Mike Braun
Mike Braun

Reputation: 3769

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

Upvotes: 0

nmenego
nmenego

Reputation: 856

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.

Upvotes: 2

SerotoninChase
SerotoninChase

Reputation: 424

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

Upvotes: 2

Vitaly
Vitaly

Reputation: 2790

  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.

Upvotes: 1

Related Questions