Programming examples
alphabetic index hierarchy of classesI've always considered examples very important. In this section I am providing a few of them, for different input tags and situations. One could start from these examples and modify them for other purposes. I'm not showing the complete code (i.e., where I include libcgi++.H, etc.), so pay attention and use common sense.
- Text tag
- Assume you have a database front-end and you pass a name through an HTML form. For this case, you use an HTML tag like INPUT TYPE=TEXT NAME="name" with the following code:
string employee_name=input["name"];
- Checkbox tag
- The exist accessor is used to get the input from checkboxes. Assume the HTML is INPUT TYPE=CHECKBOX NAME="chk". The following code does the decoding:
bool chk=input.exist("chk");Of course, you could also use the exception mechanism to do this, but it is more complicated.
- Recovering from errors
- ``EXCEPTION--Something that is excepted; a particular case which comes within the terms of a rule, but to which the rule is not applicable; a person or thing that does not conform to the general rule affecting other individuals of the same class.''---Oxford English Dictionary. Although whoever wrote the OED probably has no idea what CGI is (it does not have an entry), this definition continues to apply. Here are two possible scenarios:
- If for any reason decoding fails, the CGI program dies a horrible death. That is why the constructor throws exceptions. They need to be handled with code like the following:
Cgi *input=0; try { input=new Cgi(); } catch (Cgi::CgiException& e) { cerr << "Error while decoding" << endl << "(maybe called from command-line?)." << endl; // do some other error processing } // continue normal execution
- Requesting a non-existent variable also causes an error (only when exceptions are enabled). This is handled in the following way:
string foo; try { foo=input["name"]; } catch (Cgi::CgiException& e) { cerr << "Variable not found: " << e.s << endl; foo="(none)"; // default value } // continue normal executionWithout exceptions, this accessor returns the empty string. Depending on application, this could be a limitation.
generated by doc++