Article

Java Servlets - Part 1

Page: 1 2 3 4 5 6 Next

A Dynamic Example

The simple Servlet (MyServlet) that we have worked with so far isn't terribly exciting, because it displays the same thing every time it is loaded. The power of Servlets is that they can generate a new dynamic response every time they are loaded. Common uses of Servlets include retrieving dynamic content from a database, displaying XML documents as HTML using XSL stylesheets, and processing form submissions and taking appropriate actions (e.g. ecommerce applications).

For our first dynamic Servlet, we'll display the current server date and time. Here's the code for the servlet (Time.java):

import java.io.*;    
import javax.servlet.*;    
import javax.servlet.http.*;    
import java.util.Date;    
   
public class Time extends HttpServlet {    
 public void doGet(HttpServletRequest req, HttpServletResponse rsp)    
               throws ServletException, IOException {    
   rsp.setContentType("text/html");    
   PrintWriter out = rsp.getWriter();    
   
   Date now = new Date(); // The current date/time    
   
   out.println("<html>");    
   out.println("<head><title> Time Check </title></head>");    
   out.println("<body>");    
   out.println("<p>The time is: " + now + "</p>");    
   out.println("</body></html>");    
 }    
}

All in all, this Servlet is very similar to MyServlet. Let's look at what's new:

import java.util.Date;

We import Java's built-in Date class from the java.util package. You can read up on this class in the Java API documentation if you're curious about its properties and methods.

   Date now = new Date(); // The current date/time

We create a new variable called now and store a new Date object in it. When a Date object is created, it contains the date and time at which it was created, and will display them when it is printed out as part of a String:

   out.println("<p>The time is: " + now + "</p>");

Compile this file (or download Time.class) and deploy it as shown in the previous section. Now, when you load http://localhost:8080/servlet/Time you'll see a page like this one:

The Time Check ServletClick Reload a few times in your browser and watch the page change each time.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links