views:

73

answers:

4

Hi, 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.

A: 

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
A: 

Just choose one web framework among many

Boris Pavlović
+3  A: 

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
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
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 (<th>Title</th><th>Author</th><th>Album</th>), but it looks like the code between the <c:foreach> does not have any effect. The jstl-1.2.jar file is placed as you indicated. Am I missing anything? Thanks
dedalo
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 `<c:forEach>`.
BalusC
The installation directory says it is Tomcat 6.0.In the web.xml it says:<?xml version="1.0" encoding="ISO-8859-1"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">When I use ${items} in the jsp file it is printed in the brower the same information that provides items.toString(). Thanks
dedalo
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
The page source looks ok, no java/jsp tags. I do see there the <c:forEach> 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
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
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
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
Ok, one of the classes was duplicated, now it is ok. Thanks!
dedalo
Could someone help me with this? http://stackoverflow.com/questions/2383309/servlet-jsp-javabeans-and-html-form
dedalo
A: 

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