JSP Java Server Pages Representation and Management of

  • Slides: 59
Download presentation
JSP – Java Server Pages Representation and Management of Data on the Internet 1

JSP – Java Server Pages Representation and Management of Data on the Internet 1

What is JSP Good For? • Servlets allow us to easily: – read data

What is JSP Good For? • Servlets allow us to easily: – read data from user – read HTTP request – create cookies – etc. • It is not convenient to write long static HTML using Servlets – out. println("<h 1>Bla Bla</h 1>" + "bla bla bla " + " lots more here. . . ") 2

JSP Idea • Use HTML for most of the page • Write Java code

JSP Idea • Use HTML for most of the page • Write Java code directly in the HTML page (similar to Javascript( • Automatically translate JSP to Servlet that actually runs 3

Relationships • In servlets: HTML code is printed from java code • In JSP

Relationships • In servlets: HTML code is printed from java code • In JSP pages: Java code is embedded in HTML code Java HTML Java 4

Example <HTML> <HEAD> <TITLE>Hello World Example</TITLE> </HEAD> <BODY> <H 2>Hello World Example</H 2> <B>Hello

Example <HTML> <HEAD> <TITLE>Hello World Example</TITLE> </HEAD> <BODY> <H 2>Hello World Example</H 2> <B>Hello <% =request. get. Parameter("name") %>!</B> </BODY> </HTML> 5

Page is in the proj web application: tomcat_home/webapps/proj/Hello. World. jsp Invoked with URL: http:

Page is in the proj web application: tomcat_home/webapps/proj/Hello. World. jsp Invoked with URL: http: //<host>: <port>/proj/Hello. World. jsp? name=snoopy 6

Invoked with URL (no parameter): http: //<host>: <port>/proj/Hello. World. jsp 7

Invoked with URL (no parameter): http: //<host>: <port>/proj/Hello. World. jsp 7

JSP Limitations and Advantages • JSP can only do what a Servlet can do

JSP Limitations and Advantages • JSP can only do what a Servlet can do • Easier to write and maintain HTML • Easier to separate HTML from code • Can use a "reverse engineering technique": create static HTML and then replace static data with Java code 8

What does a JSP-Enabled Server do? • receives a request for a. jsp page

What does a JSP-Enabled Server do? • receives a request for a. jsp page • parses it • converts it to a Servlet (Jsp. Page) with your code inside the _jsp. Service() method • runs it 9

Translation of JSP to Servlet • Two phases: – Page translation: JSP is translated

Translation of JSP to Servlet • Two phases: – Page translation: JSP is translated to a Servlet. Happens the first time the JSP is accessed – Request time: When page is requested, Servlet runs • No interpretation of JSP at request time! 10

Design Stategy • Do not put lengthy code in JSP page • Do put

Design Stategy • Do not put lengthy code in JSP page • Do put lengthy code in a Java class and call it from the JSP page • Why? Easier for – Development (written separately) – Debugging (find errors when compiling) – Testing – Code Reuse 11

The Source Code • In Tomcat 3. 2. 1, you can find the generated

The Source Code • In Tomcat 3. 2. 1, you can find the generated Java and the class files in a subdirectory under tomcat_home/work. 12

JSP Scripting Elements • Scripting elements let you insert code into the servlet that

JSP Scripting Elements • Scripting elements let you insert code into the servlet that will be generated from the JSP • Three forms: – Expressions of the form <%= expression %> that are evaluated and inserted into the output, – Scriptlets of the form <% code %> that are inserted into the servlet's _jsp. Service method, and – Declarations of the form <%! code %> that are inserted into the servlet class, outside of any methods 13

JSP Expressions • A JSP expression is used to insert Java values directly into

JSP Expressions • A JSP expression is used to insert Java values directly into the output • It has the following form: <%= Java Expression %> • Example: – <%= Math. random() %> 14

JSP Expressions • A JSP Expression is evaluated • The result is converted to

JSP Expressions • A JSP Expression is evaluated • The result is converted to a string • The string is inserted into the page • This evaluation is performed at runtime (when the page is requested), and thus has full access to information about the request 15

Expression Translation <H 1>A Random Number</H 1> <%= Math. random() %> public void _jsp.

Expression Translation <H 1>A Random Number</H 1> <%= Math. random() %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println("<H 1>A Random Number</H 1>"); out. println(Math. random()); . . . } 16

Predefined Variables • The following predefined variables can be used: – request, the Http.

Predefined Variables • The following predefined variables can be used: – request, the Http. Servlet. Request – response, the Http. Servlet. Response – session, the Http. Session associated with the request – out, the Print. Writer (a buffered version of type Jsp. Writer) used to send output to the client 17

<HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H 2>JSP Expressions</H 2> <UL> <LI>Current time: <%= new

<HTML> <HEAD> <TITLE>JSP Expressions</TITLE></HEAD> <BODY> <H 2>JSP Expressions</H 2> <UL> <LI>Current time: <%= new java. util. Date() %> <LI>Your hostname: <%= request. get. Remote. Host() %> <LI>Your session ID: <%= session. get. Id() %> <LI>The <CODE>test. Param</CODE> form parameter: <%= request. get. Parameter("test. Param") %> </UL> </BODY> </HTML> 18

Encoded Unencoded 19

Encoded Unencoded 19

JSP Scriplets • JSP scriptlets let you insert arbitrary code into the servlet method

JSP Scriplets • JSP scriptlets let you insert arbitrary code into the servlet method that will be built to generate the page ( _jsp. Service ) • Scriptlets have the following form: <% Java Code %> • Scriptlets have access to the same automatically defined variables as expressions. Why? 20

Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request

Scriptlet Translation <%= foo() %> <% bar(); %> public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { request. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println(foo()); bar(); . . . } 21

Producing Code • Scriptlets can produce output by printing into the out variable •

Producing Code • Scriptlets can produce output by printing into the out variable • Example: <% String query. Data = request. get. Query. String(); out. println("Attached GET data: " + query. Data); %> • Would we want to use a scriptlet in this case? 22

HTML Code in Scriptlets • Scriptlets don't have to be entire Java Staments: <%

HTML Code in Scriptlets • Scriptlets don't have to be entire Java Staments: <% if (Math. random() < 0. 5) { %> You <B>won</B> the game! <% } else { %> You <B>lost</B> the game! <% } %> if (Math. random() < 0. 5) { out. println("You <B>won</B> the game!"); } else { out. println("You <B>lost</B> the game!"); } 23

JSP Declaration • A JSP declaration lets you define methods or fields that get

JSP Declaration • A JSP declaration lets you define methods or fields that get inserted into the servlet class (outside of all methods) • It has the following form: <%! Java Code %> • Declarations do not produce output • They are used to define variables and methods • Should you define a method in a JSP declaration? 24

Declaration Example • Print the number of times the current page has been requested

Declaration Example • Print the number of times the current page has been requested since the server booted (or the servlet class was changed and reloaded): <%! private int access. Count = 0; %> <%! private synchronized int inc. Access() { return ++access; } %> Accesses to page since server reboot: <%= inc. Access() %> • Should access. Count be static? 25

public class xxxx implements Http. Jsp. Page { private int access. Count = 0;

public class xxxx implements Http. Jsp. Page { private int access. Count = 0; private synchronized int inc. Access() { return ++access; } public void _jsp. Service(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Http. Session session = request. get. Session(true); Jsp. Writer out = response. get. Writer(); out. println("Accesses to page since server reboot: "); out. println(inc. Access()); . . . } 26

Predefined Variables • As we have seen before, there are variables that can be

Predefined Variables • As we have seen before, there are variables that can be used in the code • There are eight automatically defined variables, sometimes called implicit objects • We saw 4 variables: request, response, out, session • Other 4 variables: application, config, page. Context, page 27

More Details: request, response • request: the Http. Servlet. Request • response: the Http.

More Details: request, response • request: the Http. Servlet. Request • response: the Http. Servlet. Response • The output stream is buffered • It is legal to set HTTP status codes and response headers, even though this is not permitted in regular servlets once any output has been sent to the client • Use request to save page specific values 28

More Details: out • This is the Print. Writer used to send output to

More Details: out • This is the Print. Writer used to send output to the client • Actually a buffered version of Print. Writer called Jsp. Writer • You can adjust the buffer size, or even turn buffering off, through use of the buffer attribute of the page directive 29

More Details: session • This is the Http. Session object associated with the request

More Details: session • This is the Http. Session object associated with the request • Sessions are created automatically, so this variable is bound even if there was no incoming session reference (unless session was turned off using the session attribute of the page directive) • Use session to store client specific values 30

Another Variable: application • This is the Servlet. Context as obtained via get. Servlet.

Another Variable: application • This is the Servlet. Context as obtained via get. Servlet. Config(). get. Context() • Remember: – Servlets and JSP pages can hold constant data in the Servlet. Context object – Getting and setting attributes is with get. Attribute and set. Attribute – The Servlet. Context is shared by all the servlets in the server • Use application to store web application specific values 31

Another Variable: config • This is the Servlet. Config of the page, as received

Another Variable: config • This is the Servlet. Config of the page, as received in init method • Remember: Contains Servlet specific initialization parameters 32

Another Variable: page. Context • page. Context encapsulates use of serverspecific features like higher

Another Variable: page. Context • page. Context encapsulates use of serverspecific features like higher performance Jsp. Writers • Access server-specific features through this class rather than directly, your code will still run on "regular" servlet/JSP engines 33

Another Variable: page • Simply a synonym for this • page is not very

Another Variable: page • Simply a synonym for this • page is not very useful in JSP pages • It was created as a placeholder for the time when the scripting language could be something other than Java 34

Note about Predefined Variables • Predefined variables are local to the _jsp. Service method.

Note about Predefined Variables • Predefined variables are local to the _jsp. Service method. • How can we use them in methods that we define? • When using out in a method, note that it might throw a IOException 35

JSP Directives • A JSP directive affects the structure of the servlet class that

JSP Directives • A JSP directive affects the structure of the servlet class that is created from the JSP page • It usually has the following form: <%@ directive attribute="value" %> • Multiple attribute settings for a single directive can be combined: <%@ directive attribute 1="value 1". . . attribute. N="value. N" %> 36

Three Types of Directives • page, which lets you do things like – import

Three Types of Directives • page, which lets you do things like – import classes – customize the servlet superclass • include, which lets you insert a file into the servlet class at the time the JSP file is translated into a servlet • taglib, which indicates a library of custom tags that the page can include 37

page Directive Attributes • import attribute: A comma seperated list of classes/packages to import

page Directive Attributes • import attribute: A comma seperated list of classes/packages to import <%@ page import="java. util. *, java. io. *" %> • content. Type attribute: Sets the MIME-Type of the resulting document (default is text/html) <%@ page content. Type="text/plain" %> • Note that instead of using the content. Type attribute, you can write <% response. set. Content. Type("text/plain"); %> 38

More page Directive Attributes • is. Thread. Safe=“true|false” – false indicates that the Servlet

More page Directive Attributes • is. Thread. Safe=“true|false” – false indicates that the Servlet should implement the Single. Thread. Model • session=“true|false” – false indicates that a session should not be created – Saves memory – All related pages must do this!!! • buffer=“sizekb|none” Default is Server Dependant – specifies the buffer size for the Jsp. Writer out 39

More page Directive Attributes • autoflush=“true|false” – Flush buffer when full or throws an

More page Directive Attributes • autoflush=“true|false” – Flush buffer when full or throws an exception when buffer isfull • extends=“package. class” – Makes Servlet created a subclass of class supplied – Don't use this! Why? • info=“message” – A message for the get. Servlet. Info method 40

More page Directive Attributes • error. Page=“url” – Define a JSP page that handles

More page Directive Attributes • error. Page=“url” – Define a JSP page that handles uncaught exceptions – available to next page by exception variable – example • is. Error. Page=“true|false” – allows the page to be an error page 41

<HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page import="java. sql. *" %> <%@ page

<HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page import="java. sql. *" %> <%@ page error. Page="Error. jsp" %> <% Class. for. Name("oracle. jdbc. driver. Oracle. Driver"); Connection con = Driver. Manager. get. Connection("jdbc: oracle: thin: " + "snoopy/snoopy@sol 4: 1521: stud"); Statement stmt = con. create. Statement(); Result. Set rs = stmt. execute. Query("Select * from a"); Result. Set. Meta. Data md = rs. get. Meta. Data(); int col = md. get. Column. Count(); %> 42

<TABLE border="2"> <% while (rs. next()) { %> <TR> <% for (int i =

<TABLE border="2"> <% while (rs. next()) { %> <TR> <% for (int i = 1 ; i <= col ; i++) { %> <TD><%= rs. get. String(i) %></TD> <% } %> </TR> <% } %> </TABLE> </BODY> </HTML> Note: Is this a convenient way to print out a table? What would be a better way? 43

<HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page is. Error. Page="true" %> Oops. There

<HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> <%@ page is. Error. Page="true" %> Oops. There was an error when you accessed the database. Here is the stack trace: <pre> <% exception. print. Stack. Trace(new java. io. Print. Writer(out)); %> </pre> </BODY> </HTML> 44

Accessing Reading. Database when there is no table "a" Accessing Reading. Database when there

Accessing Reading. Database when there is no table "a" Accessing Reading. Database when there is a table "a" 45

The include Directive • This directive lets you include files at the time the

The include Directive • This directive lets you include files at the time the JSP page is translated into a servlet • The directive looks like this: <%@ include file="relative url" %> • JSP content can affect main page • servers don't notice changes in included files 46

<HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> Here is an interesting page. Bla. jsp Bla,

<HTML> <HEAD> <TITLE>Reading From Database</TITLE></HEAD> <BODY> Here is an interesting page. Bla. jsp Bla, Bla. <%@ include file="Access. Count. jsp" %> </BODY> </HTML> <hr> Page Created for Dbi Course. Email us <a href="mailto: dbi@cs. huji. ac. il">here</a>. <%! private int access. Count = 0; %> Accesses to page since server reboot: <%= access. Count++ %> Access. Count. jsp 47

48

48

Writing JSP in XML • We can replace the JSP tags with XML tags

Writing JSP in XML • We can replace the JSP tags with XML tags that represent – Expressions – Scriptlets – Declarations – Directives 49

<%= Java Expression %> <jsp: expression> Java Expression </jsp: expression> <% Code %> <jsp:

<%= Java Expression %> <jsp: expression> Java Expression </jsp: expression> <% Code %> <jsp: scriptlet> Code Java </jsp: scriptlet> <%! declaration %> <jsp: declaration> Java Declaration </jsp: declaration> <%@ directive %> <jsp: directive. type Attribute = value/> 50

Actions • JSP actions use constructs in XML syntax to control the behavior of

Actions • JSP actions use constructs in XML syntax to control the behavior of the servlet engine • You can – dynamically insert a file, – reuse Java. Beans components, – forward the user to another page, or – generate HTML for the Java plugin 51

Available Actions • jsp: include - Include a file at the time the page

Available Actions • jsp: include - Include a file at the time the page is requested • jsp: use. Bean, jsp: set. Property, jsp: get. Property – manipulate a Java. Bean (not discussed today) • jsp: forward - Forward the requester to a new page • jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin (not discussed today) 52

The jsp: include Action • This action lets you insert files into the page

The jsp: include Action • This action lets you insert files into the page being generated • The file inserted when page is requested • The syntax looks like this: <jsp: include page="relative URL" flush="true" /> 53

The jsp: forward Action • Forwards request to another page <jsp: forward page="relative URL"/>

The jsp: forward Action • Forwards request to another page <jsp: forward page="relative URL"/> • Page could be a static value, or could be computed at request time • Examples: <jsp: forward page="/utils/error. Reporter. jsp" /> <jsp: forward page="<%= some. Java. Expression %>" /> 54

Comments • <%-- comment --%> – A JSP comment, ignored by JSP-to-scriptlet translator •

Comments • <%-- comment --%> – A JSP comment, ignored by JSP-to-scriptlet translator • <!-- comment --> – An HTML comment, Passed through to resultant HTML – Any embedded JSP scripting elements, directives, or actions are executed normally • /* comment */ or // comment – Java comment, Part of the Java code 55

Quoting Conventions • <% - used in template text (static HTML) and in attributes

Quoting Conventions • <% - used in template text (static HTML) and in attributes where you really want <% • %> - used in scripting elements and in attributes where you really want %> • ‘ ” - for using quotes in attributes • \ for having in an attribute 56

Init and Destroy • In JSP pages, like regular servlets, sometimes want to use

Init and Destroy • In JSP pages, like regular servlets, sometimes want to use init and destroy • It is illegal to use JSP declarations to override init or destroy, since they are already implemented (usually) by Servlet created • Instead use jsp. Init and jsp. Destroy – The auto-generated servlet is guaranteed to call these methods from init and destroy – The standard versions of jsp. Init and jsp. Destroy are empty (placeholders for you to override) 57

Material Not Covered • Java beans: Using Java beans you can simplify the process

Material Not Covered • Java beans: Using Java beans you can simplify the process of sharing information between JSP pages and Servlets. (How can you share information now? ) • Custom Tags: You may define new tags and Java classes that define what should be done when the tag appears in a JSP page 58

JSP versus Java. Script • Q: Can/Should you have JSP and Javascript in the

JSP versus Java. Script • Q: Can/Should you have JSP and Javascript in the same page? • Q: Can you validate a form using Java. Script? Where should the code go? • Q: Can you validate a form using JSP? Where should the code go? 59