計(jì)算機(jī)專業(yè)英文翻譯_第1頁
計(jì)算機(jī)專業(yè)英文翻譯_第2頁
計(jì)算機(jī)專業(yè)英文翻譯_第3頁
計(jì)算機(jī)專業(yè)英文翻譯_第4頁
計(jì)算機(jī)專業(yè)英文翻譯_第5頁
已閱讀5頁,還剩18頁未讀, 繼續(xù)免費(fèi)閱讀

下載本文檔

版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)

文檔簡(jiǎn)介

1、Using Scripting ElementsImplicit JSP Scripting ObjectsScripting elements can use predefined variables that the container assigns as references to implicit objects (Table 16-1) to access request and application data. These objects are instances of classes defined by the servlet and JSP specifications

2、. Appendix D contains complete descriptions of all methods for each class, and they are briefly introduced here and used in a number of examples in this chapter.Table 16-1. Implicit JSP objectsVariable nameJava typeapplicationjavax.servlet.ServletContextconfigjavax.servlet.ServletConfigexceptionjava

3、.lang.Throwableoutjavax.servlet.jsp.JspWriterpagejava.lang.ObjectpageContextjavax.servlet.jsp.PageContextrequestjavax.servlet.http.HttpServletRequestresponsejavax.servlet.http.HttpServletResponsesessionjavax.servlet.http.HttpSessionThese objects provide access to the same information (and more) as t

4、he implicit variables you can use in EL expressions, but its not a one-to-one match:pageContext The pageContext variable contains a reference to an instance of the class named javax.servlet.jsp.PageContext. It provides methods for accessing references to all the other objects and attributes for hold

5、ing data that is shared between components in the same page. Its the same object that you can access with the $pageContext EL expression. Attribute values for this object represent the page scope; they are the same objects as are available to the EL world as a Map represented by the $pageScope expre

6、ssion.request The request variable contains a reference to an instance of a class that implements an interface named javax.servlet.http.HttpServletRequest. It provides methods for accessing all the information thats available about the current request, such as request parameters, attributes, headers

7、, and cookies. Its the same object that you can access with the $pageContext.request EL expression. Attribute values for this object represent the request scope; they are the same objects as are available to the EL world as a Map represented by the $requestScope expression.response The response vari

8、able contains a reference to an object representing the current response message. Its an instance of a class that implements the javax.servlet.http.HttpServletResponse interface, with methods for setting headers and the status code, and adding cookies. It also provides methods related to session tra

9、cking. These methods are the response methods youre most likely to use. The same object can be accessed with the $pageContext.response EL expression.session The session variable allows you to access the clients session data, managed by the server. Its assigned a reference to an instance of a class t

10、hat implements the javax.servlet.http.HttpSession interface, which provides access to session data as well as information about the session, such as when it was created and when a request for the session was last received. Its the same object that you can access with the $pageContext.session EL expr

11、ession. Attribute values for this object represent the session scope; they are the same objects as are available to the EL world as a Map represented by the $sessionScope expression.application The application variable contains a reference to the instance of a class that implements the javax.servlet

12、.ServletContext interface that represents the application. This object holds references to other objects that more than one user may require access to, such as a database connection pool shared by all application users. It also contains log( ) methods you can use to write messages to the containers

13、log file. Its the same object that you can access with the $pageContext.servletContext EL expression. Attribute values for this object represent the application scope; they are the same objects as are available to the EL world as a Map represented by the $applicationScope expression.out The out obje

14、ct is an instance of javax.servlet.jsp.JspWriter. You can use the print( ) and println( ) methods provided by this object to add text to the response message body. In most cases, however, you will just use template text and JSP action elements instead of explicitly printing to the out object.excepti

15、on The exception object is available only in error pages and contains information about a runtime error. Its the same object that you can access with the $pageContext.exception EL expression.The remaining two implicit objects (config and page) are so rarely used in scripting elements that I dont dis

16、cuss them here. If youre interested, you can read about them in Appendix D.All variable names listed in Table 16-1 are reserved for the implicit object references. If you declare your own variables in a JSP page, you must not use these reserved variable names.Using ScriptletsThe scriptlet element ca

17、n be used to add a whole block of code to a page, including variable declarations. The code block must be enclosed by a scriptlet start-identifier, . Example 16-1 shows a scriptlet that creates test data for action elements.Example 16-1. Scriptlet creating test data (scriptlet.jsp) Search result: Au

18、thors Here are all authors matching your search critera: Name Id $fn:escapeXml() $fn:escapeXml(current.id) The scriptlet element contains Java code that creates a java.util.ArrayList with java.util.HashMap elements and saves the list as a page scope attribute named authors by calling the

19、 setAttribute( ) method on the implicit pageScope object. The ArrayList is then used as the items attribute value in a action. You can use a scriptlet like this to test the main page functionality before the real data source is available. In the final version, the scriptlet can be removed, and the d

20、ata passed to the page from another page or a servlet.Lets look at another example, in which the implicit request object is inquired about the current client type to display different messages depending on whether the Internet Explorer or Netscape Navigator browser is used. Example 16-2 shows the co

21、mplete page.Example 16-2. Browser dependent page (fragment.jsp) Browser Check Youre using Internet Explorer. Youre probably using Netscape. Youre using a browser I dont know about. The first scriptlet uses the getHeader( ) method of the request object to get the value of the User-Agent header. This

22、header contains a string with clues about the browser making the request. The header value is then used in a number of if statements to make an educated guess about the browser type and tell the user the result.Whats most interesting here is that a number of scriptlets are used, each one containing

23、only a fragment of a Java statement: An if statement, testing if the header contains MSIE, with a block start brace. The if block end brace and an else-if statement, testing if the header contains Mozilla, with its block start brace. The else-if block end brace, and a final else block start brace, h

24、andling the case when none of the strings are found. The final else block end brace.While none of the scriptlets by itself is a valid Java statement, the JSP container combines the fragments in the four scriptlets with code for writing the template text to the response body to form a valid statement

25、. The end result is that when the first if statement is true, Youre using Internet Explorer is displayed; when the second if statement is true, Youre probably using Netscape is displayed. If none of the if statements are true, the final else block is used, displaying Youre using a browser I dont kno

26、w about.The tricky part when using scriptlets like this is making sure that all the start and end braces are in place. If you miss just one of the braces, the code that the JSP container generates isnt syntactically correct. And, unfortunately, the error message that you get isnt easy to interpret.U

27、sing ExpressionsA JSP expression element is used to insert the result of a scripting code expression into the response. Its the Java scripting equivalent to an EL expression directly in template text. An expression starts with . Note that the only syntax difference compared to a scriptlet is the equ

28、al sign (=) in the start identifier. Examples are:The result of the expression is written to the response body, converted to a String if needed. One thing is important to note: as opposed to statements in a scriptlet, the code in an expression must not end with a semicolon. This is because the JSP c

29、ontainer combines the expression code with code for writing the result to the response body. If the expression ends with a semicolon, the combined code will not be syntactically correct.As with EL expressions, a Java expression can also be used to assign a dynamic value to an action element attribut

30、e, but with a few restrictions as described later in this chapter.Using DeclarationsI have described two of the three JSP scripting elements in this chapter so far: scriptlets and expressions. Theres one more called a declaration element, which is used to declare Java variables and methods in a JSP

31、page. My advice is this: dont use it. Let me explain why.In general, Java variables can be declared either within a method or outside the body of all methods in a class, like this:public class SomeClass / Instance variable private String anInstanceVariable; / Method public void doSomething( ) String

32、 aLocalVariable; A variable declared outside the body of all methods is called an instance variable. Its value can be accessed from any method in the class, and it keeps its value even when the method that sets it returns. A variable declared within the body of a method is called a local variable; i

33、t can be accessed only within the method where its declared. When the method returns, the local variable disappears.Recall from Chapter 3 that a JSP page is turned into a servlet class when its first requested, and the JSP container creates one instance of this class. If more than one user requests

34、the same page at the same time, the single instance is used for all requests. Each user is assigned what is called a thread in the server, and each thread executes the same method in the JSP implementation class instance. When more than one thread executes the same code, you have to make sure the co

35、de is thread safe. This means that the code must behave the same when many threads are executing as when just one thread executes the code.Multithreading and thread-safe code strategies are best left to experienced programmers. However, using a JSP declaration element to declare variables exposes yo

36、ur page to multithreading problems. Thats because a variable thats declared using a JSP declaration element ends up as an instance variable in the generated servlet, not as a local variable in a method. All threads share the instance variable, so if one thread changes its value, the new value is see

37、n by all threads. To put this in JSP terms, if the instance variable is changed because one user accesses the page, all users accessing the same page will use the new value.When you declare a variable within a scriptlet element instead of in a JSP declaration block, the variable ends up as a local v

38、ariable in the generated servlets request processing method. Each thread has its own copy of a local variable, so a local variable doesnt cause any problems even when more than one thread executes the same code. If the value of a local variable is changed, it will not affect the other threads.That b

39、eing said, lets look at a simple example. We use two int variables; one declared as an instance variable using a JSP declaration, and the other declared as a local variable with a scriptlet. We increment them both by one and display the new values. Example 16-3 shows the test page.Example 16-3. Usin

40、g a declaration element (counter.jsp) A page with a counter This page has been visited: times. This counter never increases its value: The JSP declaration element is right at the beginning of the page in Example 16-3, starting with . Note the exclamation point (!) in the start identifier; thats what

41、 makes it a declaration as opposed to a scriptlet. The declaration element declares an instance variable named globalCounter, shared by all requests for the page. In the page body, a JSP expression increments the variables value and adds it to the page. Next comes a scriptlet, enclosed by , that dec

42、lares a local variable named localCounter. It is then incremented and added to the page by the last expression element.When you run this example, the globalCounter value increases every time you load the page, but localCounter stays the same. Again, this is because globalCounter is an instance varia

43、ble, while localCounter is a local variable.In this example, nothing terribly bad happens if more than one user hit the page at the same time. The worst that could happen is that you skip a number or show the same globalCounter value twice. This can happen if two requests come in at the same time, a

44、nd both requests increment the value before its inserted in the response. You can imagine the consequences, however, if you use an instance variable to save something more important, such as a customers credit-card number or other sensitive information. So even though it may be tempting to create an

45、 instance variable (using a JSP declaration) to keep a value such as a counter between requests, I recommend that you stay away from this technique. Using objects in the session and application scopes, as described in Chapter 10, is a far better approach.A JSP declaration element can also be used to

46、 declare a method that can then be used in scriptlets in the same page. The only harm this can cause is that your JSP pages end up containing too much code, making it hard to maintain the application. I recommend that you use beans, custom actions, or EL functions instead, but to be complete, Exampl

47、e 16-4 shows an example of how it can be done.Example 16-4. Method declaration and use (color.jsp) Random Color Random Color table bgcolor=   The method named randomColor( ), declared between , returns a randomly generated String in a format that can be used as an HTML color value. This method

48、is then called from an expression element to set the background color for a table. Every time you reload this page, you see a single table cell with a randomly selected color.jspInit() and jspDestroy( )If you know a bit about servlets, you know that a servlet has two methods the container calls when the servlet is loaded and shut down, respectively. These methods are called init( ) and destroy( ), and they allow the servlet to initialize instance variables when its loaded and clean up when its shut down. As you already know, a JSP page is turned

溫馨提示

  • 1. 本站所有資源如無特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
  • 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
  • 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
  • 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
  • 5. 人人文庫網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
  • 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
  • 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。

評(píng)論

0/150

提交評(píng)論