File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Avoiding java code generate HTML pages Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Avoiding java code generate HTML pages" Watch "Avoiding java code generate HTML pages" New topic

Avoiding java code generate HTML pages

deep lal

Joined: Sep 08, 2003
Posts: 1
I have read that it is a good practise to avoid java code generating HTML pages. I am not sure how to implement this. In my case, i need to fetch data from the database and display it. So can you guys suggest me a way to avoid this trap.
Thanks in advance.
Andres Gonzalez
Ranch Hand

Joined: Nov 27, 2001
Posts: 1561
Originally posted by deep lal:
I have read that it is a good practise to avoid java code generating HTML pages. I am not sure how to implement this. In my case, i need to fetch data from the database and display it. So can you guys suggest me a way to avoid this trap.
Thanks in advance.

hmm.. the way to generate HTML in servlets is using a PrintWriter object.
PrintWriter pw = response.getWriter()
I'd say it is not recommended because:
1o) that's why JSP are for (and JSF in a future)
2o) Servlets are used for business logic, not for presentation.
3o) it is a pain to maintain HTML inside a servlet.
So, you need some sort of mechanism in which you can fetch data from your database and pass it to the JSP, accessing it and displaying it in a standard way.
How about a JavaBean ?

I'm not going to be a Rock Star. I'm going to be a LEGEND! --Freddie Mercury
Lionel Port

Joined: Sep 14, 2002
Posts: 19
Use your servlet to do all the work and a jsp to do the presentation.
So the servlet will request the data from the database or DAO and store it in a collection object. Place the Collection in the request object, using request.setAttribute() and then forward to the jsp page using the RequestDispatcher. The jsp page will then need to retrieve the collection from the request object and display the contents.
It seems like a bit of extra work at first, but it makes it a lot easier to modify individual aspects of your application.
A useful framework is the jakarta struts framework from Apache. This framework makes it easier to seperate the servlet classes that perform the business logic from the jsps the do presentation.
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
Another way to avoid hardcoded HTML in your servlets is using HTML templates which are read in by the servlet and placeholders filled in with actual data.
A variation on this which I've used successfully takes this one step further and has the servlet generate XML which is then combined with XSL which is stored on the filesystem (for easy modification of the user interface) and the result piped to the browser.

karl san

Joined: Aug 27, 2003
Posts: 4
Would the method suggested by you guys improve the performance of the web application in any way and why?
William Brogden
Author and all-around good cowpoke

Joined: Mar 22, 2000
Posts: 13037
XML - XSLT will be significantly slower than lots of prints from Java due to many extra steps.
Seems to me the choice between servlets and JSP for generating HTML depends on how much is calculated on the fly. I use servlets with println for test question and survey question generation because most of the content is generated on the fly. If most of your content is static, then JSP is indicated.
For ultimate speed you need to avoid the inherent character by character conversion that a writer does - see the book by Bulka - Java Performance and Scalability.
However - there is no reason to pursue output speedups if your application has some intrinsically slow step such as database searches.
Martin Lovell

Joined: Mar 10, 2003
Posts: 5
My coworkers and I have found it very helpful to do HTML only in JSPs, and Java code only in Java. We have been using JSTL in JSPs to access beans created in Servlets (or objects working in conjunction with servlets).
All requests are dispatched through some objects which process the request and provide display data for the JSPs via request or session attributes. The JSPs job is to format the data and display it.
JSPs are included after java using:
RequestDispatcher dispatcher = request.getRequestDispatcher(jspPage);
dispatcher.include(request, response);
Generally, jsps are not requested directly...actually never in our case.
We configure which Java code to execute and which JSP(s) to include using XML.
So, that's no <% in the jsp and no println() in the java. JSPs do iterate and may contain some JSTL scripting. Using only JSTL keeps it to a optimal level. (No jstl sql. Sql is only for Java.)
Some of my coworkers don't know any Java, but can help immensely on the projects and are much better at asthetics than I am. Once they do a few pages with JSTL, they are on their way! We are able to work together efficiently and happily. It's a lot of fun!
I am not sure if it provides the best raw performance per page, but it definitely makes thing more scalable as far as managing a project goes. It makes the presentation layer very flexible and independent, makes it easy to adjust the Java implementation when performance bottlenecks are found, and makes it much easier to test the Java using JUnit. (It could be argued that using Java in any way will never provide the best raw performance, but I would never argue that .)
(I think this whole concept is also one of the goals of Struts...and they probably explain it much better than I can. Sun's documentation on the dispatcher model, and other models, for web applications is helpful too.)
PS: Well...maybe some resp.getOutputStream().write() in the java when generating non-html, such as PDF. (Cocoon might help, maybe?)
DC Dalton
Ranch Hand

Joined: May 28, 2001
Posts: 287
I have to go with Bill on this one, if you are doing a lot of manipulation to the view, based on the db returns (or anything else for that fact) build a class thats handles this (or several) & then all the servlet needs to do is pass any data to the classes & then print the final output... More and More these days an MVC design is required because plain old static pages just dont cut it any more in this database-driven, dynamic web we are into.
Im sorry I just dont go for the JSP thing in this instance UNLESS the layout is (as Bill mentioned) static with little or no changes from page to page.
I do an html output class (or two), as mentioned above on all of the sites I build & a few internal apps. Ive NEVER run into a speed issue doing it this way, as a matter of fact they tend to SCREAM!
Jeroen Wenting
Ranch Hand

Joined: Oct 12, 2000
Posts: 5093
I did some timing on the application before deciding to implement it and it wasn't all that much slower.
I DID optimise the XSL part of it by caching each precompiled XSL file.
XSL parsing took a few milliseconds for each request, which was little compared with the database access times.
The main reason I chose this way was flexibility. While the initial release was planned to be for webbrowsers only, the customer was planning on a possible interface for PDAs and EDI style applications and output to spreadsheets and maybe PDF at a later date.
Having the output generated from XSL would make that a lot easier to accomplish (just put in different XSL based on some flag indicating the desired output format).
Martin Lovell

Joined: Mar 10, 2003
Posts: 5
I don't totally understand why JSP=static. I get why html=static, but can't a JSP be just as dynamic as a println()?
I think it's fine to do all/some println() if that's what works best for a particular team.
In our case the MVC is very strict (as it can be with println() too). It's helpful for us to keep all of the V of MVC in the JSPs so that we are sure not to mix our V with the M or C. Our M is in java, and the C is in an XML file (and the java classes that use it).
Not to push JSTL, but it's possible to iterate with JSTL using <c:forEach ...>.
And, it's possible to branch based on what layout you desire with <c:choose ...> and <c:import ...>.
So... something like this worked for us when we wanted to provide a questionnaire using the model and have the JSP act as the view:
<c:forEach var="quest" items="${questionnaire.questions}" >
<c:when test="${quest.type=='radio'}">
<c:import url="qradio.jsp"/>
<c:when test="${quest.type=='checkbox'}">
<c:import url="qcheckbox.jsp"/>
<c:when test="${quest.type=='text'}">
<c:import url="qtext.jsp"/>
(The qradio.jsp, for example, outputs the radio questions by writing the question text and iterating through the possible answers using c:forEach.)
I feel like it's important to stress that I don't think it's wrong to use println() for HTML output, it just turned out to be very helpful for us not to do it that way. The techniques I am attempting to explain really worked very well for us on some projects.
steve souza
Ranch Hand

Joined: Jun 26, 2002
Posts: 862
I have just released the FormattedDataSet API that is the easiest way I have seen to generate dynamic XML, and HTML (listboxes, tables, drop down list boxes, and custom html).
It takes as an input any type of tabular data (SQL, a ResultSet, Object[][]) and outputs text. Formatting is defined in simple templates that can be reused independent of data. One signature for the formattedDataSet follows:

Best of all the FormattedDataSet is open source. For a brief explanation, examples and a live demo go to - a fast, free open source performance tuning api.
JavaRanch Performance FAQ
Will Sillmon Jr.

Joined: Aug 25, 2005
Posts: 14
I understand the argument that this situation creates but which do you feel is better when dealing with style sheets... I have not attempted to use CSS on the application that I am building but a "heads-up" on this situation would be greatly appreciated...

I agree. Here's the link:
subject: Avoiding java code generate HTML pages
It's not a secret anymore!