views:

74

answers:

4

Hi,

I have a doubt regarding the use of servlets.

In the application I'm building I use Html pages to ask the user for info.

Imagine a Html page that lets the user request to see on the screen the content of a data base. What I'm doing is:

1.- From the Html page I'm calling a servlet that will open a connection with the database. 2.- The servlet builds the web page that the user will see.

My question is: is there any other way of doing this? Do I have to build the web page in the servlet or thre is any way of sending the information contained in the database to an .html file which will build the web page (in my case I need to show on the screen a table containing all the info) ?

Thanks

+1  A: 

Ultimately the browser has to send a request to the server for the database info. You can do this in many ways:

  1. build the whole page in the servlet (perhaps the simplest)
  2. build a page in the servlet containing (say) XML data, and the browser renders it into HTML (via XSL/Javascript etc.). That may be suitable if you want the browser to control the formatting and presentation.
  3. build a page containing AJAX requests to go back to the server and get the data. That may be more suitable for data that updates regularly, or more interactive applications.

There are numerous ways to skin this cat. I suspect you're doing the simplest one, which is fine. I would tend towards this without explicit requirements that mean I need to do something else. Further requirements that complicate matters may include paging the data if there's too much to fit on the screen. All the solutions above can be made to incorporate this in some fashion.

Brian Agnew
Thanks for your answer. I also think I'm doing the easiest thing here (my application produces some results and I want to build a user-friendly enviroment). I just wanted to know if I was doing some kind of crazy thing here or something that must not be done. Thanks!
dedalo
I think it's *entirely* reasonable unless you have specific requirements or performance considerations that make it unrealistic
Brian Agnew
If I wanted to go for the second option that you described... how would that be? My servlet is connects to MySQL and prints in the browser a table that contains the info stored in the data base.Is there any example I could see and study?Thanks
dedalo
+3  A: 

In addition to Servlets, Java has JSP pages, which are a mix of HTML and custom tags (including the Java Standard Tag Library or JSTL) which are eventually compiled into Servlets.

There are other technologies for making web applications, including things like Java Server Faces (JSF), Apache Struts, Spring, etc... Spring in particular is very widely used in modern web application development.

Ultimately, though, it's like Brian Agnew said... you have to communicate back and forth from the browser to the server. These are just various technologies to facilitate that.

R. Bemrose
+2  A: 

Servlets are meant to control, preprocess and/or postprocess requests, not to present the data. There the JSP is for as being a view technology providing a template to write HTML/CSS/JS in. You can control the page flow with help of taglibs like JSTL and access any scoped attributes using EL.

First create a SearchServlet and map it on an url-pattern of /search and implement doGet() and doPost() as follows:

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Preprocess request here and finally send request to JSP for display.
    request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // Postprocess request here. Get results from your DAO and store in request scope.
    String search = request.getParameter("search");
    List<Result> results = searchDAO.find(search);
    request.setAttribute("results", results);
    request.getRequestDispatcher("/WEB-INF/search.jsp").forward(request, response);
}

Here's how the JSP /WEB-INF/search.jsp would look like, it makes use of JSTL (just drop JAR in /WEB-INF/lib) to control the page flow.

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

...

    <form action="search" method="post">
        <input type="text" name="search">
        <input type="submit" value="search">
    </form>

    <c:if test="${not empty results}">
        <p>There are ${fn:length(results)} results.</p>
        <table>
            <c:forEach items="${results}" var="result">
                <tr>
                    <td>${result.id}</td>
                    <td>${result.name}</td>
                    <td>${result.value}</td>
                </tr>
            </c:forEach>
        </table>
    </c:if>

Note that JSP is placed in /WEB-INF to prevent users from direct access by URL. They are forced to use the servlet for that by http://example.com/contextname/search.

To learn more about JSP/Servlets, I can recommend Marty Hall's Coreservlets.com tutorials. To learn more about the logic behind searchDAO, I can recommend this basic DAO tutorial.

To go a step further, you could always consider to make use of a MVC framework which is built on top of the Servlet API, such as Sun JSF, Apache Struts, Spring MVC, etcetera so that you basically end up with only Javabeans and JSP/XHTML files. The average MVC frameworks will take care about gathering request parameters, valitate/convert them, update Javabeans with those values, invoke some Javabean action method to process them, etcetera. This makes the servlet "superfluous" (which is however still used as being the core processor of the framework).

BalusC
A: 

My java is rusty but...

in your Data Access layer, iterate over the result set and build a custom object and insert it into an ArrayList;

class DataAccess {

public ArrayList foo(){
    //Connect to DB
    //Execute Query
    //Populate resultSet
    ArrayList result = new ArrayList();
    while(resultSet.hasNext())
    {
    CustomObject o = new CustomObject();
    o.setProperty1(resultSet.getInt(1));
    o.setProperty2(resultSet.getString(2));
    //and so on
    result.add(o);
    }
return result;
}
}

Call this method from your servlet. After you have populated the ArrayList, put it on the Request object and forward on to your .jsp page

ArrayList results = DataAccessClass.foo();
Request.setAttribute("Results", results);

In your jsp, build your markup using scriptlets

<% foreach (CustomObject o in Request.getAttribute("Results"))
{%>
<td><%= o.getProperty1()</td>
<td><%= o.getProperty2()</td>
<% } %>

Good luck

Robert