Creating an HTTP Response
The servlet container provides several ways to use a
rwsf::HttpServletResponse object to return a response to a client.
Using Java-Like Output Functions
Each response object contains an output object that supports a set of overloaded print() and println() functions described in the Servlet Specification. These functions are convenient for programmers accustomed to Java servlet programming. The sample below shows a doGet function that creates a simple HTML response with the Java-like functions:
void myServlet::doGet (rwsf::HttpServletRequest& request,
rwsf::HttpServletResponse& response)
{
response.setContentType("text/html"); // 1
rwsf::ServletOutputStream& out = response.getOutputStream(); // 2
out.println("<html>"); // 3
out.println("<head><title>Simple Response</title></head>");
out.println("<body bgcolor=\"white\">");
out.println("<h1>Simple Response</h1>");
out.println("A simple HTML response.");
out.println("</body></html>");
}
Setting the Response from a String
An
rwsf::ServletResponse also provides a
setPayload() function. The function sets the body of the response directly, from a single
std::string. Setting the payload directly is generally more efficient than using the
rwsf::ServletOutputStream class to write the response. The
doGet() function below constructs a
std::string, then uses the
setPayload() function to create the response.
void myServlet::doGet (rwsf::HttpServletRequest& request,
rwsf::HttpServletResponse& response)
{
response.setContentType("text/html"); // 1
std::string output("<html>\n"
"<head><title>Simple Response</title></head>\n"
"<body bgcolor=\"white\">\n"
"<h1>Simple Response</h1>\n"
"A simple HTML response.\n"
"</body></html>\n"); // 2
response.setPayload(output); // 3
}
The related function appendPayload() appends a string to the current contents of the response.