I have a question on code reuse in JSP. I have a JSP page example.jsp that issues a call to a database and gets the results. I have a java class HelperClass.java that accepts a record and prints out the different fields
response.getWriter().println
Now my JSP page has HTML as well and the problem is the content printed out by the HelperClass appears before the content in the JSP page. E.g.
<body>
This is the first line <br/>
HelperClass.printdata("second line");
</body>
output is
secondline This is the first line
Is this a known issue. What is the best way to design an HelperClass for a JSP page that prints content out to the page. Any pointers would be greatly appreciated.
Just do not use a “HelperClass to print data”. This makes no sense. There you have EL for.
That’s all. Use a servlet to control, preprocess and postprocess requests. Use taglibs (e.g. JSTL) and EL to access and display backend data.
Here’s a basic kickoff example of a Servlet which preprocesses the request before display in JSP:
Here, the
Personis just a Javabean class which represents a real world entity.The
PersonDAO#list()method just returns aListofPersonobjects from the DB:Map the servlet in
web.xmlon anurl-patternof/persons. The JSP is hidden in/WEB-INFso that nobody can access it directly without requesting the servlet first (else one would get an empty table).Now, here’s how
persons.jsplook like, it uses JSTL (just drop jstl-1.2.jar in/WEB-INF/lib)c:forEachto iterate over aListand it uses EL to access the backend data and bean properties. The servlet has put theList<Person>as request attribute with namepersonsso that it’s available by${persons}in EL. Each iteration inc:forEachgives aPersoninstance back, so that you can display their proeprties with EL.Call it by http://example.com/contextname/persons. That’s all. No need for a “HelperClass to print data” 😉 To learn more about JSTL, check Java EE tutorial part II chapter 7 and to learn more about EL, check Java EE tutorial part II chapter 5. To learn more about stuff behind PersonDAO, check this article.