Web Server Programming phần 10 ppt

54 283 0
Web Server Programming phần 10 ppt

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

' Lookup request method in the "servervariables" associative array req_method = request.servervariables("REQUEST_METHOD") if req_method = "GET" then ' Canned text defining submit form with its map input button %> <html><head><title>Hunger!</title></head> <body bgcolor=white> <form action=hunger.asp method=post> <table frame=border rules=all align=center> <caption>Desperate for a Big Mac?</caption> <tr> <td rowspan=2><input type=image src=iwol.jpg name=map></td> <td><img src=mac.jpg></td> </tr> <tr><th>Click on map</th></tr> </table> </form></body></html> <% ' Pick up with next part of scripting code, now test for "Post" method ' note the form of the equality test within the conditional elseif req_method = "POST" then ' If it is a post method, then output standard response text with a ‘ little dynamically generated insert obtained by invoking the findMac ‘ subroutine %> <html><head><title>Your nearest MacDonalds </title></head> <body> <h1 align=center>Your nearest MacDonalds</h1> <p align=center> <img src=mac.jpg> <p align=center style="font-size:24pt; color:blue"> <% dim x, y ' Pick up the map.x, map.y input data (the data take the image name ' with .x, and .y appended) x = request.form("map.x") y = request.form("map.y") ' Invoke the findMac function, it adds a line to the response call findMac(x,y) %> <p align=center> <img src=mac.jpg> <p> </body></html> <% ASP basics: ‘request’ and ‘response’ objects 553 else ' It is some unusual request method like Options, Head, Put, ' Ignore it %> <html><head><title>Error!</title></head> <body bgcolor=white> <p> Cannot handle requests of type <%= req_method %>. </body></html> <% end if ' Terminating if then elseif else construct that tests ‘ request method %> The example code shown, together with two image files ( the map, iwol.jpg,anda McDonald’s arches decorative image, mac.jpg), could be d eployed in a subdirectory Examples of the C:\Inetpub\wwwroot directory. The page can be accessed by pointing a browser at http://localhost/Examples/Hunger.asp. B.2 Adding ‘session state’ Real web application s invariably need to maintain client d ata. It is the same old HTTP pro- tocol underneath, so the same old hacks emerge for handling client state. If you have a limited and predefined set of u sers who will be accessing a site, you can use HTTP authen- tication to control a login sequence, and then in your ASP scripts you can access the REMOTE_USER server variable. The user identity can then serve as a filename, or a key for a temporary database table where state data can be maintain ed. (With IIS, this form of authentication integrates with the Windows NT user database; the accounts used by cli - ents must be Windows accounts defined by the administrator.) The login mechanism is fairly limited in its ran ge of applications; but the alternative of hidden fields in forms is always possible. Hidden fields have their limits; they only work when your state data are acquired through a sequence of forms that must be completed in succession, and the sup - posedly hidden data are actually quite open to view and modification. Where web site exploration is freer and hidden fields are inappropriate, application-specific cookies, whose values hold session data, may be used; but these have the same disadvantages of exposure and susceptibility to modification. The preferred solution is to use session variables in the server and cookies for user iden - tification. The ASP reference manual from Microsoft states: ASP provides a unique solution for the problem of managing session information. Using the ASP Session object and a special user ID generated by your server, you can create clever applications that identify each visiting user and collect in formation that your application can then use to track user preferences or selections. 554 Active Server Pages: ASP (scripting) Sessions, maintained in association with an automatically set user identification cookie, are enabled by default with ASP. When the first access is made to an ASP page in the site, the ASP interpreter in IIS will create a user identification cookie and a ‘session’ object associated with this cookie (the mechanism is identical to that used in servlet/JSP sys - tems). A session object can hold a collection of name/value pairs set by ASP scripts (much like a servlet session object’s ‘attribute’ collection). The automatically generated cookie is set to expire when the browser terminates; the associated IIS resident data structure is automatically garbage collected if left unused for a long period of time (default is about 30 minutes). An ASP script can discard the data structure as soon as the data processing is complete. The Session object: ● Owns: – Collections for ‘contents’ and ‘static objects’ (the ‘static objects’ collection migh t contain something like a database connection used on a per-session basis; ‘contents’ are name/value pairs set by application code). – Attributes for sessio n identifier, timeou t and ‘location’ (data similar to Java interna - tionalization information). ● Does: – ‘Abandon’: releases all session data at end of current script (rather than wait for timeout). – Contents.Remove, Contents.RemoveAll (clear specified item or all items in the con- tents collection) . One ASP page can place data into the contents collection of its associated session object; these data can then be picked up later by some other ASP page that gets accessed later. The following example is a reworking of the e-mart example used in Chapter 6 (see Figure 6.2). The PH P version illustrated the use of hidden form fields to hold name and address data; here, these data will be held in the session object. This web application consists of an Emart.asp page and a Page2.asp page. The Emart.asp page handles a g et request by displaying a form that allows users to enter their name, address, age group and sex. The data are posted back to the same Emart.asp page; the post request is handled by saving the name and address data (in the associated ses - sion’s contents collection) and the generation of a form with multiple checkboxes that allow selection of purchases. The data selected in this second form are posted to the Page2.asp page. The code on this page simply lists the selected purchase items, along with name and address data retrieved from the session object. The form’s appearance is essentially the same as the versions shown in Figur e 6.2. Although conceptually the Emart.asp page represents a single unit, its code is split among several files. The actual Emart.asp pages is: <% ' Determine request method dim req_method Adding ‘session state’ 555 req_method = request.servervariables("REQUEST_METHOD") if req_method = "GET" then %> <! #include file ="GetEMart.inc" > <% else %> <! #include file ="PostEMart.inc" > <% end if %> The page is essen tially a simple structu re: ‘if get request then generate first form else pro - cess input’. The details would obscure this structure, so they have been moved into sepa - rate include files. The GetEMart.inc include file contains simp ly static HTML: <html><head><title>e-Mart New Customer Page</title></head> <body> <h1 align=center>e-Mart New Customer Page</h1> <p> Please supply details so that we can select appropriate items from our great range of products. <form action=EMart.asp method=post> <table align=center border=2> <tr> <th align=left>Your name</th> <td><input type=text name=Name size=20></td> </tr> <tr> <th align=left>Your address</th> <td><textarea cols=20 rows=2 name=Address></textarea></td> </tr> <tr><th align=left>Your age</th> <td><select name=age size=1> <option value=kid>Less than 14 <option value=teenager>14-19 </select> </td> </tr> <tr> <td>Male<input type=radio name=sex checked value=Male></td> <td>Female<input type=radio name=sex value=Female></td> </tr> 556 Active Server Pages: ASP (scripting) <tr><td colspan=2 align=center><input type=submit value="Submit details"></td></tr> </table></form></body> The PostEmart.inc inclu de file contain s a mix of static HTML and VBScript code to generate a form with selected items. It relies on a further include file, EmartProducts.inc; it is this file that contains the data d efining the products that are available and provides a function that d etermines whether a product might suit a customer of a specific age group and sex. <! #include file ="EMartProducts.inc" > <html><head><title>Our products for you</title> </head><body> <h1 align=center> Products specially selected to appeal to you </h1> <% ' Check data from form Name = request.form("Name") Address= request.form("Address") Age= request.form("age") Sex= request.form("sex") if Name = "" then response.redirect("baddata.html") end if if Address = "" then response.redirect("baddata.html") end if ' Save data in session session.contents("Name") = Name session.contents("Address") = Address %> <form action=page2.asp method=post> <table align=center border=2> <caption>Some items of interest</caption> <% dim ndx for ndx=1 to numproducts dim ok ok = suits(ndx, Age, Sex) Adding ‘session state’ 557 if ok then %> <tr> <td><input type=checkbox name=purchase value="<%= title(ndx) %>" </td> <td align=left><%= title(ndx) %> </td> </tr> <% end if next %> <tr><td colspan=2 align=center><input type=submit value="Order now!"> </td></tr> </table></form></body></html> Input data are obtained from the request's ‘form’ collection. If a user fails to enter data in a required field, the VBScript code arranges for redirection to a simple error report page. If data were entered, the name and address information are saved in the session.contents collection. Then a loop is used to ad d tab le entries for suitable items to the purchase for m that is displayed . The details of products, and the function that checks their suitability for a client, are held in another include file: <% ' Arrays defining Emarts products ' (as in PHP example, this is just a simple exercise, ' a real application would get its data from a database) dim title(18) dim agegroup(18) dim gender(18) dim numproducts numproducts = 18 title(1) = "Playstation" agegroup(1) = "kid" gender(1) = "Either" title(2) = "Barbie doll" agegroup(2) = "kid" gender(2) = "Female" function suits(item, age, sex) 558 Active Server Pages: ASP (scripting) ' VBScript is similar to Pascal, the return value of a function ' is assigned to a variable with same name as function suits = (age = agegroup(item)) and ((gender(item) = "Either") or (gender(item) = sex)) end function %> Pages that involve lots of code and static HTML can be simplified through the use of include files (commo nly these are given the file extension .inc, but this is not manda - tory). If you do use .inc files, you should be careful to set your web server so that these are not available for download; smart hackers can guess filenames and simply submit download requests for script files and thereby gain details of your code (and hence iden - tify vulnerabilities). The final Page2.asp page has code that retrieves the session variables and lists the chosen purchases. The purchases are multi-choice items. The entry request.con - tents("purchase") becomes an array that can be accessed by the analysis code. The Count property of the array returns the number of elements defined; standard array subscripting can be used to access the individual purchase choices: <html><head><title>Listing input</title></head> <body> <h1 align=center>Listing all data received in form</h1> <% dim itemschosen itemschosen = request.form("purchase").Count if itemschosen = 0 then %> <p>Go back and buy something! <% else %> <ol> <% dim ndx forndx=1toitemschosen %> <li><%= request.form("purchase")(ndx) %> <% next %> </ol> <% end if %> <p> Adding ‘session state’ 559 Data received from: <br>Name : <%= session.contents("Name") %> <br>Address : <%= session.contents("Address") %> </body> </html> B.3 Database access The e-mart example in the last section is of cou rse a toy. Its data are predefined in arrays, and all it does is list the items chosen. A real web application would obtain the products data from a database, and store the user’s submitted order in some other database table. ASP naturally provides database access via ODBC and OLE DB (OLE DB is an extension of ODBC that can handle additional data sources apart from standard relational data - bases). A SP scripts can obtain a connection to an ODBC or OLE DB data source; a source that is a conventional relational database will handle the usual select, update, insert and delete SQL requests. Connections, and other components, can be obtained from the prede - fin ed Server object. The ASP Server object has a few properties and helper methods (e.g. a timeout value for a script, which helps avoid problems with buggy ASP script pages that have infinite loops, and methods for generating escaped HTML strings etc.). The Server’s main role is to act as a factory that can create additional components. Components include: ● A file access component (for reading and writing data files). ● A ‘browser capabilities’ component (holds details about the browser as obtained from the H TTP request headers; this may be useful if you need to generate complex dynamic HTML pages containing client-side JavaScript code that must be configured for dif- ferent browsers). ● A logging utility (accesses the IIS server logs). ● PageCounter, Counters, ‘Advertisement Rotator’ and ‘Content Rotator’: assorted utili - ties that help display changing advertisements and so forth. ● Database access component. The database access component is the most important. It combines parts of the roles that JDBC allocates to java.sql.Connection and java.sql.Statement objects. A data - base connection can be obtained to a chosen database, and can then be used to submit SQL query and update requests. Prototypical ODBC style code illustrating the acquisition and use of a database connec - tion is as f ollows: <% 'Ask for a database connection ' (Basic's "Let" keyword can be omitted from assignments like 560 Active Server Pages: ASP (scripting) ' "x = 3" – rather than "Let x= 3", but the keyword "Set" ' is required when assigning to pointer-like reference ' variables.) set db = Server.CreateObject("ADODB.Connection") ' Connect to database, the name – MyDatabase – is matched ' to the actual database via the ODBC Data Sources resource ' in the Control Panel Call db.Open("MyDatabase") ' Define query, standard sql constructs sql = "Select * from MyTable" ' Create object to store results Set resultset = Server.CreateObject("ADODB.Recordset") ' Run query on database Call resultset.Open(sql, db) ' Loop through result set generating rows of an HTML ' table from rows in resultset resultset.MoveFirst() while Not resultset.EOF %> ' Field names match column names in database table <tr> <th><%= resultset.Fields("Name").Value %></th> <th><%= resultset.Fields("Address").Value %></th> <th><%= resultset.Fields("City").Value %></th> <th><%= resultset.Fields("Postcode").Value %></th> </tr> <% Call resultset.MoveNext() WEND %> <% resultset.close db.close %> A database connection is created with the createObject request essentially sp ecifying the class of the object that is to be created. The actual connection to the database is made with the open call; the name in this call is the name of a ‘System DSN’ created using the ODBC Data Sources control in the Windows Control Panel. The example below uses Microsoft Access, which does not require account names and passwords. Account name and password data, as necessary for more sophisticated databases, can be included in the open call in the script or specified in the ODBC Data Sources record. The SQL request is defined as a string. Since this is a ‘select’ request, a RecordSet must be created to hold the response data; the Server object is again used to create the additional Database access 561 component. Once the query string, the database connection and the RecordSet for the response have all been created, the request can be run. The retrieved results can then be accessed as illustrated with the while loop structure. The following example is an ASP version of the E-Pal (email pen friend system) used as an illustration for database access with Perl. The database consists of a single table that holds records on people participating in the scheme; the table can be created directly in Microsoft Access’s design view, but conceptually it is defined by the following SQL: CREATE TABLE EPAL (email varchar(32) NOT NULL, type varchar(8) NOT NULL, want varchar(8) NOT NULL, interest1 number(4), interest2 number(4), interest3 number(4), interest4 number(4), interest5 number(4) ); Participants provide an email co ntact address, details of th eir own sex (male, female or ‘eperson’ for those who prefer not to reveal personal details too early), any requirements for gender of correspondent (male, female, eperson or any), and five interest numbers. These numbers represent interests picked from a fixed list. The database can be created, as epals.mdb,intheExamples directory within your wwwroot directory. The D ata Sources tool in the Control Panel should then be used to create an ODBC entry that references this database (e.g. ‘EpalDB’ – a ‘system DSN’ linkedtothe epals.mdb file). Note that a d atabase set up like this can be downloaded by visitors to your web site (try asking for http://localhost/Examples/epals.mdb!). As noted below, the administration tools used w ith IIS allow the setting of access restrictions on files; it is not a good idea to allow your database to be quite that readily accessed. A get operation on the EPAL.asp page results in the display of an app lication form (opposite); the form allows new members to join or existing members (and non-members) to run searches. The post operation returns the submitted data to the same EPAL.asp page. If the data represent a request to be added to the database, a new record is created. Otherwise a search is run against th e data table th at finds existing members with interests that overlap those of the suitor. Once again, the actual EPAL.asp page is made up from a number of separate include files, each file handling a particular aspect of the task. There is also a supporting Errors.asp page used to report problems like a user entering an email address that already exists as the key for an entry in the database table. The main EPAL.asp page is: <! #include file ="EPALInterests.inc" > <! #include file ="DoAdd.inc" > <! #include file ="DoSearch.inc" > 562 Active Server Pages: ASP (scripting) [...]... languages for server- side programming G Emphasis on the concept of integrated web services along with the provision of some frequently used components of a web service G An enterprise computing architecture comparable to that introduced in the chapter on EJBs The NET technology is aimed more at enterprise-level web applications than at the simple applications, with a client-side data entry form plus server- side... derived from Microsoft’s System .Web. UI.Page class (e.g MyNetPageClass) The aspx file declares 578 NET that it is defining a subclass of this class, and contains a link to the source file with the programmer’s class definition C.3 An example of the ‘new world order’ for web servers The following example illustrates something of the style of this new web browser to web server relationship The application... id="Form1" method="post" runat= "server" > An example of the ‘new world order’ for web servers 581 Arts Law . ' Lookup request method in the "servervariables" associative array req_method = request.servervariables("REQUEST_METHOD") if req_method = "GET". your server, you can create clever applications that identify each visiting user and collect in formation that your application can then use to track user preferences or selections. 554 Active Server. extension .inc, but this is not manda - tory). If you do use .inc files, you should be careful to set your web server so that these are not available for download; smart hackers can guess filenames and simply

Ngày đăng: 14/08/2014, 12:20

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan