-
Previously,
a servlet with a
doGet
method has been used to get HTML
generated dynamically.
-
How can the visitor
influence the execution of the bytecodes?
-
Often the author
produces a WWW form
for the visitor to provide input.
-
Here is a WWW page
to obtain a Centigrade value:
0065: <HTML>
0066: <BODY>
0067: <FORM METHOD="POST" ACTION="http://localhost:8080/mytomcat/servlet/toFahrenheit">
0068: Type in a Centigrade value
0069: <INPUT TYPE="text" NAME="centigrade">
0070: <BR>
0071: <INPUT TYPE="submit" VALUE="Get Fahrenheit">
0072: </FORM>
0073: </BODY>
0074: </HTML>
-
Suppose this HTML is in a file called
toFahrenheit.html.
-
When a browser visits this WWW page,
the WWW form will appear.
-
The visitor types a value into the textbox
and clicks on the
button.
-
When the visitor does this,
the action given in the ACTION
attribute gets executed.
-
This means that the bytecodes of the
toFahrenheit
servlet will get executed.
-
Here is the code of a toFahrenheit servlet:
0075: import javax.servlet.http. HttpServlet; // toFahrenheit.java
0076: import javax.servlet.http. HttpServletRequest;
0077: import javax.servlet.http. HttpServletResponse;
0078: import java.io. IOException;
0079: import java.io. PrintWriter;
0080: import javax.servlet. ServletException;
0081: public class toFahrenheit extends HttpServlet
0082: {
0083: public void doPost(HttpServletRequest request,
0084: HttpServletResponse response)
0085: throws IOException, ServletException
0086: {
0087: String tCentigradeString = request.getParameter("centigrade");
0088: double tCentigrade = Double.parseDouble(tCentigradeString);
0089: double tFahrenheit = 32 + tCentigrade*9/5;
0090: response.setContentType("text/html");
0091: PrintWriter tResponsePrintWriter = response.getWriter();
0092: StringBuffer tStringBuffer = new StringBuffer();
0093: tStringBuffer.append("<html>\n" );
0094: tStringBuffer.append("<head>\n" );
0095: tStringBuffer.append("<title>Reply</title>\n" );
0096: tStringBuffer.append("</head>\n" );
0097: tStringBuffer.append("<body>\n" );
0098: tStringBuffer.append("<p>\n" );
0099: tStringBuffer.append("In Fahrenheit, this is " + tFahrenheit + "\n" );
0100: tStringBuffer.append("</p>\n" );
0101: tStringBuffer.append("</body>\n" );
0102: tStringBuffer.append("</html>\n" );
0103: tResponsePrintWriter.println(tStringBuffer);
0104: tResponsePrintWriter.close();
0105: }
0106: }
-
Because a WWW form is being used,
an HTTP POST request will be generated.
-
For this reason,
the above code overrides
doPost
rather than
doGet.
-
Like
doGet,
the
doPost
method
has two parameters.
-
It is the parameter called
request
that enables the values supplied on the WWW form
to be accessed.
-
Because in the HTML we gave the textbox
the name centigrade, ...
-
... the servlet can access the text typed into the
centigrade textbox
using:
0087: String tCentigradeString = request.getParameter("centigrade");