A WResource is a target for an HTTP request. It specifies application-dependent content that may be generated by your application on demand. This allows you to serve auxiliary objects related to a particular application or application session, and perhaps dynamically generate the content. There are different type of resources which can serve an HTTP request:
You can deploy a resource depending on the scope:
By default, a resource is private to an application; access to it is protected by same secret session ID that protects any other access to the application.
You can help the browser to start a suitable helper application to handle
the downloaded resource, or suggest to the user a suitable filename for
saving the resource, by setting an appropriate file name using
suggestFileName()
.
To serve resources that you create on the fly, you need to specialize
the WResource
class and implement handleRequest()
.
Because of the nature of the web, a resource may be requested one time or multiple times at the discretion of the browser, and therefore your resource should in general not have any side effects except for what is needed to render its own contents. Unlike event notifications to a Wt application, resource requests are not serialized, but are handled concurrently. You need to grab the application lock if you want to access or modify other widget state from within the resource.
When deleting a resource, any pending request is cancelled
first. For this mechanism to work you need to specialize the destructor
and call beingDeleted()
. This method may safely be called
multiple times (i.e. from within each destructor in the hierarchy).
Static resources are global which means that they are available as long as the application is running. A web service (e.g. REST, SOAP, WSDL) is a typical example of a resource that should always be available. This could be needed for machine-to-machine communication, etc.
Use WServer::addResource()
to deploy static resources.
#include <Wt/WContainerWidget.h>
#include <Wt/WPainter.h>
#include <Wt/WResource.h>
#include <Wt/WServer.h>
auto container = std::make_unique<Wt::WContainerWidget>();
//auto resource = std::make_shared<SamplePdfResource>();
//WServer::addResource(resource, "/media/static-resource");
Classes such as WAnchor
or WImage
can use a resource
instead of a URL to provide their contents. So, in any widget where you
pass a WLink, you can refer to a resource. You can find several examples
in the widget gallery: