Home arrow Java & J2EE arrow Page 3 - Getting Started with Java Servlets using Apache JServ

Examples - Java

In the quest for more dynamic content, web server technologies have flourished. One particular solution to provide this dynamic content is Java Servlet technology. As a replacement to the traditional CGI script approach, servlets give developers a powerful tool to create web enabled applications. Not only does the servlet solution give developers the ease of using the Java language, it is also offers a more efficient solution in terms of CPU power.

TABLE OF CONTENTS:
  1. Getting Started with Java Servlets using Apache JServ
  2. Installation
  3. Examples
  4. Future Directions
  5. Links
By: Richard M. Yumul
Rating: starstarstarstarstar / 11
September 07, 1999

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

As stated previously, one of the big benefits of using Java on the server is the ability to use any of large number of API's available for Java. One of the more common tasks in creating a web-enabled application is to make the html pages driven from a database. The following shows a simple example of a servlet accessing a database via JDBC. The database which my sample servlet will be connecting to is MySQL, a robust open-source database which has gained popularity in web applications because of it's reliability and blazing speed. For this example, you'll also need a JDBC driver for MySQL. One of which can be found at http://www.worldserver.com/mm.mysql/

The following example shows how one might use servlet technology in a simple shopping cart application. The product catalog will be stored in the database. Items placed in the customer's cart will be stored in the HttpSession object.

Setting up the database:

  1. First, create the database:
                                    
    $ mysqladmin create testCart
    Make sure that you have the appropriate permissions to create databases and tables in your MySQL database.
  2. Create the table and import data.
                                    
    $ mysql testCart < cart.sql

The ShoppingCart.java class displays a fictional product catalog where the customer can select items to add to their "cart". When the customer is done adding items to their cart, they can click on the "View Your Cart" link and get an itemized list of each product they selected.

The "brains" of the servlet is contained within the doGet() method. The cutomer's shopping cart is represented by a Java Hashtable. The key of the Hashtable is the productID of the item and the value of the Hashtable entry is the quantity of the products desired.


public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Hashtable cart; PrintWriter out; HttpSession session; out = response.getWriter(); response.setContentType("text/html"); session = request.getSession(true); String id = request.getParameter("id"); String command = request.getParameter("command"); String requestURI = request.getRequestURI(); cart = (Hashtable) session.getValue("cart"); if (cart == null) { cart = new Hashtable(); } out.println("<h1>Shopping Cart</h1>"); try { if (command.equals("add")) { Integer num = (Integer) cart.get(id); if (num == null) { num = new Integer(0); } cart.put(id, new Integer(num.intValue() + 1) ); printCatalog(out, requestURI); } else if (command.equals("viewcart")) { printCart(cart, out, requestURI); } else { printCatalog(out, requestURI); } } catch (NullPointerException e) { printCatalog(out, requestURI); } session.putValue("cart", cart); }

After declaring serveral objects, the the PrintWriter "out" is obtained from the HttpServletResponse's getWriter() method, as described previously. If the servlet were to return a binary file, like a dynamically created GIF or JPEG for example, you would want to use the ServletResponse's getOutputStream() method.

The next line,

        
session = request.getSession(true);
initiates a session in the servlet engine where information can be stored to have a persistent state. The customer's shopping cart, represented by the Hashtable, will be stored in the HttpSession object. The boolean parameter passed to the getSession() method tells the servlet engine to start a session if one hasn't already been started. If the parameter passed was 'false', then the servlet would return the already existing session object. Otherwise, the getSession() method will return null.

        
String id = request.getParameter("id"); String command = request.getParameter("command");
The next two lines demonstrate how to get values passed to your servlet from HTML forms. The getParameter() doesn't differentiate if the form data was passed in a GET request or a POST request. If the form parameter doesn't exist, the method returns null. Alternatively, you can use the ServletRequest's getParameterNames() method to get an Enumeration of parameter names you can iterate through with the getParameter() to get all of the form names and values.

Next, the cart is instantiated.

        
cart = session.getValue("cart"); if (cart == null) { cart = new Hashtable(); }
If the Hashtable cannot be retrieved from the session object with the HttpSession.getValue(String key) method, then one is instantiated as a new Hashtable.

Now comes the logic of the servlet. The default behavior of the servlet is to print display the product catalog. If the customer click's on the "Add to Cart" hyperlink, the command "add" and the product ID of the item is passed to the servlet. The value of the Hashtable entry with the productID as the key is incremented, and the product catalog is again displayed. If the "View your Cart" hyperlink is clicked, then the "viewcart" command is passed to the servlet and the contents of the customer's cart is displayed.

Finally, after products have been added (optionally) to the the cart Hashtable, it is put back into the session object, replacing the old cart.

JDBC
The product listing and cart content listing is generated dynamically from the database.


public void init(ServletConfig config) throws ServletException { super.init(config); dbc = null; try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/testCart?" + "user=dbUser&password=userPasswd"); } catch (Exception e) { e.printStackTrace(); } }
In the init() method, the database connection is initialized, and will be available to the servlet for its lifetime. In the JSDK 2.0 specification, the super.init(ServletConfig) method must be the first command in the method. However, in version 2.1 of the specification, this requirement has been fixed and is no longer necessary. If you are going to be using mutltiple servlets accessing a database, a better solution would be to use a database connection pool.


try { Statement stmt = dbc.createStatement(); stmt.execute("select * from Products"); ResultSet rs = stmt.getResultSet(); while (rs.next()) { out.println("<tr>"); out.println("<td><b>" + rs.getString("name") + "</b><br>" + rs.getString("description") + "</td>"); out.println("<td align=\"right\">" + nf.format(rs.getDouble("price")) + "</td>"); out.println("<td><a href=\"" + requestURI + "?command=add&id=" + String.valueOf(rs.getInt("productID")) + "\">Add to Cart</a></td>"); out.println("</tr>"); } rs.close(); stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
The JDBC methods called in the printCatalog() and printCart() methods are fairly straightforward; we simply create a Statement from the database connection, execute the SQL query, and then iterate through the result set.

It is important to remember to free up the resources used in your servlet, as multiple accesses can impact your server quite quickly. In the ShoppingCart.java example statements and result sets are closed after every request, and the database conncection is closed inside the servlet's destroy() method.



 
 
>>> More Java & J2EE Articles          >>> More By Richard M. Yumul
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

JAVA & J2EE ARTICLES

- More Java Bugs Lead to More Attacks
- Oracle's Java One Brings News, Surprises
- Oracle Patches Java Runtime Environment
- Apple Syncs Java Update with Oracle
- Spring 3.1 Java Development Framework Compat...
- Jelastic Java PaaS Availability and Pricing ...
- NetBeans 7.1 Released, Supports JavaFX 2
- SolarWinds Releases Newest Version of Java M...
- Free Monitoring Tool for Java Apps on Heroku
- Heroku Adds JCloud Platform Support, Java 7 ...
- Java SE 8 Speculation in Full Swing
- Java SE 7 Now Available
- New JVM Language and Java Reporting Tool
- Java 7 Release Update and New Eclipse Toolkit
- The Best Java Netbeans IDE Plugins

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: