HTML Generation
April 5, 2000
Let's say in the above example we want to display this welcome
message in bold, using 'HTML'. There are several ways of
generating HTML content from within a servlet. The simplest is
to use the PrintWriter and write the detailed HTML tags.
So for e.g. to generate the 'bold' welcome message,
first we will set the content type :
response.setContentType("text/html");
Then write the HTML :
PrintWriter out = response.getWriter();
out.println("<HTML> <HEAD> <B> Welcome " + Name + "! ");
out.println("</B> </HEAD> </ HTML>");
In this way you can build the whole HTML page in the servlet.
NOTE: We do not intend to show how to write a well formatted HTML here,
but just the concept - how to generate HTML from a servlet.
The complete code for the Welcome Servlet with HTML generation is:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String Name = request.getParameter("myName");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML> <HEAD> <B> Welcome " + Name + "! ");
out.println("</B> </HEAD> </ HTML>");
}
}
There are two better approaches:
First one can define an HTML class say MyHTML with methods such
as
SetHeading1(String heading)
SetHeading2(String heading)
SetBody(String Body)
Then instead of writting the detailed HTML tages one can call:
SetHeading1("Welcome" + Name + "! ");
This way one can mask the details of the tags from the Servlet
programmer.
There are some commercial products available
which support such HTML
generation.
Another approach is to write a JSP which is described in the next
section.
We will cover Request dispatcher and Session Object in this
article and then go on to build a sample application. For
further information on Servlets refer to:
Sun's main servlet Page
Server side Java resources
Java Servlet Programming (site blessed by Jason Hunter ?)
coolservlets.com
The Next Servlet: The Request and the Response
Building Web Applications Using Servlets and JSP
Java Server Pages
|