Технология создания активных документов SSI+ -- Server Side Includes предложена фирмой Questar Microsystems. Эту технологию поддерживают такие WWW сервера как Apache, Netscape, Spry Web и Microsoft Internet Information Server (MS IIS).
Поддержка этой технологии связана с специальной конфигурацией WWW сервера и протокола HTTP.
Технология Server side includes (SSI) позволяет использовать в HTML документах такие возможности как: опрос текущего времени и даты, условного выполнения форматирования в зависимости от логических сравнений, формировать запросы или модифицировать базы данных, посылать электронную почту, вызывать программы или CGI scripts.
Возможности технологии SSI+ задают механизм совместного использования языка HTML и программ CGI Script.
Замечание: отметим, что различные сервера (например, Apache или MS IIS) немного поразному интерпретируют команды SSI.
Формат команды SSI+:
'<!--#<tag><variable set >-->'
где:
Чаcть команд SSI имеют подкоманды, управляющие их работой, например, команды if, и exec. Формат подкоманды следующий:
'&&'<subtag>'&&'
где:
Замечание о SSI документах
SSI+ документ по умолчанию имеет суффикс (расширение) '.SHT' (для MS Windows) или '.SHTM' (для UNIX систем) для их отличия от обычных HTML документов, которые имеют расширение '.HTM' или .HTML соотвественно.
При конфигурации сервера можно объявить все документы как SSI, но это снижает его эффективность, но не существенно.
'echo' | Включение значений переменных окружения (CGI) в HTML документ. |
'set' | Установка значений переменной окружения. |
'include' | Включение файла в HTML документ. |
'fsize' | Включение размера файла в HTML документ. |
'flastmod' | Включение даты последней модификации файла в HTML документ. |
'exec' | Выполнение внешнего исполняемого файла (CGI программы). Выходной поток данных (стандартный вывод) этой программы включается в документ. |
'config' | Установка параметров для SSI+ команд. |
'if' | Условный оператор, управляющий выполнением других команд SSI и вывода документа. |
'goto' | Оператор перехода на определенную SSI метку ('label'). |
'label' | Метка в документе. |
'break' | Остановка вывода документа. |
Включение значений переменных
окружения в HTML документ. Команда echo имеет только один атрибут
var
Пример:
Вы используете просмотрщик <!--#echo var="HTTP_USER_AGENT"-->
Если данный документ просматривается через просмотрщик MS Internet Explorer 3.0 for Windows 95, то эта команда даст следующий результат
Вы используете просмотрщик Mozilla/2.0 (compatible; MSIE 3.0; Windows 95)
А для просмотрщика, через который вы сейчас читаете этот текст, получим
Вы используете просмотрщик Mozilla/4.0 (compatible; MSIE 5.5; Windows 98; Win 9x 4.90)
WWW сервер, который понимает технологию SSI, как правило, использует описанные ниже переменные окружения. Кроме того, если на сервере разрешено выполнение исполняемых модулей (CGI Script программы), то в документе могут быть использованы и переменные окружения CGI.
Пример. Вызов документа ssi-var.html выводит значения всех перечисленных выше переменных.
Установка значения переменной окружения.
Параметры (атрибуты):
<!--#set var="category" value="help" -->
Установка переменных важна при передаче параметров динамическому ресурсу, вызываемому командами include или exec, т.к. для системы они являются дочерним процессом и переменные CGI для них не будут переданы.
По команде 'include' на место этой команды подставляется содержимое файла, на
который она указывает.
Команда имеет два параметра (атрибута):
Замечание: при задании адресов ресурсов можно использовать как полный
путь к ресурсу (на сервере) так и частичный.
Отметим, что используя команду include можно вставлять в документ и
активные ресурсы (динамические
страницы), обрабатываемые WWW сервером, например, PHP скрипты или те же
shtml файлы, при этом перед вставкой (в отличие от ASP скриптов сервера MS
IIS) сервер произведет обработку этих ресурсов.
Формат выдачи размера соотвествует установке сервера и может быть изменен
командой config.
Команда flastmod включает дату последней модификации файла.
Пример: Формат выдачи даты и времени соотвествует установке сервера и может быть
изменен командой config.
Выполнение внешних программ и программ CGI Script.
Параметры:
Команда config модифицирует вывод в HTML документ.
Параметры-атрибуты команды:
Example. The following token on an HTML document sets the SSI+ error
message to '*** ERROR ***'. From this point on down when an error occurs in the
SSI+ parsing engine the message '*** ERROR ***'will be inserted into the HTML
document at the location of the offending SSI+ statement.
Example. The following token on an HTML document sets the SSI+ error
action to print a message and terminate the document. From this point on down
when an error occurs in the SSI+ parsing engine the message will be inserted
into the HTML document at the location of the offending SSI+ statement, and the
document will be terminated
Example. Suppose you wish to create an HTML document that performs a
'PING' operation on address '204.96.64.171' and then echo the results back to
the client browser, with each line echoed as an element in an unnumbered list.
The if tag provides for conditional execution of SSI operations, and
conditional printing of HTML text, based on logical comparisons. The format of
the if tag is :
'if' '"'<operand1>'"' <operator>
'"'<operand2>'"'<operation>
where:
The operands may be any string or number (integer or floating point). In the
event that both operands are numbers the comparison will be based on the value
of the numbers. In the event that one or both of the operands and not numbers,
the comparison will be based on the alphabetic order of the operands.
The special case of the NULL operand is defined by two quotes with no
characters between them. The NULL operand may used to check for the existence of
form data from the remote client (see example below).
In the event that the logical comparison evaluates to FALSE, nothing happens,
If the logical comparison evaluates to TRUE then one of the following operations
may be performed:
Example. The following document fragment compares two numbers, if the
operands are not equal then a goto will jump to a label.
Example. The following document fragment demonstrates conditional
execution based on data delivered from an HTML form. Suppose we have two form
datum called 'formdata1' and 'formdata2' and we wish to compare them. The
following document fragment compares the two operands, if the operands are equal
then a goto will jump to a label. Otherwise the next line will print and the
document will terminate on a break token (see below).
Example. The following document fragment prints two different
statements depending on whether or not the client agent is NCSA Mosaic.
Example. Suppose we have a form with amongst other things a field
named "BOO" and we wish to make sure that the remote client user enterted data
into the "BOO" field before submitting the form. The following document fragment
checks for the presence of data in the "BOO" field, if data exists then nothing
happens, if data does not exist then a message will be displayed and the
document will terminate.
Команда goto оператор перехода на метку label.'include'
Пример: <!--#include virtual="include.txt"-->
Далее между двумя
горизонтальными чертами следут вставленный в документ файл
include.txt из текущей директории.
Начало вставки
Данный текст вставлен в документ из файла
iclude.txt
Конец вставки
Вид файла include.txt
fsize
Вывод размера файла в документ.
Команда имеет два
параметра-переменных:
Пример: <!--#fsize virtual="ssi.html"-->
Выдача размера файла, который
вы в данный момент читаете:
Размер файла ssi.html = 36k
'flastmod'
Команда имеет два параметра-переменных:
<!--#flastmod virtual="ssi.html"-->
Включение даты последней
модификации файла 'ssi.html' в документ:
Дата последней модификации
файла ssi.html = Thursday, 11-May-2000 22:00:37 NOVST.
'exec'
cmd="<exename> <argument list>"
где: <exename>
полное имя исполняемой программы или команды, и <argument list> список
аргументов, посылаемых исполняемой программе в командной
строке.
Замечание: на сервере должны быть заданы пути к исполняемой
программе в переменной окружения 'PATH'.
В случае отсутвия пути программу
можно запустить, используя shell или CGI Script. Стандартный вывод программы
направляется в HTML документ. Вывод может быть модифицирован командой 'config..cmdecho'.
cgi="<exename>"
где <exename> полное имя программы CGI
Script.
Стандартный вывод программы подставляется в документ.
'config' tag
'if'
'goto'
Формат
команды:
<!--#goto ="<label>"--> |
где <label> имя метки, определенное командой label.
Пример.
<!--#goto ="testlabel" --> <P>This line will not print. <!--#label ="testlabel" --> <P>This line will print.
Замечание: Между символами <!--#goto и знаком = обязательно должен стоять пробел.
Команда label устанавливает метку в документе, которая используется
командами goto или if..goto
Формат
команды:
<!--#label ="<label>"-->
где <label> строка из не более чем 51 символа без пробелов, идентифицирующая место в документе.
Задание метки не влияет на форматирование документа.
Замечание: Между символами <!--#label и знаком = обязательно должен стоять пробел.
Команда break останавливает вывод документа как только встречается.
Пример. Следующий документ демонстрирует работу команды break.
<P>This line will print. <!--#break --> <P>This line will not print because the document has been truncated and transmission to the client is terminated.
'odbc' | Обращение к внешней ODBC СУБД. |
'email' | Отправка электронной почты или представление формы. |
Notice! Due to some problems with the MS ODBC drivers we are phasing out the support of the SSI+ ODBC tags. To impliment ODBC with WebQuest we are using CScript with our WQODBC.DLL. For more information on CScript and ODBC, check out the Guestbook tutorial. The SSI+ ODBC tags will not exist in WebQuest 3.0.
The odbc tag provides for querying and updating odbc databases. Four variables are defined for the odbc token; 'debug', 'connect', 'statement', and 'format'.
The debug variable is used to set the SSI+ engine into debug mode. Debug mode provides diagnostics of a highly detailed nature from both the SSI engine itself and the local ODBC engine. Debug messages appear on the returned HTML document at the position at which the errors occur. The debug variable should be used only for development and must be removed before production. When the debug variable is present a warning message will appear indicating it's presence, this message is benign and will not affect any other aspect of the SSI+ engine. The format of the debug variable is : 'debug='"<debugstring>"' where;
The connect variable is used to connect to a pre-existing odbc data source, to allow for subsequent statement tag operations on that data source. The format of the connect variable is 'connect="'<datasource>','<username>','<password>'"'where ;
Example. To connect to a data source called 'odbcsht' as user 'dufus' and password 'dorkboy', one would use the following statement: <!--#odbc connect="odbcsht,dufus,dorkboy"-->.
The statement variable is used to submit a Transact SQL statement to the odbc data source. The format of a statement variable is as follows: 'statement="'<SQLStatement>'"',where:
Example. Suppose one wanted to query the 'CUSTOMERS' table from the above connected 'odbcsht' database to return all rows and display each row on a separate line. One may use the following sequence of statements:
The format variable is used to provide a template for the format of data that is returned from and odbc query. Use this variable to set up the appearance of data that will be returned from subsequent statement tag operations that return data from a database (i.e. the SQL statement 'SELECT'). The format of the format variable is 'format="'<cprintfstatement>'"'where;
Example. Suppose one wanted to query the 'CUSTOMERS' table from the above connected 'odbcsht' database to display the columns 'name', 'age', and 'viscosity' with each row on a separate line. One may use the following sequence of statements:
'email'
Отправка электронной почты.
Пример:
<!--#email tohost="www.ict.nsk.su" message="Thanks for the HTML" toaddress="www@www.ict.nsk.su" subject="The SSI"-->При отработке данного примера будет отправлено электронное письмо (e-mail), содержание которого задано атрибутом message, по адресу, определенному атрибутом toaddress, если данный адрес и host, заданный атрибутом tohost (данный атрибут может отсутствовать), реально существует.
The email tag provides for sending an Email whenever an HTML page is accessed or an HTML form submitted. The nature of the variables below is defined in RFC 733. The variables 'fromhost', 'tohost', 'fromaddress' and 'toaddress' are required, all others are optional.
Example. The following document send an email with debugging enabled. Supposewe have a form with datum : [First, Last, Middle Initial, Company,Address1, Address2, City, State, Zip, Country, Phone, Fax, Request,Urgency, ReplyMethod; Email, Subject, Message] we may post thatform to an HTML document containing the following fragment tosend an email.
Начало создания курса: Mondy, 19-Aug-1996 10:12:15 NOVST
Дата последней
модификации: Thursday, 11-May-2000 22:00:37 NOVST
© 1996 - 2001, А.М.Федотов
© 1996 - 2001, Институт
вычислительных технологий СО РАН, Новосибирск