Helloworld! of C + + write dynamic website

Source: Internet
Author: User

Sample source code:fetch_platform.7z

More complex code can refer to the implementation of this blog BBS


Simply put, the dynamic site is the site can be dynamically changed, dynamic content is usually from the back-end database, the following ellipsis ( dynamic site )

A dynamic Web page into a dynamic site, dynamic Web pages in a certain template by the back-end local replacement, so that users see the content is on demand and change, here we ignore the database processing part, directly realize the changes in the content of the Web page, to understand the server-side work principle, It is helpful for you to understand the work process of the entire dynamic website.

Note: The following procedures are all used with Visual C + + Express compilation on Windows 7 64, such as using a different environment or tool, please take care of the master himself

Static page


Dynamic page



start usingIDE

Open in Visual C + + Express 2008, configure as shown


website Port

the portal of the website program is in file HTTPFormServer.cpp, below is the port of the website, usually 80 port, in order to avoid possible port conflict, here use 8020, the website program runs up can use http://localhost:8020/access ,

Of course, if the 80 port on your computer is not occupied by other programs, you can simply use http://localhost/ to access it.

            unsigned short ports = 8020;if (Args.size () > 0)/change default Portport = (unsigned short) Numberparser::p Arse (args[ 0]);


Back-end Add service class

Add a header file DemoService.h

#ifndef demo_service_h#define demo_service_h#include "Shared_service.h" class Demoservice:public SharedService{ Public:    void handle (poco::net::httpserverrequest& req, poco::net::httpserverresponse& resp,        Poco:: uri& URI, const std::string& fileName);p ublic:    static const std::string Service_prefix;//For URL distribution    Private:}; #endif//Demo_service_h

Implementation fileDemoservice. cpp

#include "demo_service.h" Const std::string demoservice::service_prefix        = "/demo/";//the address bar shown below will enter the following method//HTTP ://domain/demo/***//void Demoservice::handle (poco::net::httpserverrequest& req, Poco::Net::HTTPServerResponse & Resp,     Poco::uri & URI, const std::string& fileName) {    //classify processing demo under different request, then return////    otherwise , if there is no special processing, will call the parent class handle method//        As an example, there is no expansion of demoservice, interested can download BBS source code    //So here directly to the parent class processing    //   Sharedservice::handle (req, resp, Uri, fileName);}

webserver is how the browser's request is forwarded to the Demoservice?

The answer is in the Servicedispatcher class, specifically as follows

    Demo Service    if (StartsWith (FileName, Demoservice::service_prefix))    {        Demoservice demo;        Demo.handle (req, resp, Uri, fileName);        return;    }


Add Label class

Tag class is responsible for dynamically replacing the content in the template, the most important part of the label is the label name, must be guaranteed to uniqueness

The label class must be used in conjunction with the . JSP front- End Web page to achieve the effect of dynamically displaying Web pages

Header file

#ifndef demo_tag_h#define demo_tag_h#include "Poco/net/base_tag.h" class Demotag:public Poco::net::basetag//    Generates the number of the last hits shown on this page. {public:    Demotag ();    ~demotag (); #ifndef using_stencil_serialize    virtual void Printendtag (poco::net::P agerequest* req, poco::net:: Pageresponse* resp);        Called when the parser reaches the end tag.        ///          @param request the page request.        @param response the page response.        @throws Exception If There is an Exception. #endif}; #endif//Demo_tag_h
Implementation part

#include "demo_tag.h" Demotag::D Emotag () {#if!defined (_DEBUG) | | defined (using_stencil_serialize) _type = demo_tag;# Endif}demotag::~demotag () {} #ifndef using_stencil_serializevoid Demotag::p rintendtag (poco::net::P agerequest* req, Poco::net::P ageresponse* resp) {    std::string type = getparameter ("type");    Here, depending on the type, return different strings to the browser    //Implement Dynamic Web page effects    if (type = = "Chinese")    {        resp->print ("Hello, World!");    }    else        resp->print ("Hello world!");} #endif

The label class must be registered before webserver will know

See Basetagmanager class

void Basetagmanager::registeralltags () {basetagfactory& tagfactory = basetagfactory::d efaultfactory (); Tagfactory.registertagclass ("Demo",                 new Instantiator<demotag, basetag>);    /* * The following is used to create new object and loading from file */#if!defined (_DEBUG) | | Defined (using_stencil_serialize) tagfactory.registertagclass (Demo_tag,             new Instantiator<demotag, BaseTag >), #endif//Ndebug | | Using_serialize_tag}

Now when there is a browser-basedwhen requested, webserver can implement the dynamic output Web page.

Front-end New JSP file

The front-end resources are all placed under the root folder, andthe root directory of the Webserver Action Web page is here.

In the root folder, we create a new demo folder, and then create a new. jsp file, JSP extension to tell Webserver is currently requesting a dynamic Web page

Of course you can also use any other extension, if you want to use a different extension, you need to modify the following part of the Sharedservice::handle method

    if (file.exists () && file.isfile ())    {        if (EndsWith (NewFileName, std::string (". JSP"))// A file that ends with a JSP represents a dynamic Web page        {#ifdef _DEBUG            poco::net::executer* root = _parser.parse (Fetch_wwwroot, Path (NewFileName). ToString ()); #else

Add tags

In the backend Code section, we have added the label processing class, where we need to add the front-end section, only the two sides of the corresponding, a real Dynamic Web page to work properly

index.jsp

<fetch:demo/><br><fetch:demo type= "Chinese"/>

Label description

<fetch:demo/>,fetch is not practical but can not be omitted, can be used to search the label, the key part is the demo, this is with the back-end

Tagfactory.registertagclass ("Demo",                 new Instantiator<demotag, basetag>);
Want to correspond, if you want to create a new individual tag, fully refer to the demo this can be

<br>, is a standard HTML tag that represents a newline

<fetch:demo type= "Chinese"/>, with the first line than, more Type= "Chinese", here you can also change to other, but the form must be consistent, such as you can change to value= "English", That corresponds to the demotag part of the backend.

std::string type = getparameter ("type");
You need to change the

std::string value = GetParameter ("value");

Summary
    1. Add the service class and distribute it in servicedispatcher based on the file name
    2. Add tag class and register in Basetagmanager
    3. Add a JSP Web page, and note that the tag class mates

Helloworld! of C + + write dynamic website

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.