Dynamic content - novalexei/mod_servlet GitHub Wiki

Dynamic content

Now let's do something more dynamic. We will write servlet which will ask our name and address us by it. New class and export instruction:

class tutorial_2_servlet : public http_servlet
{
public:
    void do_get(http_request& req, http_response& resp) override
    {
        resp.set_content_type("text/html");
        std::ostream &out = resp.get_output_stream();
        auto name = req.get_parameter("t2-name");
        out << "<!DOCTYPE html>\n"
               "<html>\n"
               "<head>\n"
               "<title>Conversation</title>\n"
               "</head>\n"
               "<body>\n"
               "<form action=\"\">\n"
               "<p>- What is your name?</p>\n"
               "<p>- My name is <input type=\"text\" name=\"t2-name\" value=\"";
        if (name) out << name;
        out << "\"/><input type=\"submit\" value=\"Say\"/></p>\n";
        if (name) out << "<p>- Hello, " << name << ".</p>\n";
        out << "</form>\n"
               "</body>\n"
               "</html>\n";
    }
};

SERVLET_EXPORT(tutorial2Servlet, tutorial_2_servlet)

What makes difference here is the line:

        auto name = req.get_parameter("t2-name");

This line retrieves the value of a request parameter with a given name. "t2-name" is the name of the field in the HTML form which we generated right there in the very same servlet.

I believe you should still remember how to build, deploy, configure and run it from the information we already covered in previous section.

Now servlet talks to us and reacts to our input. But we still transfer all the information via GET request, which means the information encoded right into URL. What about streaming field in POST request?

POST request instead of sending information encoded into the URL can directly stream it to the server.

Let's now rewrite this servlet to use POST data transfer instead of GET. In order to do that we need to modify the HTML form tag we generate from:

               "<form action=\"\">\n"

to

               "<form method="POST" action=\"\">\n"

Also we need to implement do_post method in order to handle POST requests. But we still want to handle GET requests too, because initial request (before we submit the form) will come with GET method. We might notice that out GET and POST methods should be very similar. So we can just do this in our class:

    void do_post(http_request& req, http_response& resp) override
    {
        do_get(req, resp);
    }

And that's it! Now your servlet can handle POST requests. http_request is smart enough to figure out if this is a POST request and retrieve the parameters from the input stream instead of the URL.

In the next section we will find out what we can do with http_session

To The Programming Guide

⚠️ **GitHub.com Fallback** ⚠️