2

I've developed an application using Tomcat, Mysql and Servlets.

One of the options the user can choose is to see on the web browser the information of one of the tables of a database. When the user chooses this option a servlet is used. This servlet opens a connection to the data base and iterates over the rows, showing the information. This works without problems.

In order to show this information in the browser I'm using a lot of "out.println()" lines.

Although the functionality is implemented I'd like to know if there is any other way of showing this information on the browser. If anyone could name a method or provide me with links to examples it would be great.

thanks a lot.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
carlos
  • 21
  • 1

4 Answers4

3

Create a Javabean class which represents each item (row) of the table. Create a DAO class which returns a list of those items using JDBC. Then in the servlet, just put the list of items in the request scope using HttpServletRequest#setAttribute(), forward the request to a JSP file using RequestDispatcher#forward() and iterate over the list of items using JSTL (just drop jstl-1.2.jar in /WEB-INF/lib) c:forEach tag.

Basic kickoff example:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    List<Item> items = itemDAO.list();
    request.setAttribute("items", items); // It's now available as ${items} in EL.
    request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);
}

where result.jsp look like this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

...

<table>
    <c:forEach items="${items}" var="item">
        <tr>
            <td>${item.someProperty}</td>
            <td>${item.anotherProperty}</td>
        </tr>
    </c:forEach>
</table>

For more hints and examples you may find this article an useful starting point.

It's a Good Thing that you asked this. Putting presentation logic in a Servlet class is a bad practice. Any of those out.println() statements inside a Servlet class needs to be eliminated. It belongs in a JSP file.

To go some steps further, you can also use a MVC framework so that you basically end up with only a Javabean class and a JSP file (i.e. the role of the servlet have been taken over by the MVC framework).

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Hi, I've been able to remove all the out.println's from my servlets following your advice. However I'm not able to print the content of a database in the html page I've created a Javabean class. This class has 3 atributes (title, author, album). I'm able to store each row of the database's table in a List element (I've checked it using:items.get(i).getTitle(),items.get(i).getAuthor() and items.get(i).getAlbum() for each row). Up to this point everything looks ok. Then I've put the list in the request and forward the request to a jsp file. – dedalo Mar 04 '10 at 01:01
  • In the jsp file everything works ok. The problem is that does not print the information sent in the request. It does print the table's header (TitleAuthorAlbum), but it looks like the code between the does not have any effect. The jstl-1.2.jar file is placed as you indicated. Am I missing anything? Thanks – dedalo Mar 04 '10 at 01:07
  • Which Tomcat version are you using? Which Servlet version is declared in web.xml? How does the generated page source look like? (rightclick page in webbrowser and choose "view source"). You shouldn't see any Java/JSP tags, but only pure HTML. Also try putting the `${items}` "plain vanilla" in JSP to see if it prints the same value as `items.toString()` in real Java code. By the way, as everything in Java, taglibs are also case sensitive, it should be ``. – BalusC Mar 04 '10 at 01:13
  • The installation directory says it is Tomcat 6.0. In the web.xml it says: When I use ${items} in the jsp file it is printed in the brower the same information that provides items.toString(). Thanks – dedalo Mar 04 '10 at 01:21
  • OK, everything looks fine. JSTL just did not her work :) How about the page source? Did you by the way declare the taglib in top of JSP as per its documentation? http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/c/tld-summary.html I see that I didn't mention it in my answer. I'll update my answer soon (edit: done). – BalusC Mar 04 '10 at 01:25
  • The page source looks ok, no java/jsp tags. I do see there the tag, is it ok? When I add the declaration at the beggining of the jsp file (in the first line) I get a big error message : java.lang.ClassNotFoundException: javax.servlet.jsp.tagext.TagLibraryValidator.... – dedalo Mar 04 '10 at 01:37
  • You shouldn't see the JSTL tags as well. Wrt the exception: There's a collision in the classpath. Do you have anything else in `/WEB-INF/lib`? Didn't you accidently or unawarely copypasted appserver-specific libraries in there like `servlet-api.jar`, `jsp-api.jar` and so on? You need to get rid of them in `/WEB-INF/lib` and untouch/keep them there where they belongs (in the appserver's library). – BalusC Mar 04 '10 at 02:41
  • No, in WEB-INF/lib there's only one file: the jstl-1.2.jar, downloaded from the link in your post. Do I need to tell Tomcat somehow that I have that file in the 'lib' folder? Thanks – carlos Mar 04 '10 at 07:40
  • No, you don't need to. The `WEB-INF/lib` is already "automatically" taken in the runtime classpath. At least this exception would mean that there's another (older) version of the JSP API JAR file somewhere in the classpath which collided with the one default supplied by Tomcat 6. I can't do much more than suggesting that you need to cleanup the runtime classpath. This covers under each `JRE/lib/*`, `Tomcat/lib`, `Webapp/WEB-INF/lib`. – BalusC Mar 04 '10 at 11:30
  • Ok, one of the classes was duplicated, now it is ok. Thanks! – dedalo Mar 04 '10 at 22:28
  • Could someone help me with this? http://stackoverflow.com/questions/2383309/servlet-jsp-javabeans-and-html-form – dedalo Mar 04 '10 at 23:59
0

Try using Java Server Pages along with the JavaServer Pages Standard Tag Library. JSP's with JSTL is a way of using html like syntax (xml) to create dynamic Java web pages. JSP's are converted to Servlets at runtime.

kgrad
  • 4,672
  • 7
  • 36
  • 57
0

Just choose one web framework among many

Boris Pavlović
  • 63,078
  • 28
  • 122
  • 148
0

There are many different ways to achieve the same ( thanks to the abundance of web frame works) To list a few:

Pure Servlets (As you have done)

Servlet + JSP

Servlet + JSP ( using JSTL)

Struts frame work involving JSP and action classes

Spring webflows (involves JSP)

Velocity, Tapestry, Cocoon, Stripes ( all require JSP knowledge) ... and it is endless

An ideal way is to separate content out of Servlets. Content should go into pages such as JSPs. Servlets' out.println is so.. 90s. Java web technology has come a long way since then. Cheers!

ring bearer
  • 20,383
  • 7
  • 59
  • 72