Java Servlets   «Prev  Next»

Lesson 8Generating a form in a servlet
Objective Write a servlet doGet() that generates a form.

Generating a Form in a Servlet

Writing a doGet() method that generates the HTML for a form is not much different than writing a doGet() method that generates any other kind of HTML.
There is one little trick, though: the ACTION parameter on the form should be the very same servlet that generated the form.
You could hard-code this, but then whenever your servlet changed name or location, you would have to remember to change the ACTION parameter too.
It was better to use a method of the HttpServletRequest class called getServletPath(). As you might imagine, this method returns a string that you can use in the ACTION parameter of the form you generate.

A typical doGet()

Here is the way a typical doGet() (that generates a form) looks:
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
	PrintWriter out = res.getWriter();
	// generate the start of the page in ordinary HTML
	String url = req.getServletPath();
	out.println("<form method=POST action=\""+ url+ "\">");
	// generate the INPUT and other tags within the form

The backslash (\) characters in the println() statement for the FORM tag deserve a mention. The ACTION attribute should be surrounded by double quotes, like this:

<FORM METHOD=POST ACTION="http://localhost:8080/servlet/Form">

In order to put a double quote into a literal string, you must excape it with the backslash (\) character. This tells the compiler that the " character is not the end of the string you are typing, but rather a character you want to use in the string.
Learn how to code doPost() in the next lesson.