1. Trang chủ
  2. » Công Nghệ Thông Tin

ColdFusion Developer’s Guide phần 3 pps

119 379 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 119
Dung lượng 0,91 MB

Nội dung

ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 227 Using application event handlers The following table briefly describes the application event CFC methods that you can implement, including when they are triggered. The following sections describe how to use these methods in more detail. When ColdFusion receives a request, it instantiates the Application CFC and runs the Application.cfc code in the following order: • CFC initialization code at the top of the file • onApplicationStart, if not run before for this application • onSessionStart, if not run before for this session • onRequestStart • onRequest, or the requested page if there is no onRequest method • onRequestEnd The following methods are triggered by specific events: • onApplicationEnd • onSessionEnd • onMissingTemplate • onError The onApplicationEnd and onSessionEnd methods do not execute in the context of a page request, so they cannot access request variables or display information to the user. The onMissingTemplate method is triggered when a URL specifies a CFML page that does not exist. The OnError method does not always execute in the context of a request; you can use its Event argument to determine the context. Method When run onApplicationStart The application first starts: when the first request for a page is processed or the first CFC method is invoked by an event gateway instance, Flash Remoting request, or a web service invocation. This method is useful for setting application-wide (Application scope) variables, such as the names of data sources. onApplicationEnd The application ends: when the application times out or the server shuts down. onSessionStart A new session is created as a result of a request that is not in an existing session, including ColdFusion event gateway sessions. The application must enable sessions for this event to happen. onSessionEnd A session time-out setting is reached. This event is not triggered when the application ends or the server shuts down. onRequestStart ColdFusion receives any of the following: a request, an HTTP request (for example, from a browser), a message to an event gateway, a SOAP request, or a Flash Remoting request. onRequest The onRequestStart event has completed. This method can act as a filter for the requested page content. onRequestEnd All pages and CFCs in the request have been processed: equivalent to the OnRequestEnd.cfm page. onMissingTemplate When ColdFusion receives a request for a nonexistent page. onError When an exception occurs that is not caught by a try/catch block. ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 228 Managing the application with Application.cfc You use the onApplicationStart and onApplicationEnd methods to configure and manage the application; that is, to control resources that are used by multiple pages and requests and must be consistently available to all code in your application. Such resources can include data sources, application counters such as page hit variables, or style information for all pages. The onApplicationStart method executes when ColdFusion gets the first request for a page in the application after the server starts. The onApplicationEnd method executes when the application server shuts down or if the application is inactive for the application time-out period. The following sections describe some of the ways you can use these methods. For more information, see entries for onApplicationStart and onApplicationEnd in the CFML Reference. Defining application utility functions Functions that you define in Application.cfc and do not put in a shared scope are, by default, available only to other methods in the CFC. If your Application.cfc implements the onRequest method, any utility functions that you define in Application.cfc are also directly available in to the target page, because Application.cfc and the target page share the Variables scope. If your application requires utility functions that are used by multiple pages, not just by the methods in Appli- cation.cfc, and you do not use an onRequest method, Adobe recommends that you put them in a separate CFC and access them by invoking that CFC. As with other ColdFusion pages, Application.cfc can access any CFC in a directory path that is configured on the ColdFusion Administrator Mappings page. You can, therefore, use this technique to share utility functions across applications. If your Application.cfc defines utility functions that you want available on request pages and does not use an onRequest method, you must explicitly put the functions in a ColdFusion scope, such as the Request scope, as the following code shows: <cffunction name="theFunctionName" returntype="theReturnType"> <! Function definition goes here. > </cffunction> <cffunction name="OnRequestStart"> <! OnRequestStart body goes here > <cfset Request.theFunctionName=This.theFunctionName> </cffunction> On the request page, you would include the following code: <cfset myVar=Request.theFunctionName(Argument1 )> Functions that you define in this manner share the This scope and Variables scope with the Application.cfc file for the request. Setting application default variables and constants in onApplicationStart You can set default variables and application-level constants in Application.cfc. For example, you can do the following: • Specify a data source and ensure that it is available • Specify domain name • Set styles, such as fonts or colors • Set other application-level variables ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 229 You do not have to lock Application scope variables when you set them in the Application.cfc onApplicationStart method. For details on implementing the onApplicationStart method, see onApplicationStart in the CFML Reference. Using the onApplicationEnd method Use the onApplicationEnd method for any clean-up activities that your application requires when it shuts down, such as saving data in memory to a database, or to log the application end. You cannot use this method to display data on a user page, because it is not associated with any request. The application ends, even if this method throws an exception. An application that is used often is unlikely to execute this method, except when the server is shut down. For details on implementing the onApplicationEnd method, see onApplicationEnd in the CFML Reference. Managing sessions in Application.cfc You u s e t h e onSessionStart and onSessionEnd methods to configure and manage user sessions; that is, to control resources that are used by multiple pages while a user is accessing your site from during a single browser session. The session begins when a user first requests a page in your application, and ends when the session times out. For more information on Session scope and Session variables, see “Using Persistent Data and Locking” on page 272. Session resources include variables that store data that is needed throughout the session, such as account numbers, shopping cart contents, or CFCs that contain methods and data that are used by multiple pages in a session. Note: Do not put the cflogin tag or basic login processing in the onSessionStart method, as the code executes only at the start of the session; it cannot handle user logouts, and cannot fully ensure security. The following sections describe some of the ways you can use the onSessionStart and onSessionEnd methods. For more information, see the onSessionStart and onSessionEnd entries in the CFML Reference. Using the onSessionStart method This method is useful for initializing session data, such as user settings or shopping cart contents, or for tracking the number of active sessions. You do not need to lock the Session scope when you set session variables in this method. Using the onSessionEnd method Use this method for any clean-up activities when the session ends. (For information on ending sessions, see “Ending a session” on page 286.) You can, for example, save session-related data, such as shopping cart contents or infor- mation about whether the user has not completed an order, in a database, or you can log the end of the session to a file. You cannot use this method to display data on a user page, because it is not associated with a request. Note: Sessions do not end, and the onSessionEnd method is not called when an application ends. For more infor- mation, see the onSessionEnd entry in the CFML Reference. Managing requests in Application.cfc ColdFusion provides three methods for managing requests: onRequestStart, onRequest, and onRequestEnd. ColdFusion processes requests, including these methods, as follows: 1 ColdFusion always processes onRequestStart at the start of the request. 2 If you implement an onRequest method, ColdFusion processes it; otherwise, it processes the requested page. If you implement an onRequest method, you must explicitly call the requested page in your onRequest method. 3 ColdFusion always processes onRequestEnd at the end of the request. ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 230 The following sections explain how you can use each of the Application.cfc request methods to manage requests. For more information, see entries for onRequestStart, onRequest, and onRequestEnd in the CFML Reference. Using the onRequestStart method This method runs at the beginning of the request. It is useful for user authorization (login handling), and for request- specific variable initialization, such as gathering performance statistics. If you use the onRequestStart method and do not use the onRequest method, ColdFusion automatically processes the request when it finishes processing the onRequestStart code. Note: If you do not include an onRequest method in Application.cfm file, the onRequestStart method does not share a Variables scope with the requested page, but it does share Request scope variables. User authentication When an application requires a user to log in, put the authentication code, including the cflogin tag or code that calls this tag, in the onRequestStart method. Doing so ensures that the user is authenticated at the start of each request. For detailed information on security and creating logins, see “Securing Applications” on page 311 For an example that uses authentication code generated by the Adobe Dreamweaver CF Login Wizard, see onRequestStart in the CFML Reference. Using the onRequest method The onRequest method differs from the onRequestStart method in one major way: the onRequest method inter- cepts the user’s request. This difference has two implications: • ColdFusion does not process the request unless you explicitly call it, for example, by using a cfinclude tag. This behavior lets you use the onRequest method to filter requested page content or to implement a switch that deter- mines the pages or page contents to be displayed. • When you use cfinclude to process request, the CFC instance shares the Variables scope with the requested page. As a result, any method in the CFC that executes can set the page’s Variables scope variables, and the onRequestEnd method can access any Variable scope values that the included page has set or changed. Therefore, for example, the onRequestStart or onRequest method can set variables that are used on the page. To use this method as a filter, put the cfinclude tag inside a cfsavecontent tag, as the following example shows: <cffunction name="onRequest"> <cfargument name = "targetPage" type="String" required=true/> <cfsavecontent variable="content"> <cfinclude template=#Arguments.targetPage#> </cfsavecontent> <cfoutput> #replace(content, "report", "MyCompany Quarterly Report", "all")# </cfoutput> </cffunction> Using the onRequestEnd method You use the onRequestEnd method for code that should run at the end of each request. (In ColdFusion versions through ColdFusion MX 6.1, you would use the OnRequestEnd.cfm page for such code.) Typical uses include displaying dynamic footer pages. For an example, see onSessionEnd in the CFML Reference. Note: If you do not include an onRequest method in Application.cfm file, the onRequestEnd method does not share a Variables scope with the requested page, but it does share Request scope variables. ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 231 Handling errors in Application.cfc The following sections briefly describe how you can handle errors in Application.cfc. For more information on error pages and error handling, see “Handling Errors” on page 246 For details on implementing the onError method, see onError in the CFML Reference. Application.cfc error handling techniques Application.cfc can handle errors in any combination of the following ways: • You can use try/catch error handling in the event methods, such as onApplicationStart or onRequestStart, to handle exceptions that happen in the event methods. • You can implement the onError method. This method receives all exceptions that are not directly handled by try/catch handlers in CFML code. The method can use the cfthrow tag to pass any errors it does not handle to ColdFusion for handling. • You c a n us e cferror tags in the application initialization code following the cfcomponent tag, typically following the code that sets the application’s This scope variables. These tags specify error processing if you do not implement an onError method, or if the onError method throws an error. You could implement an application- specific validation error handler, for example, by putting the following tag in the CFC initialization code: <cferror type="VALIDATION" template="validationerrorhandler.cfm"> 1 The ColdFusion default error mechanisms handle any errors that are not handled by the preceding techniques. These mechanisms include the site-wide error handler that you can specify in the ColdFusion Administrator and the built-in default error pages. These techniques let you include application-specific information, such as contact information or application or version identifiers, in the error message, and let you display all error messages in the application in a consistent manner. You can use Application.cfc to develop sophisticated application-wide error-handling techniques, including error-handling methods that provide specific messages, or use structured error-handling techniques. Note: The onError method can catch errors that occur in the onSessionEnd and onApplicationEnd application event methods. It will not display messages to the user, however, because there is no request context. The onError function can log errors that occur when the session or application ends. Handling server-side validation errors in the onError method Server-side validation errors are actually ColdFusion exceptions; as a result, if your application uses an onError method, this method gets the error and must handle it or pass it on to ColdFusion for handling. To identify a server-side validation error, search the Arguments.Exception.StackTrace field for coldfusion.filter.FormValidationException. You can then handle the error directly in your onError routine, or throw the error so that either the ColdFusion default validation error page or a page specified by an cferror tag in your Application.cfc initialization code handles it. Example: error Handling with the onError method The following Application.cfc file has an onError method that handles errors as follows: • If the error is a server-side validation error, the onError method throws the error for handling by ColdFusion, which displays its standard validation error message. • For any other type of exception, the onError method displays the name of the event method in which the error occurred and dumps the exception information. In this example, because you generate errors on the CFM page only, and not in a Application.cfc method, the event name is always the empty string. <cfcomponent> <cfset This.name = "BugTestApplication"> ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 232 <cffunction name="onError"> <! The onError method gets two arguments: An exception structure, which is identical to a cfcatch variable. The name of the Application.cfc method, if any, in which the error happened. <cfargument name="Except" required=true/> <cfargument type="String" name = "EventName" required=true/> <! Log all errors in an application-specific log file. > <cflog file="#This.Name#" type="error" text="Event Name: #Eventname#" > <cflog file="#This.Name#" type="error" text="Message: #except.message#"> <! Throw validation errors to ColdFusion for handling. > <cfif Find("coldfusion.filter.FormValidationException", Arguments.Except.StackTrace)> <cfthrow object="#except#"> <cfelse> <! You can replace this cfoutput tag with application-specific error-handling code. > <cfoutput> <p>Error Event: #EventName#</p> <p>Error details:<br> <cfdump var=#except#></p> </cfoutput> </cfif> </cffunction> </cfcomponent> To test this example, put a CFML page with the following code in the same page as the Application.cfc file, and enter valid and invalid text in the text input field. <cfform> This box does Integer validation: <cfinput name="intinput" type="Text" validate="integer" validateat="onServer"><br> Check this box to throw an error on the action page: <cfinput type="Checkbox" name="throwerror"><br> <cfinput type="submit" name="submitit"> </cfform> <cfif IsDefined("form.fieldnames")> <cfif IsDefined("form.throwerror")> <cfthrow type="ThrownError" message="This error was thrown from the bugTest action page."> <cfelseif form.intinput NEQ ""> <h3>You entered the following valid data in the field</h3> <cfoutput>#form.intinput#</cfoutput> </cfif> </cfif> Note: For more information on server-side validation errors, see “Validating Data” on page 553. Example: a complete Application.cfc The following example is a simplified Application.cfc file that illustrates the basic use of all application event handlers: <cfcomponent> <cfset This.name = "TestApplication"> <cfset This.Sessionmanagement=true> <cfset This.Sessiontimeout="#createtimespan(0,0,10,0)#"> <cfset This.applicationtimeout="#createtimespan(5,0,0,0)#"> <cffunction name="onApplicationStart"> <cftry> ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 233 <! Test whether the DB that this application uses is accessible by selecting some data. > <cfquery name="testDB" dataSource="cfdocexamples" maxrows="2"> SELECT Emp_ID FROM employee </cfquery> <! If we get database error, report it to the user, log the error information, and do not start the application. > <cfcatch type="database"> <cfoutput> This application encountered an error.<br> Please contact support. </cfoutput> <cflog file="#This.Name#" type="error" text="cfdocexamples DB not available. message: #cfcatch.message# Detail: #cfcatch.detail# Native Error: #cfcatch.NativeErrorCode#"> <cfreturn False> </cfcatch> </cftry> <cflog file="#This.Name#" type="Information" text="Application Started"> <! You do not have to lock code in the onApplicationStart method that sets Application scope variables. > <cfscript> Application.availableResources=0; Application.counter1=1; Application.sessions=0; </cfscript> <! You do not need to return True if you don't set the cffunction returntype attribute. > </cffunction> <cffunction name="onApplicationEnd"> <cfargument name="ApplicationScope" required=true/> <cflog file="#This.Name#" type="Information" text="Application #ApplicationScope.applicationname# Ended"> </cffunction> <cffunction name="onRequestStart"> <! Authentication code, generated by the Dreamweaver Login Wizard, makes sure that a user is logged in, and if not displays a login page. > <cfinclude template="mm_wizard_application_include.cfm"> <! If it’s time for maintenance, tell users to come back later. > <cfscript> if ((Hour(now()) gt 1) and (Hour(now()) lt 3)) { WriteOutput("The system is undergoing periodic maintenance. Please return after 3:00 AM Eastern time."); return false; } else { this.start=now(); } </cfscript> </cffunction> <cffunction name="onRequest"> <cfargument name = "targetPage" type="String" required=true/> <cfsavecontent variable="content"> <cfinclude template=#Arguments.targetPage#> </cfsavecontent> <! This is a minimal example of an onRequest filter. > <cfoutput> #replace(content, "report", "MyCompany Quarterly Report", "all")# ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 234 </cfoutput> </cffunction> <! Display a different footer for logged in users than for guest users or users who have not logged in. > <cffunction name="onRequestEnd"> <cfargument type="String" name = "targetTemplate" required=true/> <cfset theAuthuser=getauthuser()> <cfif ((theAuthUser EQ "guest") OR (theAuthUser EQ ""))> <cfinclude template="noauthuserfooter.cfm"> <cfelse> <cfinclude template="authuserfooter.cfm"> </cfif> </cffunction> <cffunction name="onSessionStart"> <cfscript> Session.started = now(); Session.shoppingCart = StructNew(); Session.shoppingCart.items =0; </cfscript> <cflock timeout="5" throwontimeout="No" type="EXCLUSIVE" scope="SESSION"> <cfset Application.sessions = Application.sessions + 1> </cflock> <cflog file="#This.Name#" type="Information" text="Session: #Session.sessionid# started"> </cffunction> <cffunction name="onSessionEnd"> <cfargument name = "SessionScope" required=true/> <cflog file="#This.Name#" type="Information" text="Session: #arguments.SessionScope.sessionid# ended"> </cffunction> <cffunction name="onError"> <cfargument name="Exception" required=true/> <cfargument type="String" name = "EventName" required=true/> <! Log all errors. > <cflog file="#This.Name#" type="error" text="Event Name: #Eventname#"> <cflog file="#This.Name#" type="error" text="Message: #exception.message#"> <! Some exceptions, including server-side validation errors, do not generate a rootcause structure. > <cfif isdefined("exception.rootcause")> <cflog file="#This.Name#" type="error" text="Root Cause Message: #exception.rootcause.message#"> </cfif> <! Display an error message if there is a page context. > <cfif NOT (Arguments.EventName IS onSessionEnd) OR (Arguments.EventName IS onApplicationEnd)> <cfoutput> <h2>An unexpected error occurred.</h2> <p>Please provide the following information to technical support:</p> <p>Error Event: #EventName#</p> <p>Error details:<br> <cfdump var=#exception#></p> </cfoutput> </cfif> </cffunction> </cfcomponent> ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 235 Migrating from Application.cfm to Application.cfc To migrate an existing application that uses Application.cfm to one that uses Application.cfc, do the following: • Replace the cfapplication tag with CFC initialization code that sets the Application.cfc This scope variables that correspond to the tag attributes. • Put in the onApplicationStart method any code that initializes Application scope variables, and any other application-specific code that executes only when the application starts. Often, such code in Application.cfm is inside a block that tests for the existence of an Application scope switch variable. Remove the variable test and the Application scope lock that surrounds the code that sets the Application scope variables. • Put in the onSessionStart method any code that initializes Session scope variables, and any other application- specific code that executes only when the session starts. Remove any code that tests for the existence of Session scope variables to be for initialized and the Session scope lock that surrounds the code that sets the Session scope variables. • Put in the onRequestStart method any cflogin tag and related authentication code. • Put in the onRequest method any code that sets Variables scope variables and add a cfinclude tag that includes the page specified by the method’s Arguments.Targetpage variable. • Put in the onRequestEnd method any code you have in an OnRequestEnd.cfm page. • Consider replacing cferror tags with an onError event method. If you do not do so, put the cferror tags in the CFC initialization code. Using an Application.cfm page If you do not use an Application.cfc file, you can use the Application.cfm page to define application-level settings and functions. Naming the application Use the cfapplication tag to specify the application name and define a set of pages as part of the same logical appli- cation. Although you can create an application by putting a cfapplication tag with the application name on each page, you normally put the tag in the Application.cfm file; for example: <cfapplication name="SearchApp"> Note: The value that you set for the name attribute in the cfapplication tag is limited to 64 characters. Setting the client, application, and session variables options Use the cfapplication tag to specify client state and persistent variable use, as follows: • To use Client scope variables, you must specify clientManagement=True. • To use Session scope variables, you must specify sessionManagment=True. You can also optionally do the following: • Set application-specific time-outs for Application and Session scope variables. These settings override the default values set in the ColdFusion Administrator. • Specify a storage method for Client scope variables. This setting overrides the method set in the ColdFusion Administrator. ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 236 • Specify not to use cookies on the client browser. For more information on configuring these options, see “Using Persistent Data and Locking” on page 272 and the CFML Reference. Defining page processing settings The cfsetting tag lets you specify page processing attributes that you might want to apply to all pages in your appli- cation. For more information, see “Setting page processing options” on page 226. Setting application default variables and constants You can set default variables and application-level constants on the Application.cfm page. For example, you can specify the following values: • A data source • A domain name • Style settings, such as fonts or colors • Other important application-level variables Often, an Application.cfm page uses one or more cfinclude tags to include libraries of commonly used code, such as user-defined functions, that are required on many of the application’s pages. Processing logins When an application requires a user to log in, you typically put the cflogin tag on the Application.cfm page. For detailed information on security and creating logins, including an Application.cfm page that manages user logins, see “Securing Applications” on page 311 Handling errors You can use the cferror tag on your Application.cfm page to specify application-specific error-handling pages for request, validation, or exception errors, as shown in the example in the following section. This way you can include application-specific information, such as contact information or application or version identifiers, in the error message, and you display all error messages in the application in a consistent manner. For more information on error pages and error handling, see “Handling Errors” on page 246. Example: an Application.cfm page The following example shows a sample Application.cfm file that uses several of the techniques typically used in Application.cfm pages. For the sake of simplicity, it does not show login processing; for a login example, see “Securing Applications” on page 311. <! Set application name and enable Client and Session variables. > <cfapplication name="Products" clientmanagement="Yes" clientstorage="myCompany" sessionmanagement="Yes"> <! Set page processing attributes. > <cfsetting showDebugOutput="No"> <! Set custom global error handling pages for this application > [...]... Administering ColdFusion For information on debugging techniques that can help you identify slow pages, see “Debugging and Troubleshooting Applications” on page 35 1 For additional information on optimizing ColdFusion, see the Adobe ColdFusion support center at www.adobe.com/go/support /coldfusion ADOBE COLDFUSION 8 239 ColdFusion Developer’s Guide Caching ColdFusion pages that change infrequently Some ColdFusion. .. RS1> ADOBE COLDFUSION 8 2 43 ColdFusion Developer’s Guide The output param value: '#foo#' The Results Information . its function: ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 238 Optimizing ColdFusion applications You can optimize your ColdFusion application in many ways. Optimizing ColdFusion mostly involves. used in most pages in the application. ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 239 Caching ColdFusion pages that change infrequently Some ColdFusion pages produce output that changes. Application.productCache vari- able. Code Description ADOBE COLDFUSION 8 ColdFusion Developer’s Guide 2 43 <cfprocresult name = RS3 resultSet = 3& gt; <! cfprocparam tags > <cfprocparam type

Ngày đăng: 14/08/2014, 10:22

TỪ KHÓA LIÊN QUAN