JSP Java Server Pages Part 2 Representation and

  • Slides: 48
Download presentation
JSP – Java Server Pages Part 2 Representation and Management of Data on the

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

Interacting with other Resources

Interacting with other Resources

JSP Cooperation • We will consider several ways in which JSP and other resources

JSP Cooperation • We will consider several ways in which JSP and other resources cooperate - Forwarding the request handling to other resources - Including the content of other sources - Including the code of other JSP files - Forwarding exception handling to other JSPs

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 • Using actions, you can - forward the request to another resource in the application - dynamically include a resource content in the response

The forward Action • jsp: forward - Forwards the requester to a new resource

The forward Action • jsp: forward - Forwards the requester to a new resource <jsp: forward page="{relative. URL|<%= expression %>}"> <jsp: param name="parameter. Name" value="{parameter. Value | <%= expression %>}" /> * </jsp: forward> • This action is translated to an invocation of the Request. Dispatcher

The include Action • jsp: include - Include a resource content at run time

The include Action • jsp: include - Include a resource content at run time <jsp: include page="{relative. URL|<%= expression %>}"> <jsp: param name="parameter. Name" value="{parameter. Value | <%= expression %>}" />* </jsp: include> • This action is also translated to an invocation of the Request. Dispatcher

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="url" %> • JSP content can affect main page • In Tomcat 5. x, generated Servlet is updated when included files change (unlike old versions. . . )

Include - Action File 1. jsp HTML content Servlet 1 HTML content File 2.

Include - Action File 1. jsp HTML content Servlet 1 HTML content File 2. jsp Servlet 2 HTML content

Include Directive File 1. jsp File 2. jsp Servlet HTML content

Include Directive File 1. jsp File 2. jsp Servlet HTML content

include Action vs. Directive • When a resource is included using the include action,

include Action vs. Directive • When a resource is included using the include action, the generated Servlet uses the dispatcher to include its content at runtime • When a file is included using the include directive, the file itself is included verbatim into the JSP code, prior to the Servlet generation • Question: in which of the above options can the included element change the HTTP headers or status?

Bla. jsp <html> <head><title>Including JSP</title></head><body> <h 2>Here is an interesting page. </h 2> <p>Bla,

Bla. jsp <html> <head><title>Including JSP</title></head><body> <h 2>Here is an interesting page. </h 2> <p>Bla, Bla. </p> <%@ include file="/Access. Count. jsp" %> <jsp: include page="/dbimail. jsp"/> </body></html> Access. Count. jsp <%! private int access. Count = 0; %> <hr><p>Accesses to page since Servlet init: <%= ++access. Count %></p> dbimail. jsp <hr><p> Page Created for Dbi Course at <%= new java. util. Date() %>. Email us <a href="mailto: dbi@cs. huji. ac. il">here</a>. </p>

Bla. Bla_jsp. java out. write("<html>rn"); out. write(" <head><title>Including JSP</title></head>rn"); out. write(" <body>rn"); out. write("

Bla. Bla_jsp. java out. write("<html>rn"); out. write(" <head><title>Including JSP</title></head>rn"); out. write(" <body>rn"); out. write(" <h 2>Here is an interesting page. </h 2>rn"); out. write(" <p>Bla, Bla. </p>rn"); out. write("<hr>rn"); out. write("<p> rn"); out. write(" Accesses to page since Servlet init: rn"); out. print( ++access. Count ); out. write("</p>rn"); org. apache. jasper. runtime. Jsp. Runtime. Library. include(request, response, "/dbimail. jsp", out, false); out. write(" </body>rn"); out. write("</html>rn");

Included Counter • Suppose that the file Bla 2. jsp is similar the Bla.

Included Counter • Suppose that the file Bla 2. jsp is similar the Bla. jsp • How will the counter of Bla 2. jsp act? • What if we used a JSP action instead of a JSP directive for the counter?

Error Pages • We can set one JSP page to be the handler of

Error Pages • We can set one JSP page to be the handler of uncaught exceptions of another JSP page, using JSP directives • <%@ page error. Page="url " %> - Defines a JSP page that handles uncaught exceptions - The page in url must have true in the page-directive: • <%@ is. Error. Page="true|false" %> - The variable exception holds the exception thrown by the calling JSP

connect. jsp <html> <head><title>Reading From Database </title></head> <body> <%@ page import="java. sql. *" %>

connect. jsp <html> <head><title>Reading From Database </title></head> <body> <%@ page import="java. sql. *" %> <%@ page error. Page="error. Page. jsp" %> <% Class. for. Name("oracle. jdbc. driver. Oracle. Driver"); Connection con = Driver. Manager. get. Connection ("jdbc: oracle: thin: " + "snoopy/snoopy@sol 4: 1521: stud"); %> <h 2>Connection Established!!</h 2> </body> </html>

error. Page. jsp <html> <head><title>Connection Error</title></head> <body> <%@ page import="java. io. *" %> <%@

error. Page. jsp <html> <head><title>Connection Error</title></head> <body> <%@ page import="java. io. *" %> <%@ page is. Error. Page="true" %> <h 1>Oops. There was an error when you accessed the database. </h 1> <h 2>Here is the stack trace: </h 2> <pre style="color: red"> <% exception. print. Stack. Trace(new Print. Writer(out)); %> </pre> </body> </html>

Custom JSP Tags

Custom JSP Tags

Custom JSP Tags • JSP code may use custom tags - tags that are

Custom JSP Tags • JSP code may use custom tags - tags that are defined and implemented by the programmer • The programmer defines how each of the custom tags is translated into Java code • There are two methods to define custom tags: - Tag libraries - used in old versions of JSP - Tag files - much simpler, introduced in JSP 2. 0

Tag Libraries • A tag library consists of: - Tag handlers - Java classes

Tag Libraries • A tag library consists of: - Tag handlers - Java classes that define how each of the new tags is translated into Java code - A TLD (Tag Library Descriptor) file, which is an XML file that defines the structure and the implementing class of each tag

A Simple Tag. Lib Example Date. Tag. java package dbi; import javax. servlet. jsp.

A Simple Tag. Lib Example Date. Tag. java package dbi; import javax. servlet. jsp. Jsp. Exception; import javax. servlet. jsp. tagext. Simple. Tag. Support; import java. io. IOException; public class Date. Tag extends Simple. Tag. Support { public void do. Tag() throws Jsp. Exception, IOException { get. Jsp. Context(). get. Out(). print(new java. util. Date()); } }

<taglib> <tlib-version>1. 0</tlib-version><jsp-version>2. 0</jsp-version> <tag> <name>date</name> <tagclass>dbi. Date. Tag</tagclass> <body-content>empty</body-content> </tag> </taglib> dbi-taglib. tld

<taglib> <tlib-version>1. 0</tlib-version><jsp-version>2. 0</jsp-version> <tag> <name>date</name> <tagclass>dbi. Date. Tag</tagclass> <body-content>empty</body-content> </tag> </taglib> dbi-taglib. tld <%@ taglib prefix="dbitag" uri="/WEB-INF/tags/dbi-taglib. tld" %> <html><body> <h 1>Hello. The time is: <dbitag: date/></h 1> </body></html> taglibuse. jsp

Tag Files • JSP 2. 0 provides an extremely simplified way of defining tags

Tag Files • JSP 2. 0 provides an extremely simplified way of defining tags • The idea: for each custom tag, write a tag file tag. Name. tag that implements the tag translation using JSP code • This way, the programmer can avoid creating tag handlers and TLD files

The Simplified Example <%= new java. util. Date() %> date. tag <%@ taglib prefix="dbitag"

The Simplified Example <%= new java. util. Date() %> date. tag <%@ taglib prefix="dbitag" tagdir="/WEB-INF/tags/" %> <html> <body> <h 1>Hello. The time is: <dbitag: date/></h 1> </body> </html> taguse. jsp

Other Capabilities of Custom Tags • Attributes - You can define the possible attributes

Other Capabilities of Custom Tags • Attributes - You can define the possible attributes of the Tags - These can be accessed during the Tag translation • Tag Body - Tag translation may choose to ignore, include or change the tag body

Java Beans in JSP

Java Beans in JSP

Motivation • Software components (e. g. objects, data structures, primitives) are extensively used in

Motivation • Software components (e. g. objects, data structures, primitives) are extensively used in Web applications • For example: - Service local variables - Attributes forwarded in requests - Session attributes, like users information - Application attributes, like access counters

Motivation • Standard actions are used to manipulate components: declaration, reading from the suitable

Motivation • Standard actions are used to manipulate components: declaration, reading from the suitable context, setting of new values (according to input parameters), storing inside the suitable context, etc. • Java Beans provide a specification for automatic handling and manipulation of software components in JSP (and other technologies. . . )

Java Beans: The Idea • Java Beans are simply objects of classes that follow

Java Beans: The Idea • Java Beans are simply objects of classes that follow some (natural) coding convention: - An empty constructor - A readable property has a matching getter - A writable property has a matching setter • Use JSP actions to access and manipulate the bean, and special action attributes to specify the properties of the bean, like its scope

Example 1: Access Counter In the following example, we use a Bean to maintain

Example 1: Access Counter In the following example, we use a Bean to maintain an access counter for requests to the pages

Counter Bean package dbi; Bean must reside in a package public class Counter. Bean

Counter Bean package dbi; Bean must reside in a package public class Counter. Bean { private int counter; Bean is created by an empty constructor public Counter. Bean() { counter = 0; } public int get. Counter() { return counter; } public void set. Counter(int i) { counter = i; } counter is readable and writable public void increment() { ++counter; } } other methods can be used Counter. Bean. java

<html> <head><title>Bean Example</title></head><body> <jsp: use. Bean id="access. Counter" class="dbi. Counter. Bean" scope="application"/> <% access.

<html> <head><title>Bean Example</title></head><body> <jsp: use. Bean id="access. Counter" class="dbi. Counter. Bean" scope="application"/> <% access. Counter. increment(); %> <h 1> Welcome to Page A</h 1> <h 2>Accesses to this application: <jsp: get. Property name="access. Counter" property="counter"/> </h 2> <a href="page. B. jsp">Page B</a></body> </html> invokes get. Counter() page. A. jsp

<html> <head><title>Bean Example</title></head><body> <jsp: use. Bean id="access. Counter" class="dbi. Counter. Bean" scope="application"/> <% access.

<html> <head><title>Bean Example</title></head><body> <jsp: use. Bean id="access. Counter" class="dbi. Counter. Bean" scope="application"/> <% access. Counter. increment(); %> <h 1> Welcome to Page B</h 1> <h 2>Accesses to this application: <jsp: get. Property name="access. Counter" property="counter"/> </h 2> <a href="page. A. jsp">Page A</a></body> </html> page. B. jsp

From the Generated Servlet dbi. Counter. Bean access. Counter = null; synchronized (application) {

From the Generated Servlet dbi. Counter. Bean access. Counter = null; synchronized (application) { access. Counter = (dbi. Counter. Bean) _jspx_page_context. get. Attribute("access. Counter", Page. Context. APPLICATION_SCOPE); if (access. Counter == null) { access. Counter = new dbi. Counter. Bean(); _jspx_page_context. set. Attribute("access. Counter", access. Counter, Page. Context. APPLICATION_SCOPE); } }

Example 2: Session Data In the following example, we use a Bean in order

Example 2: Session Data In the following example, we use a Bean in order to keep a user's details throughout the session

package dbi; public class User. Info. Bean { private String first. Name; private String

package dbi; public class User. Info. Bean { private String first. Name; private String last. Name; public User. Info. Bean() { first. Name = last. Name = null; } public String get. First. Name() {return first. Name; } public String get. Last. Name() { return last. Name; } public void set. First. Name(String string) {first. Name = string; } public void set. Last. Name(String string) {last. Name = string; } } User. Info. Bean. java

<html> <head><title>Information Form</title></head> <body> <h 1>Fill in your details: </h 1> <form action="info. A.

<html> <head><title>Information Form</title></head> <body> <h 1>Fill in your details: </h 1> <form action="info. A. jsp" method="get"><p> Your First Name: <input type="text" name="first. Name" /> <br/> Your Last Name: <input type="text" name="last. Name" /><br/> <input type="submit" /></p> </form> </body></html> info. Form. html

<jsp: use. Bean id="user. Info" class="dbi. User. Info. Bean" scope="session"/> <jsp: set. Property name="user.

<jsp: use. Bean id="user. Info" class="dbi. User. Info. Bean" scope="session"/> <jsp: set. Property name="user. Info" property="*"/> <html> Match parameters to <head><title>Page A</title></head><body> corresponding properties <h 1>Hello <jsp: get. Property name="user. Info" property="first. Name"/> <jsp: get. Property name="user. Info" property="last. Name"/>, </h 1> <h 1>Have a nice session!</h 1> <h 2> <a href="info. B. jsp">User Info B</a></h 2> </body></html> info. A. jsp

<jsp: use. Bean id="user. Info" class="dbi. User. Info. Bean" scope="session"/> <jsp: set. Property name="user.

<jsp: use. Bean id="user. Info" class="dbi. User. Info. Bean" scope="session"/> <jsp: set. Property name="user. Info" property="*"/> <html> <head><title>Page B</title></head><body> <h 1>Hello <jsp: get. Property name="user. Info" property="first. Name"/> <jsp: get. Property name="user. Info" property="last. Name"/>, </h 1> <h 1>Have a nice session!</h 1> <h 2> <a href="info. A. jsp">User Info A</a></h 2> </body></html> info. B. jsp

Advantages of Java Beans • Easy and standard management of data - Automatic management

Advantages of Java Beans • Easy and standard management of data - Automatic management of bean sharing and lots more • Good programming style - Allow standard but not direct access to members - You can add code to the setters and getters (e. g. constraint checks) without changing the client code - You can change the internal representation of the data without changing the client code • Increase of separation between business logic (written by programmers) and HTML (written by GUI artists)

JSP Expression Language

JSP Expression Language

JSP Expression Language • JSP expression language is a comfortable tool to access useful

JSP Expression Language • JSP expression language is a comfortable tool to access useful objects in JSP • This language provides shortcuts in Java. Scriptlike syntax • An expression in EL is written as ${expr} • For example: Hi, ${user}. <em style="${style}">Welcome</em>

EL Variables • JSP EL does not recognize JSP's implicit objects, but rather has

EL Variables • JSP EL does not recognize JSP's implicit objects, but rather has its own set: param, param. Values, header. Values, cookie, init. Param, page. Scope, request. Scope, session. Scope, application. Scope • Each of these objects maps names to values • For example, use param["x"] or param. x to get the value of the parameter x

EL Variables (cont) • A variable that is not an EL implicit object is

EL Variables (cont) • A variable that is not an EL implicit object is looked up at the page, request, session (if valid) and application scopes • That is, x is evaluated as the first non null element obtained by executing page. Context. get. Attribute("x"), request. get. Attribute("x"), etc.

Object Properties • In JSP EL, Property p of Object o is referred to

Object Properties • In JSP EL, Property p of Object o is referred to as o[p] • Property p of Object o is evaluated as follows: - If o is a Map object, then o. get(p) is returned - If o is a List or an array, then p is converted into an integer and o. get(p) or o[p] is returned - Otherwise, treat o as a bean, convert p to a string, and return apply the corresponding getter of o • The term o. p is equivalent to o["p"]

An Example <% response. add. Cookie(new Cookie("course", "dbi")); session. set. Attribute("dbiurl", new java. net.

An Example <% response. add. Cookie(new Cookie("course", "dbi")); session. set. Attribute("dbiurl", new java. net. URL("http: //www. cs. huji. ac. il/~dbi/index. html")); String[] strs = {"str 1", "str 2"}; session. set. Attribute("arr", strs); %> <html><head><title>JSP Expressions</title></head><body> <form method="get" action="el. jsp"> <h 2>Write the parameter x: <input name="x" type="text" /> <input type="submit" value="send" /></h 2> </form> </body></html> elcall. jsp

<%@ page is. ELIgnored="false" %> <html> <head><title>EL Examples</title></head> <h 1>Expression-Language Examples</h 1> <h 2>Parameter

<%@ page is. ELIgnored="false" %> <html> <head><title>EL Examples</title></head> <h 1>Expression-Language Examples</h 1> <h 2>Parameter <code>x</code>: ${param["x"]} </h 2> <h 2>Cookie <code>course</code>: ${cookie. course. value}</h 2> <h 2>Header <code>Connection</code>: ${header. Connection} </h 2> <h 2>Path of session attr. <code>dbiurl</code>: ${session. Scope. dbiurl. path}</h 2> <h 2>Element <code>arr[${param. x}]</code>: ${arr[param. x]} </h 2> </body></html> el. jsp