1. Write CGI
The simple CGI program is as follows:
#! / usr / bin / env ruby print "http / 1.0 200 okrn" Print "Content-Type: Text / htmlrnrn" Print "Hello World! RN"
We can use ruby to handle the submitted parameters, fill the template, generate HTML, but a little troubles, you can use the CGI module.
2. Use cgi.rb
CGI.rb is used to write CGI scripts, and he can operate Form, cookies, environment variables, maintenance session, and so on. Specific usage, you should know where to find it.
3. Quote and escape
/ In the URL is a special character, as well as
Require 'cgi' Puts cgi.escape ("Nicholas Payton / Trumpet & Flugel Horn")
produces result:
Nicholas payton% 2Ftrumpet % 26 Flugel Horn
Examples of the elements in the HTML document (omitted):
4. Form form
Class CGI can obtain data submitted by two methods. Join the user to submit look? Player = tom & year = 1958, we can use the CGI [] array to access it directly.
Require 'cgi' cgi = cgi.new cgi ['Player'] # -> ["Tom"] CGI ['Year'] # -> ["1958"]
Another way is to use a Hash table to get all parameters and values.
Require 'cgi' cgi = cgi.new h = cgi.Params h ['player'] # -> ["Tom"]
5. Generate Form and HTML
The CGI class provides a lot of methods for generating HTML, almost a method of each tag. Still examples come intuitive:
Require "CGI" cgi = cgi.new ("html3") # add html generation methods cgi.out {cgi.html {cgi.Head {"n" cgi.title {"this is a test"}} CGI. Body {"n" cgi.form {"n" cgi.hr cgi.h1 {"a form:"} "n" cgi.textarea ("get_text") "n" cgi.br CGI.submit}}}}
Generate the following code:
6. cookies
Require "CGI" cookie = cgi :: cookie.new ("Rubyweb", "Custid = 123", "part = ABC"); cgi = cgi.new ("html3") cgi.out ("cookie" => The head produced by cookie]) {cgi.html {"nhtml content here"}} is as follows:
Content-type: text / htmlcontent-length: 86set-cookie: Rubyweb = CUSTID% 3D123 & Part% 3DABC; PATH =
Then, when the user accesses the page, you can read this value.
Require "CGI" cgi = cgi.new ("html3") cgi.out {cgi.html {cgi.pre {cookie = cgi.cookies ["rubyweb"] "ncookies am" cookie.value.join ("n" }}
7. sessions
Treatment session requires extra class: CGI :: session
Require "CGI" Require "CGI / Session"
CGI = cgi.new ("html3") sess = cgi :: session.new (cgi, "session_key" => "rubyweb", "session_id" => "9650", "new_session" => true, "prefix" = > "Web-session.") Sess ["Custid"] = 123 sess ["part"] = "abc"
Cgi.out {cgi.html {"nhtml content here"}}
Reading Session passed the following code:
Require "CGI" Require "CGI / Session"
CGI = cgi.new ("html3") sess = cgi :: session.new (cgi, "session_key" => "rubyweb", "prefix" => "Web-session.") cgi.out {cgi.html { "NCUSTOMER # {sess ['Custid']} ORDERS AN # {sess ['part']}}}