Tuesday, May 7, 2013

quick ref for future self: old school servet and jsp pairing

The other week I was converting some servlets that had a lot of embedded HTML to Servlet/JSP pairs (a preferred mutant MVC variant I like called "Model 2 Plus".) So a few notes to when I have to do that again (these were from a sticky I left to make a blog entry about, hence less haphazard nature of the examples.)

In the servlet, I wanted to put some information (a ContactList instance named contacts) into the request for later retrieval:

req.setAttribute("contacts", contacts);
RequestDispatcher dispatcher = 


Then telling the JSP about the object:
 <%@ page import="com.mycompany.util.ContactList" %>
and later to loop over it:
ContactsList contacts = (ContactsList)request.getAttribute("contacts");
for (int i=0;i<contacts.size();i++) {
Contact contact = contacts.get(i);
<TD><%= contact.getID() %></TD>
<TD><%= contact.getName() %></TD>
<% } %>

I guess I felt more comfortable with the "do flaps" ( <% %> that execute code) and the "show flaps" ( <%=  %> that show a value) then using one of the taglibs-- yeah, having code embedded in HTML is a bit rough and less "pure", but A. I actually LIKE that my code looks/smells different than my looping markup, B. I kind of dislike having two ways of saying something, and C. I prefer to have fewer moving parts... I really liked how old school JSPs got precompiled directly into servlets, and how you could even crack open the intermediate generated servlets and see how things got translated.

No comments:

Post a Comment