Tai lieu jsp

Document Sample
Tai lieu jsp
Description

T�i liệu về jsp rất hay

Shared by: long nguyen
Stats
views:
491
posted:
6/6/2009
language:
Vietnamese
pages:
78
Web Programming with Java



Java Server Pages



Huynh Huu Viet University of Information Technology Department of Information Systems Email: viethh@uit.edu.vn



1



Outline Introduction Scripting Elements The JSP page Directive Including Files Using JavaBeans Components in JSP Servlets and JSP: The Model View Controller (MVC) Architecture

2008 © Department of Information Systems - University of Information Technology 2



The Need for JSP

With servlets, it is easy to Read form data Read HTTP request headers Set HTTP status codes and response headers Use cookies and session tracking Share data among servlets Remember data between requests Get fun, high-paying jobs But, it sure is a pain to Use those println statements to generate HTML Maintain that HTML

2008 © Department of Information Systems - University of Information Technology 3



JSP Framework

Idea: Use regular HTML for most of page Mark servlet code with special tags Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request) Example



2008 © Department of Information Systems - University of Information Technology



4



Benefits of JSP

Although JSP technically can't do anything servlets can't do, JSP makes it easier to: Write HTML Read and maintain the HTML JSP makes it possible to: Use standard HTML tools such as Macromedia DreamWeaver or Adobe GoLive. Have different members of your team do the HTML layout than do the Java programming JSP encourages you to Separate the (Java) code that creates the content from the (HTML) code that presents it

2008 © Department of Information Systems - University of Information Technology 5



Advantages of JSP Over Competing Technologies (1)



Versus ASP or ColdFusion Better language for dynamic part Portable to multiple servers and operating systems Versus PHP Better language for dynamic part Better tool support Versus pure servlets More convenient to create HTML Can use standard tools (e.g., DreamWeaver) Divide and conquer JSP programmers still need to know servlet programming

2008 © Department of Information Systems - University of Information Technology 6



Advantages of JSP Over Competing Technologies (2)



Versus client-side JavaScript (in browser) Capabilities mostly do not overlap with JSP, but

• You control server, not client • Richer language



Versus server-side JavaScript (e.g., LiveWire, BroadVision) Richer language Versus static HTML Dynamic features Adding dynamic features no longer"all or nothing" decision

2008 © Department of Information Systems - University of Information Technology 7



Example



JSP Expressions





JSP Expressions Current time: Server: Session ID: The testParam form parameter:







2008 © Department of Information Systems - University of Information Technology



8



JSP Lifecycle



2008 © Department of Information Systems - University of Information Technology



9



JSP/Servlets in the Real World

Ten most popular Web sites [1] 1) Google

• Custom technology,some Java Web pages using JSP [2] 568 million Most popular languages worldwide [3] Java C/C++ Visual Basic PHP Python C#



2) Yahoo

• PHP and Java



3) MySpace

• ColdFusion (Java “under the hood”)



4) YouTube

• Flash, Python, Java



9) Ebay

• Java



10) AOL

• Java



[1]: reported by alexis.com, Fall 2008 [2]:reported by Google [3]: reported by tiobe.com

10



2008 © Department of Information Systems - University of Information Technology



Some webpages using JSP Airlines American Airlines British Airways United Airlines Financial Services Bank of America NY Stock Exchange Royal Bank of Scotland

Entertainment Billboard.com WarnerBrothers.com Military and Federal Government CIA NSA Army Search/Portals Parts of Google All of Ebay Paypal

11



2008 © Department of Information Systems - University of Information Technology



Outline Introduction Scripting Elements The JSP page Directive Including Files Using JavaBeans Components in JSP Servlets and JSP: The Model View Controller (MVC) Architecture

2008 © Department of Information Systems - University of Information Technology 12



Uses of JSP Constructs

Simple Application

Scripting elements calling servlet code directly Scripting elements calling servlet code indirectly (by means of utility classes) Beans Servlet/JSP combo (MVC) MVC with JSP expression language Custom tags MVC with beans, custom tags, and a framework like Struts or JSF



Complex Application



2008 © Department of Information Systems - University of Information Technology



13



Design Strategy: Limit Java code in JSP Pages



You have two options Put 25 lines of Java code directly in the JSP page Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it Why is the second option much better? Development. You write the separate class in a Javaenvironment (editor or IDE), not an HTML environment Debugging. If you have syntax errors, you see themimmediately at compile time. Simple print statements can be seen. Testing. You can write a test routine with a loop that does 10,000 tests and reapply it after each change. Reuse. You can use the same class from multiple pages.

2008 © Department of Information Systems - University of Information Technology 14



Basic Syntax

HTML Text Blah Passed through to client. Really turned into servlet code that looks like

• out.print("Blah");



HTML Comments Same as other HTML: passed through to client JSP Comments Not sent to client Escaping Evaluated and inserted into the servlet’s output. I.e., results in something like out.print(expression) Scriptlets Format: Inserted verbatim into the servlet’s _jspService method (called by service) Declarations Format: Inserted verbatim into the body of the servlet class, outside of any existing methods XML syntax See slides at end of the lecture for an XML-compatible way of representing JSP pages and scripting elements

16



2008 © Department of Information Systems - University of Information Technology



JSP Expressions

Format Result Expression evaluated, converted to String, and placed into HTML page at the place it occurred in JSP page That is, expression placed in _jspService inside out.print Examples Current time: Your hostname: XML-compatible syntax Java Expression You cannot mix versions within a single page You must page. use XML for entire page if you use jsp:expression.

• See slides at end of this lecture



2008 © Department of Information Systems - University of Information Technology



17



JSP/Servlet Correspondence

Original JSP A Random Number Representative resulting servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {



response.setContentType("text/html"); HttpSession session = request.getSession(); JspWriter out = response.getWriter(); out.println("A Random Number"); out.println(Math.random()); ... }

2008 © Department of Information Systems - University of Information Technology 18



Predefined Variables

request The HttpServletRequest (1st argument to service/doGet) response The HttpServletResponse (2nd arg to service/doGet) out The Writer (a buffered version of type JspWriter) used to send output to the client session The HttpSession associated with the request (unless disabled with the session attribute of the page directive) application The ServletContext (for sharing data) as obtained via getServletContext().

2008 © Department of Information Systems - University of Information Technology 19



Comparing Servlets to JSP

Reading Three Request Parameters Reading Three Request Parameters param1: param2: param3:

2008 © Department of Information Systems - University of Information Technology 20



JSP Scriptlets

Format Result Code is inserted verbatim into servlet's _jspService Example



XML-compatible syntax Java Code

2008 © Department of Information Systems - University of Information Technology 21



JSP/Servlet Correspondence

Original JSP foo Representative resulting servlet code public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); JspWriter out = response.getWriter(); out.println("foo"); out.println(bar()); baz(); ... }

2008 © Department of Information Systems - University of Information Technology 22



JSP Scriptlets Example Suppose you want to let end users customize the background color of a page What is wrong with the following code?



">



2008 © Department of Information Systems - University of Information Technology



23



JSP Scriptlets Example

Color Testing "> Testing a Background of “ ".



2008 © Department of Information Systems - University of Information Technology



24



Make Parts of the JSP File Conditional

Point Scriplets are inserted into servlet exactly as written Need not be complete Java expressions Complete expressions are usually clearer and easier to maintain, however Example

Have a nice day! Have a lousy day!



Representative result

if (Math.random() nice day!");



} else {

out.println("Have a lousy day!");



}



2008 © Department of Information Systems - University of Information Technology



25



JSP Declarations

Format Result Code is inserted verbatim into servlet's class definition, outside of any existing methods Examples Design consideration Fields are clearly useful. For methods, it is usually better to define the method in a separate Java class. XML-compatible syntax Java Code

2008 © Department of Information Systems - University of Information Technology 26



JSP/Servlet Correspondence (1) Original JSP

Some Heading " + Math.random() + ""); } %>



Better alternative: Make randomHeading a static method in a separate class

2008 © Department of Information Systems - University of Information Technology 27



JSP/Servlet Correspondence (2)

Possible resulting servlet code public class xxxx implements HttpJspPage { private String randomHeading() { return("" + Math.random() + ""); } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); HttpSession session = request.getSession(); JspWriter out = response.getWriter(); out.println("Some Heading"); out.println(randomHeading()); ... } ... }

2008 © Department of Information Systems - University of Information Technology 28



JSP Declarations Example

JSP Declarations JSP Declarations Accesses to page since server reboot:



2008 © Department of Information Systems - University of Information Technology



29



jspInit and jspDestroy Methods (1)

JSP pages, like regular servlets, sometimes want to use init and destroy Problem: the servlet that gets built from the JSP page might already use init and destroy Overriding them would cause problems. Thus, it is illegal to use JSP declarations to declare init or destroy. Solution: use jspInit and jspDestroy. The auto-generated servlet is guaranteed to call these methods from init and destroy, but the standard versions of jspInit and jspDestroy are empty (placeholders for you to override).

2008 © Department of Information Systems - University of Information Technology 30



jspInit and jspDestroy Methods (2)

Example The lifecycle of jsp page Showing the life cycle of jsp using jspInit and jspDestroy "); out.println("The counter is " + count + ""); %>



2008 © Department of Information Systems - University of Information Technology



31



Predefined Variables

Problem The predefined variables (request, response, out, session, etc.) are local to the _jspService method. Thus, they are not available to methods defined by JSP declarations or to methods in helper classes. What can you do about this? Solution: pass them as arguments. E.g. Same issue with separate static methods And they are usually preferred over JSP declarations println of JSPWwriter throws IOException Use “throws IOException” for methods that use println

2008 © Department of Information Systems - University of Information Technology 32



When to use Expressions, Scriptlets or Declarations Task 1 Output a bulleted list of five random ints from 1 to 10. Since the structure of this page is fixed and we use a separate helper class for the randomInt method, JSP expressions are all that is needed. Task 2 Generate a list of between 1 and 10 entries (selected at random), each of which is a number between 1 and 10. Because the number of entries in the list is dynamic, a JSP scriptlet is needed. Task 3 Generate a random number on the first request, then showthe same number to all users until the server is restarted. Instance variables (fields) are the natural way to accomplish this persistence. Use JSP declarations for this.

33



2008 © Department of Information Systems - University of Information Technology



Examples

RanUtilities Class /** Simple utility to generate random integers. */ public class RanUtilities { /** A random int from 1 to range (inclusive). */ public static int randomInt(int range) { return(1 + ((int)(Math.random() * range))); } public static void main(String[] args) { int range = 10; try { range = Integer.parseInt(args[0]); // Array index or number format // Do nothing: range already has default value. } catch(Exception e) { } for(int i=0; i Random Numbers Random Numbers



%> %> %> %> %>



2008 © Department of Information Systems - University of Information Technology



35



JSP Scriptlets Example (V1)

Random List (Version 1) Random List (Version 1) " + RanUtilities.randomInt(10)); } %>



2008 © Department of Information Systems - University of Information Technology



36



JSP Scriptlets Example (V2)

Random List (Version 2) Random List (Version 2)

2008 © Department of Information Systems - University of Information Technology 37



JSP Declarations Example

Semi-Random Number Semi-Random Number:

2008 © Department of Information Systems - University of Information Technology 38



JSP Pages with XML Syntax

Why Two Versions Classic syntax is not XML-compatible

• , , are illegal in XML • HTML 4 is not XML compatible either • So, you cannot use XML editors like XML Spy



You might use JSP in XML environments

• To build xhtml pages • To build regular XML documents

– You can use classic syntax to build XML documents, but it is sometimes easier if you are working in XML to start with » For Web services » For Ajax applications



So, there is a second syntax

• Following XML rules

2008 © Department of Information Systems - University of Information Technology 39



Sample HTML 4 Page: Classic Syntax (sample.jsp)



Sample (Classic Syntax)

Sample (Classic Syntax) Num1: Num2: Num3:





2008 © Department of Information Systems - University of Information Technology 40



Sample XHTML Page: XML Syntax (sample.jspx)

Sample (XML Syntax) Sample (XML Syntax) Num1: Math.random()*10 double num2 = Math.random()*100; Num2: num2 private double num3 = Math.random()*1000; Num3: num3

2008 © Department of Information Systems - University of Information Technology 41



Outline Introduction Scripting Elements The JSP page Directive Including Files Using JavaBeans Components in JSP Servlets and JSP: The Model View Controller (MVC) Architecture

2008 © Department of Information Systems - University of Information Technology 42



Purpose of the page Directive Give high-level information about the servlet that will result from the JSP page Can control Which classes are imported What class the servlet extends What MIME type is generated How multithreading is handled If the servlet participates in sessions The size and behavior of the output buffer What page handles unexpected errors

2008 © Department of Information Systems - University of Information Technology 43



The import Attribute

Format Purpose Generate import statements at top of servlet definition Notes Although JSP pages can be almost anywhere on server, classes used by JSP pages must be in normal servlet dirs E.g.:

• …/WEB-INF/classes or • /WEB-INF/classes/directoryMatchingPackage

– …/WEB Always use packages for utilities that will be used by JSP!

2008 © Department of Information Systems - University of Information Technology 44



The Importance of Using Packages

What package will the system think that SomeHelperClass and SomeUtilityClass are in? ... public class SomeClass { public String someMethod(...) { SomeHelperClass test = new SomeHelperClass(...); String someString = SomeUtilityClass.someStaticMethod(...); ... } } ...



2008 © Department of Information Systems - University of Information Technology



45



The contentType and pageEncoding Attributes Format Purpose Specify the MIME type of the page generated by the servlet that results from the JSP page Notes Attribute value cannot be computed at request time See section on response headers for table of the most common MIME types

2008 © Department of Information Systems - University of Information Technology 46



Example: Conditionally Generating Excel Spreadsheets



You cannot use the contentType attribute for this task, since you cannot make contentType be conditional. The following always results in the Excel MIME type





Solution: use a regular JSP scriptlet with response.setContentType

2008 © Department of Information Systems - University of Information Technology 47



Example: Conditionally Generating Excel Spreadsheets

Comparing Apples and Oranges ApplesOranges First Quarter 2307 4706 Second Quarter2982 5104 Third Quarter 3011 5220 Fourth Quarter3055 5287



2008 © Department of Information Systems - University of Information Technology



48



The session Attribute

Format Purpose To designate that page not be part of a session Notes By default, it is part of a session Saves memory on server if you have a high-traffic site All related pages have to do this for it to be useful



2008 © Department of Information Systems - University of Information Technology



49



The buffer Attribute

Format Purpose To give the size of the buffer used by the out variable Notes Buffering lets you set HTTP headers even after some page content has been generated (as long as buffer has not filled up or been explicitly flushed) Servers are allowed to use a larger size than you ask for, but not a smaller size Default is system-specific, but must be at least 8kb

2008 © Department of Information Systems - University of Information Technology 50



The errorPage Attribute

Format Purpose Specifies a JSP page that should process any exceptions thrown but not caught in the current page Notes The exception thrown will be automatically available to the designated error page by means of the "exception“ variable The web.xml file lets you specify application-wide error pages that apply whenever certain exceptions or certain HTTP status codes result.

• The errorPage attribute is for page-specific error pages



Example: ComputeSpeed.jsp

2008 © Department of Information Systems - University of Information Technology 51



The extends Attribute

Format Purpose To specify parent class of servlet that will result from JSP page Notes Use with extreme caution Can prevent system from using high-performance custom superclasses Typical purpose is to let you extend classes that come from the server vendor (e.g., to support personalization features), not to extend your own classes.

2008 © Department of Information Systems - University of Information Technology 52



The isThreadSafe Attribute

A piece of code is thread-safe if it functions correctly during simultaneous execution by multiple threads Format Purpose To tell the system when your code is not threadsafe, so that the system can prevent concurrent access

• Normally tells the servlet to implement SingleThreadModel



Notes Avoid this like the plague

• Causes degraded performance in some situations • Causes incorrect results in others

2008 © Department of Information Systems - University of Information Technology 53



Non-Threadsafe Example Code (1) What's wrong with this code?





+ ".");



2008 © Department of Information Systems - University of Information Technology



54



Non-Threadsafe Example Code (2)

Is isThreadSafe Needed Here? No! It is not needed. Synchronize normally:





Better performance in high-traffic environments isThreadSafe="false" will totally fail if server uses pool-of-instances approach

2008 © Department of Information Systems - University of Information Technology 55



Outline Introduction Scripting Elements The JSP page Directive Including Files Using JavaBeans Components in JSP Servlets and JSP: The Model View Controller (MVC) Architecture

2008 © Department of Information Systems - University of Information Technology 56



jsp:include:Including Pages at Request Time Format Purpose To reuse JSP, HTML, or plain text content To permit updates to the included content without changing the main JSP page(s) Notes JSP content cannot affect main page: only outputof included JSP page is used Don’t forget that trailing slash Relative URLs that starts with slashes are interpreted relative to the Web app, not relative to the server root. You are permitted to include files from WEBINF

2008 © Department of Information Systems - University of Information Technology 57



Example

What's New at JspNews.com Here is a summary of our four most recent news stories: Note that the page is not a complete HTML document; it has only the tags appropriate to the place that it will be inserted

2008 © Department of Information Systems - University of Information Technology 58



jsp:param: Augmenting Request Parameters



Code





URL http://host/path/MainPage.jsp?fgColor=RED Main page fgColor: RED bgColor: null

• Regardless of whether you check before or after inclusion



Included page fgColor: RED bgColor: YELLOW

2008 © Department of Information Systems - University of Information Technology 59



:Including Files at Page Translation Time



Format Purpose To reuse JSP content in multiple pages, where JSP content affects main page Notes Servers are not required to detect changes to the included file, and in practice they don’t. Thus, you need to change the JSP files whenever the included file changes. You can use OS-specific mechanisms such as the Unix “touch” command, or

• •

2008 © Department of Information Systems - University of Information Technology 60



jsp:include vs.



2008 © Department of Information Systems - University of Information Technology



61



Which Should We Use?

Use jsp:include whenever possible Changes to included page do not require any manual updates Speed difference between jsp:include and the include directive (@include) is insignificant The include directive () has additional power, however Main page Included page Example: SomeRandomPage.jsp

2008 © Department of Information Systems - University of Information Technology 62



Understanding jsp:include vs.



Footer defined the accessCount field (instance variable) If main pages used accessCount, they would have to use @include Otherwise accessCount would be undefined In this example, the main page did not use accessCount So why did we use @include?

2008 © Department of Information Systems - University of Information Technology 63



Outline Introduction Scripting Elements The JSP page Directive Including Files Using JavaBeans Components in JSP Servlets and JSP: The Model View Controller (MVC) Architecture

2008 © Department of Information Systems - University of Information Technology 64



Uses of JSP Constructs

Simple Application

Scripting elements calling servlet code directly Scripting elements calling servlet code indirectly (by means of utility classes) Beans Servlet/JSP combo (MVC) MVC with JSP expression language Custom tags MVC with beans, custom tags, and a framework like Struts or JSF



Complex Application



2008 © Department of Information Systems - University of Information Technology



65



What Are Beans?

Java classes that follow certain conventions Must have a zero-argument (empty) constructor

• You can satisfy this requirement either by explicitly defining such a constructor or by omitting all constructors



Should have no public instance variables (fields)

• I hope you already follow this practice and use accessor methods instead of allowing direct access to fields



Persistent values should be accessed through methods called getXxx and setXxx

• If class has method getTitle that returns a String, class is said to have a String property named title • Boolean properties use isXxx instead of getXxx



For more on beans, see

• http://java.sun.com/beans/docs/

66



2008 © Department of Information Systems - University of Information Technology



Why You Should Use Accessors, Not Public Fields (1)



To be a bean, you cannot have public fields So, you should replace public double speed; with private double speed; public double getSpeed() { return(speed); } public void setSpeed (double newSpeed) { speed = newSpeed; } You should do this in all your Java code anyhow. Why?

2008 © Department of Information Systems - University of Information Technology 67



Why You Should Use Accessors, Not Public Fields (2)



You can put constraints on values public void setSpeed(double newSpeed) { if (newSpeed



jsp:setProperty This element modifies a bean property (i.e., calls a setBlah method). It is normally used as follows:





jsp:getProperty This element reads and outputs the value of a bean property It is used as follows:

71



2008 © Department of Information Systems - University of Information Technology



jsp:useBean

Format Purpose Allow instantiation of Java classes without explicit Java programming (XML-compatible syntax) Notes Simple interpretation:

• can be thought of as equivalent to the scriptlet •



But jsp:useBean has two additional advantages: It is easier to derive object values from request parameters It is easier to share objects among pages or servlets

2008 © Department of Information Systems - University of Information Technology 72



jsp:setProperty

Format Purpose Allow setting of bean properties (i.e., calls to setXxx methods) without explicit Java programming Notes is equivalent to the following scriptlet



2008 © Department of Information Systems - University of Information Technology



73



jsp:getProperty

Format Purpose Allow access to bean properties (i.e., calls to getXxx methods) without explicit Java programming Notes is equivalent to the following JSP expression



2008 © Department of Information Systems - University of Information Technology



74



Example

package mybeans; public class StringBean { private String message = "No message specified"; public String getMessage() { return(message); } public void setMessage(String message) { this.message = message; } }

2008 © Department of Information Systems - University of Information Technology 75



Outline Introduction Scripting Elements The JSP page Directive Including Files and Applets Using JavaBeans Components in JSP Servlets and JSP: The Model View Controller (MVC) Architecture

2008 © Department of Information Systems - University of Information Technology 76



Readings & Exercise

Further Readings Exercise



2008 © Department of Information Systems - University of Information Technology



77



Discussion



2008 © Department of Information Systems - University of Information Technology



78




Share This Document


Related docs
Other docs by long nguyen
tong hop csdl phan tan
Views: 2091  |  Downloads: 123
Tai lieu jsp
Views: 491  |  Downloads: 45
tom tat jstl tieng viet
Views: 2118  |  Downloads: 88
by registering with docstoc.com you agree to our
privacy policy

You are almost ready to download!

You are almost ready to download!