Home Backend Development XML/RSS Tutorial Detailed explanation of XML and sample code for modern CGI applications

Detailed explanation of XML and sample code for modern CGI applications

May 19, 2017 pm 01:11 PM

Introduction

The popularity of Perl is directly related to the vigorous development of the Internet. Perl's powerful functions and easy expansion make it the most natural choice for developing CGI applications, and it has quickly become the preferred language for CGI scripts. CGI itself is not perfect. But thanks to the favor of many developers, CGI is still widely used today and shows no signs of "retiring" in the near future.

A typical CGI::XMLApplication script consists of three parts: a small executable script that provides access support to the application, a logic module that implements various manager methods, and a logic module that implements various manager methods. ##There may be one or more XSLT style sheets. XSLT style sheets can convert the results returned by the module into a format that the browser can display to the user. Below we briefly introduce the application of CGI::XMLApplication through examples.

Example 1: CGI XSLT Gateway

CGI::XMLApplication assumes that the designers and developers involved in a project separate the logic and presentation of the application using XSLT stylesheets to make this separation apparent Very direct and will not have any impact on the project. Developers only need to be able to make setStylesheet return the location of the XSLT style sheet that matches the current application state. The conversion of the DOM tree created by the application, the transmission of XSLT parameters to the conversion engine, and the transmission of converted content to the browser are all transparent to users.

To highlight this separation, our first example is not a web application in the traditional sense, but a generic XSLT gateway that can be added to the server's cgi-bin to convert the entire XML content The directory tree is converted into a format that conforms to the requesting browser, and all this is transparent to users, stylesheets, and document authors.

The first step is to establish a CGI script that connects the client's request and application. We want to make XML documents easily browseable via URLs and make creating hyperlinks between these documents intuitive. Therefore, we will create a CGI script without the extension so that as a node in the URL path, everything to the right of the node will be interpreted within a virtual document environment containing XML content. In this case, we call CGI a style sheet selector.

use strict;
use lib '/path/to/secure/webapp/libs';
use XSLGateway;
use CGI qw(:standard);my $q = CGI->new();
my %context = ();
my $gateway_name = 'stylechooser';
Copy after login

After loading the appropriate modules and setting some

variables

that are valid throughout the script, we start adding some fields to the %context that is passed to the class that handles the application logic . In this application, we only pass the requested URL (REQUEST entry) to the right of the path to the script file and the STYLE key containing the data stored in the query parameter style.

Finally, we create an instance of the XSLGateway logical class and handle the request by calling its run method, passing %context as the only parameter.

my $app = XSLGateway->new();
$app->run(%context);
Copy after login

The CGI script is complete. Next we create the XSLGateway module that does most of the work:

package XSLGateway;
use strict;
use vars qw(@ISA);
use CGI::XMLApplication;
use XML::LibXML;
@ISA = qw(CGI::XMLApplication);
Copy after login

As I mentioned in the introduction, CGI::XMLApplication works via

Event

calls: a given in the application class The execution of a certain method depends on the input of a specified field (usually the name of the button used to submit the form.), and two calling methods must be executed: selectStylesheet and requestDOM method. selectStylesheet returns the full

file system

path to the relevant XSLT style sheet. For simplicity, we assume that the stylesheet will be kept in a single directory. We can provide other style sheets through the $context-> {STYLE} field to increase the flexibility of the system.

Next, we need to create the requestDOM method, which will return the XML::LibXML DOM

expression

of the XML document being transferred. Since our gateway only works with static files, we need to use XML::LibXML to parse the document and return the result tree.

At this point, our CGI script can be safely run in the cgi-bin directory of the server and upload some XML documents and one or two XSLT stylesheets in some appropriate directories. Now we can start to test the results of our work. A request to localhost/cgi-bin/stylechooser/mydocs/somefile.xml will cause the Internet server to select the mydocs/somefile.xml file from the /opt/www/htdocs/xmldocs/ directory, using /opt/www/htdocs/stylesheets The stylesheet default.xsl in / transforms the file and transmits it to the client.

如果需要,我们可以扩充这一基本的框架,例如,可以 在样式表选择CGI脚本程序添加一些查找组件,选择合适的样式表,可以设置或读 取HTTP cookies,对网站进行修饰。

例2:一个简单的购物系统

在 该例子中,我们将使用CGI::XMLApplication创建一个简化的Web应用程序,购物 系统。

与上个例子相同,这个应用程序中与CGI-BIN有关的部分仍然非常 地少。我们所需要作的只不过是初始化CustomerOrder应用类并调用它的run()方 法。这次,我们将CGI.pm中Vars作为%context的PARAMS域:

use strict;
use CGI qw(:standard);
use lib '/path/to/secure/webapp/libs';
use CustomerOrder;
my $q = CGI->new();
my %context = ();
$context{PARAMS} = $q- >Vars;
my $app = CustomerOrder->new();
$app->run(% context);
Copy after login

在这个例子中,我们假定该应用中的产品信息存储在关 系数据库中,产品清单不是太长,使我们在应用中不会出现多屏才能显示相关信 息的麻烦:用户输入订购的产品数量的主要数据输入屏,显示订购单内容和所选 物品总价格的确认屏,显示订单已经处理的提示。为了简单起见,我们在这里没 有涉及送货和财务数据的输入等问题。

package CustomerOrder;
use strict;
use vars qw(@ISA);
use CGI::XMLApplication;
use XML::LibXML::SAX::Builder;
use XML::Generator::DBI;
use DBI;
@ISA = qw (CGI::XMLApplication);
Copy after login

在加载必要的模块和定义从 CGI::XMLAplication中继承的类后,我们开始创建应用中与各种状态有关的事件 调用。首先,我们必须通过创建registerEvents()方法注册这些事件。在本例中 ,我们将注册order_confirm 和order_send方法,这二个方法设置%context中的 SCREENSTYLE域。稍后,我们将利用该属性定义在显示客户端的数据时应该使用三 个XSLT样式表中的哪一个。

需要注意的是,这些事件将被映射到实现它们 的实际的子程序中,子程序的命名规则是event_<事件名>,例如, order_confim事件是由event_order_confim执行的。另外,还需要注意的是,各 种事件的选择是由CGI::XMLApplication根据其查找一个与注册事件同名的表格参 数的能力进行的。例如,要执行order_confirm事件,表格组件中必须包含一个提 交非空值的名字为order_confirm的表格域。

# 事件的注册和事件调用

sub registerEvents {
return qw( order_confirm order_send );
}
sub event_order_confirm {
my ($self, $context) = @_;
$context->{SCREENSTYLE} = &#39;order_confirm.xsl&#39;;
}
sub event_order_send {
my ($self, $context) = @_;
$context->{SCREENSTYLE} = &#39;order_send.xsl&#39;;
}
Copy after login

如果没有请求执行其他的事 件,则缺省地执行event_default。在本例中,我们只使用它将SCREENSTYLE域设 定为一个合适的值。

sub event_default {
my ($self, $context) = @_;
$context->{SCREENSTYLE} = &#39;order_default.xsl&#39;;
}
Copy after login

每次请求都会执行 event_init方法,而且总是在其他方法之前执行它,这使得它非常适合对应用中 被其他事件使用的部分进行初始化。在本例中,我们使用它返回利用 fetch_recordset()方法从数据库中获取的产品信息的、最初的DOM树。

sub event_init {
my ($self, $context) = @_;
$context->{DOMTREE} = $self->fetch_recordset();
}
Copy after login

state-handler方法完成后,我们需要执行必需的 selectStylesheet和requestDOM方法。

与在第一个例子中一样,我们假设 所有的应用的样式表都存储在服务器上相同的目录中。我们所需要作的是返回 $context->{SCREENSTYLE}的值所指定的路线,并添加到末尾。

# app config and helpers
sub selectStylesheet {
my ($self, $context) = @_;
my $style = $context-> {SCREENSTYLE};
my $style_path = &#39;/opt/www/htdocs/stylesheets/cart/&#39;;
return $style_path . $style;
}
Copy after login

在研究requestDOM处理程序之前,我们先来详细 地研究fetch_recordset helper方法。

需要记住的是,我们要做的工作是 从一个关系数据库中选择所订购产品的有关信息,但传递给XSLT处理器的数据必 须是DOM树。在本例中,我们不通过编程的方法,而是利用XML::Generator::DBI ,它能够从执行SQL SELECT语句得到的数据中生成SAX数据。创建要求的DOM树就 是建立XML::LibXML::SAX::Builder(它从SAX事件中创建XML::LibXML DOM树)的 实例。

sub fetch_recordset {
my $self = shift;
my $sql = &#39;select id, name, price from products&#39;;
my $dbh = DBI->connect(&#39;dbi:Oracle:webclients&#39;,
&#39;chico&#39;,
&#39;swordfish&#39;)
|| die "database connection couldn&#39;t
be initialized: $DBI::errstr n";
my $builder = XML::LibXML::SAX::Builder->new();
my $gen = XML::Generator::DBI->new(Handler => $builder,
dbh => $dbh,
RootElement => &#39;document&#39;,
QueryElement => &#39;productlist&#39;,
RowElement => &#39;product&#39;);
my $dom = $gen->execute($sql) || die "Error Building DOM Treen";
return $dom;}
Copy after login

fetch_recordset方法完成了另一项很重要的任务,但它返回的 DOM树只包含我们想向客户发送信息的一部分,我们还必须获取用户输入的产品数 量,另外,还需要提供一个订购产品的总计。

sub requestDOM {
my ($self, $context) = @_;
my $root = $context-> {DOMTREE}->getDocumentElement();
my $grand_total = &#39;0&#39;;
Copy after login

为了将当前的订货数量作为更大的文档的一部分, 我们将遍历所有的产品元素,并在每行中添加和子元素。的值可以从$context- >{PARAMS}域获得。

foreach my $row ($root->findnodes (&#39;/document/productlist/product&#39;)) {
my $id = $row- >findvalue(&#39;id&#39;);
my $cost = $row->findvalue (&#39;price&#39;);
my $quantity = $context->{PARAMS}->{$id} || &#39;0&#39;;
my $item_total = $quantity * $cost;
$grand_total += $item_total;
# add the order quantity and item totals to the tree.
$row->appendTextChild(&#39;quantity&#39;, $quantity);
$row->appendTextChild(&#39;item-total&#39;, $item_total);
}
Copy after login

最后,我们将增加一些有关订单的元信息 ,方法是在具有元素的根元素中添加一个元素,该元素中包含有当前所选货物的 总价值。

$grand_total ||= &#39;0.00&#39;;
my $info = XML::LibXML::Element->new(&#39;instance-info&#39;);
$info- >appendTextChild(&#39;order-total&#39;, $grand_total);
$root- >appendChild($info);
return $context->{DOMTREE};
}
Copy after login

细心的读者可能已经注意到,我们这个非常简单的应用程序在 order_send方法中没有作任何实际的事。决定如何处理这些数据是产品订购应用 程序中与具体的购物网站最有关的部分。

结束语

CGI::XMLApplication在CGI脚本程序的编程中提供了一种清晰的、模块化 的隔离系统的内容和表示的方法,单就这一点,就值得我们对它进行一番研究。 此外,它还可以使我们避免纠缠于一些细节问题,而集中精力解决主要的问题。

【相关推荐】

1. Detailed explanation of the example code of cgi writing data to text or database

2. Sharing an example tutorial on running Python scripts using CGI on IIS

3. Using CGI module to create a simple web page tutorial example

4. Share an example tutorial of Python CGI programming

5 . What is CGI? Detailed introduction to Python CGI programming

6. FastCGI process unexpectedly exited causing 500 error

The above is the detailed content of Detailed explanation of XML and sample code for modern CGI applications. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Unable to save changes to Photos app error in Windows 11 Unable to save changes to Photos app error in Windows 11 Mar 04, 2024 am 09:34 AM

If you encounter the Unable to save changes error while using the Photos app for image editing in Windows 11, this article will provide you with solutions. Unable to save changes. An error occurred while saving. Please try again later. This problem usually occurs due to incorrect permission settings, file corruption, or system failure. So, we’ve done some deep research and compiled some of the most effective troubleshooting steps to help you resolve this issue and ensure you can continue to use the Microsoft Photos app seamlessly on your Windows 11 device. Fix Unable to Save Changes to Photos App Error in Windows 11 Many users have been talking about Microsoft Photos app error on different forums

Photos cannot open this file because the format is not supported or the file is corrupted Photos cannot open this file because the format is not supported or the file is corrupted Feb 22, 2024 am 09:49 AM

In Windows, the Photos app is a convenient way to view and manage photos and videos. Through this application, users can easily access their multimedia files without installing additional software. However, sometimes users may encounter some problems, such as encountering a "This file cannot be opened because the format is not supported" error message when using the Photos app, or file corruption when trying to open photos or videos. This situation can be confusing and inconvenient for users, requiring some investigation and fixes to resolve the issues. Users see the following error when they try to open photos or videos on the Photos app. Sorry, Photos cannot open this file because the format is not currently supported, or the file

How to connect Apple Vision Pro to PC How to connect Apple Vision Pro to PC Apr 08, 2024 pm 09:01 PM

The Apple Vision Pro headset is not natively compatible with computers, so you must configure it to connect to a Windows computer. Since its launch, Apple Vision Pro has been a hit, and with its cutting-edge features and extensive operability, it's easy to see why. Although you can make some adjustments to it to suit your PC, and its functionality depends heavily on AppleOS, so its functionality will be limited. How do I connect AppleVisionPro to my computer? 1. Verify system requirements You need the latest version of Windows 11 (Custom PCs and Surface devices are not supported) Support 64-bit 2GHZ or faster fast processor High-performance GPU, most

How to solve application startup error 0xc000012d problem How to solve application startup error 0xc000012d problem Jan 02, 2024 pm 12:53 PM

When a friend's computer is missing certain files, the application cannot start normally with error code 0xc000012d. In fact, it can be solved by re-downloading the files and installing them. The application cannot start normally 0xc000012d: 1. First, the user needs to download ".netframework". 2. Then find the download address and download it to your computer. 3. Then double-click on the desktop to start running. 4. After the installation is completed, return to the wrong program location and open the program again.

MS Paint not working properly in Windows 11 MS Paint not working properly in Windows 11 Mar 09, 2024 am 09:52 AM

Microsoft Paint not working in Windows 11/10? Well, this seems to be a common problem and we have some great solutions to fix it. Users have been complaining that when trying to use MSPaint, it doesn't work or open. Scrollbars in the app don't work, paste icons don't show up, crashes, etc. Luckily, we've collected some of the most effective troubleshooting methods to help you resolve issues with Microsoft Paint app. Why doesn't Microsoft Paint work? Some possible reasons why MSPaint is not working on Windows 11/10 PC are as follows: The security identifier is corrupted. hung system

Fix caa90019 Microsoft Teams error Fix caa90019 Microsoft Teams error Feb 19, 2024 pm 02:30 PM

Many users have been complaining about encountering error code caa90019 every time they try to log in using Microsoft Teams. Even though this is a convenient communication app, this mistake is very common. Fix Microsoft Teams Error: caa90019 In this case, the error message displayed by the system is: "Sorry, we are currently experiencing a problem." We have prepared a list of ultimate solutions that will help you resolve Microsoft Teams error caa90019. Preliminary steps Run as administrator Clear Microsoft Teams application cache Delete settings.json file Clear Microsoft from Credential Manager

Can I open an XML file using PowerPoint? Can I open an XML file using PowerPoint? Feb 19, 2024 pm 09:06 PM

Can XML files be opened with PPT? XML, Extensible Markup Language (Extensible Markup Language), is a universal markup language that is widely used in data exchange and data storage. Compared with HTML, XML is more flexible and can define its own tags and data structures, making the storage and exchange of data more convenient and unified. PPT, or PowerPoint, is a software developed by Microsoft for creating presentations. It provides a comprehensive way of

Shazam app not working in iPhone: Fix Shazam app not working in iPhone: Fix Jun 08, 2024 pm 12:36 PM

Having issues with the Shazam app on iPhone? Shazam helps you find songs by listening to them. However, if Shazam isn't working properly or doesn't recognize the song, you'll have to troubleshoot it manually. Repairing the Shazam app won't take long. So, without wasting any more time, follow the steps below to resolve issues with Shazam app. Fix 1 – Disable Bold Text Feature Bold text on iPhone may be the reason why Shazam is not working properly. Step 1 – You can only do this from your iPhone settings. So, open it. Step 2 – Next, open the “Display & Brightness” settings there. Step 3 – If you find that “Bold Text” is enabled

See all articles