/* * @(#)EchoSurvey.java * * Copyright (c) 1998 Karl Moss. All Rights Reserved. * * You may study, use, modify, and distribute this software for any * purpose provided that this copyright notice appears in all copies. * * This software is provided WITHOUT WARRANTY either expressed or * implied. * * @author Karl Moss * @version 1.0 * @date 26Mar98 * */ package javaservlets.samples; import javax.servlet.*; import javax.servlet.http.*; /** *
This is a simple servlet that will echo survey information * that was entered into an HTML form. */ public class EchoSurvey extends HttpServlet { /** *
Performs the HTTP POST operation * * @param req The request from the client * @param resp The response from the servlet */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, java.io.IOException { // Set the content type of the response resp.setContentType("text/html"); // Create a PrintWriter to write the response java.io.PrintWriter out = new java.io.PrintWriter(resp.getOutputStream()); // Print a standard header out.println(""); out.println("
"); out.println("Initialize the servlet. This is called once when the * servlet is loaded. It is guaranteed to complete before any * requests are made to the servlet * * @param cfg Servlet configuration information */ public void init(ServletConfig cfg) throws ServletException { super.init(cfg); } /** *
Destroy the servlet. This is called once when the servlet * is unloaded. */ public void destroy() { super.destroy(); } /** *
Convert any carriage return/line feed pairs into
* an HTML line break command (
)
*
* @param line Line to convert
* @return line converted line
*/
private String toHTML(String line)
{
String s = "";
if (line == null) {
return null;
}
// Cache the length of the line
int lineLen = line.length();
// Our current position in the source line
int curPos = 0;
// Loop through the line and find all of the carriage
// return characters (0x0D). If found, convert it into
// an HTML line break command (
). If the following
// character is a line feed (0x0A) throw it away
while (true) {
// Make sure we don't run off the end of the line
if (curPos >= lineLen) {
curPos = 0;
break;
}
int index = line.indexOf(0x0D, curPos);
// No more characters found
if (index == -1) {
break;
}
// Add any data preceding the carriage return
if (index > curPos) {
s += line.substring(curPos, index);
}
// Add the line break command
s += "
";
// Adjust our position
curPos = index + 1;
// If the next character is a line feed, skip it
if (curPos < lineLen) {
if (line.charAt(curPos) == 0x0A) {
curPos++;
}
}
}
// Be sure to add anything after the last carriage return
// found
if (curPos > 0) {
s += line.substring(curPos);
}
return s;
}
}