47
1 (Server-Side Programming using Java Server Pages) cs236607

1 (Server-Side Programming using Java Server Pages) cs236607

Embed Size (px)

Citation preview

Page 1: 1 (Server-Side Programming using Java Server Pages) cs236607

1

(Server-Side Programming using Java Server Pages)

cs236607

Page 2: 1 (Server-Side Programming using Java Server Pages) cs236607

2cs236607

Page 3: 1 (Server-Side Programming using Java Server Pages) cs236607

3

MotivationSoftware components (e.g. objects, data

structures, primitives) are extensively used in Web applications

For example:Service local variablesAttributes forwarded in requestsSession attributes, such as user informationApplication attributes, such as access counters

See tutorial at http://java.sun.com/docs/books/tutorial/javabeans/

cs236607

Page 4: 1 (Server-Side Programming using Java Server Pages) cs236607

4

MotivationStandard 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...)

cs236607

Page 5: 1 (Server-Side Programming using Java Server Pages) cs236607

5

Java Beans: The IdeaJava Beans are simply objects of classes that

follow some (natural) coding convention:An empty constructorA readable property has a matching getterA 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, e.g., its scope

JSP programmers do not wish to write cumbersome code or class files

cs236607

Page 6: 1 (Server-Side Programming using Java Server Pages) cs236607

6

Example 1: Access Counter

In the following example, we use a Bean to maintain an

access counter for requests to the pages

cs236607

Page 7: 1 (Server-Side Programming using Java Server Pages) cs236607

7

package myUtils;

public class CounterBean {

private int counter;

public CounterBean() { counter = 0; }

public int getCounter() { return counter; }

public void setCounter(int i) { counter = i; }

public void increment() { ++counter; }

}

Counter Bean

CounterBean.java

Bean must reside in a package

A Bean is created by an empty constructor

Counter setter and getter

Other methods can be implemented as well

A Bean is a concept and therefore there’s no need to extend any class or implement any interface!

(though it would’ve been very Java-ish to create an empty interface “Bean”)

cs236607

Page 8: 1 (Server-Side Programming using Java Server Pages) cs236607

8

<html>

<head><title>Bean Example</title></head><body>

<jsp:useBean id="accessCounter"

class=“myUtils.CounterBean" scope="application"/>

<% accessCounter.increment(); %>

<h1> Welcome to Page A</h1>

<h2>Accesses to this application:

<jsp:getProperty name="accessCounter" property="counter"/>

</h2>

<a href="pageB.jsp">Page B</a></body>

</html> pageA.jsp

Invokes getCounter()

An instance named according to the given id is either found in the relevant scope or is created

The default scope is page

You could also use the type attribute in order to instantiate a data type which is either superclass of class or an interface that class implements

cs236607

Page 9: 1 (Server-Side Programming using Java Server Pages) cs236607

9

<html>

<head><title>Bean Example</title></head><body>

<jsp:useBean id="accessCounter"

class=“myUtils.CounterBean" scope="application"/>

<% accessCounter.increment(); %>

<h1> Welcome to Page B</h1>

<h2>Accesses to this application:

<jsp:getProperty name="accessCounter" property="counter"/>

</h2>

<a href="pageA.jsp">Page A</a></body>

</html>

pageB.jsp

A very similar JSP

Since an instance named according to the given id can be found in the application scope, no instantiation takes place

cs236607

Page 10: 1 (Server-Side Programming using Java Server Pages) cs236607

10

myUtils.CounterBean accessCounter = null;

synchronized (application) {

accessCounter = (myUtils.CounterBean) _jspx_page_context.getAttribute("accessCounter",

PageContext.APPLICATION_SCOPE);

if (accessCounter == null) {

accessCounter = new myUtils.CounterBean();

_jspx_page_context.setAttribute("accessCounter",

accessCounter, PageContext.APPLICATION_SCOPE);

}

}

Part of the Generated Servlet

Similar effect to getServletContext().setAttribute()

Similar effect to getServletContext().getAttribute()

The instance is created and kept in the application’s scope as required. Note however that accessing this instance is out of the synchronized scope

cs236607

Page 11: 1 (Server-Side Programming using Java Server Pages) cs236607

11

Example 2: Session DataIn the following example, we use a Bean in

order to keep a user's details throughout the session

cs236607

Page 12: 1 (Server-Side Programming using Java Server Pages) cs236607

12

package myUtils;

public class UserInfoBean {

private String firstName;

private String lastName;

public UserInfoBean() { firstName = lastName = null;}

public String getFirstName() {return firstName;}

public String getLastName() {return lastName;}

public void setFirstName(String string) {firstName = string;}

public void setLastName(String string) {lastName = string;}

} UserInfoBean.java

cs236607

Page 13: 1 (Server-Side Programming using Java Server Pages) cs236607

13

<html>

<head><title>Information Form</title></head>

<body>

<h1>Fill in your details:</h1>

<form action="infoA.jsp" method="get"><p>

Your First Name:

<input type="text" name="firstName" /> <br/>

Your Last Name:

<input type="text" name="lastName" /><br/>

<input type="submit" /></p>

</form>

</body></html> infoForm.htmlcs236607

Page 14: 1 (Server-Side Programming using Java Server Pages) cs236607

14

<jsp:useBean id="userInfo" class=“myUtils.UserInfoBean"

scope="session"/>

<jsp:setProperty name="userInfo" property="*"/>

<html>

<head><title>Page A</title></head><body>

<h1>Hello

<jsp:getProperty name="userInfo" property="firstName"/>

<jsp:getProperty name="userInfo" property="lastName"/>,

</h1>

<h1>Have a nice session!</h1>

<h2> <a href="infoB.jsp">User Info B</a></h2>

</body></html> infoA.jsp

Match all the request parameters to corresponding properties. You could match parameters to properties explicitly using property=… param=…

You can also set properties with explicit values using property=… value=…

The String values are converted to the right bean’s property types..

cs236607

Page 15: 1 (Server-Side Programming using Java Server Pages) cs236607

15

<jsp:useBean id="userInfo" class=“myUtils.UserInfoBean"

scope="session"/>

<jsp:setProperty name="userInfo" property="*"/>

<html>

<head><title>Page B</title></head><body>

<h1>Hello

<jsp:getProperty name="userInfo" property="firstName"/>

<jsp:getProperty name="userInfo" property="lastName"/>,

</h1>

<h1>Have a nice session!</h1>

<h2> <a href="infoA.jsp">User Info A</a></h2>

</body></html>infoB.jsp

A very similar JSP

This time the request has no parameters so no bean properties are set

cs236607

Page 16: 1 (Server-Side Programming using Java Server Pages) cs236607

16

Advantages of Java BeansEasy and standard management of data

Automatic management of bean sharing and lots more

Good programming styleAllow 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)

cs236607

Page 17: 1 (Server-Side Programming using Java Server Pages) cs236607

17cs236607

Page 18: 1 (Server-Side Programming using Java Server Pages) cs236607

18

Custom JSP TagsJSP code may use custom tags – tags that are

defined and implemented by the programmerThe programmer defines how each of the

custom tags is translated into Java codeThere are two methods to define custom tags:

Tag libraries - used in old versions of JSPTag files - much simpler, introduced in JSP 2.0

cs236607

Page 19: 1 (Server-Side Programming using Java Server Pages) cs236607

19

Tag LibrariesA 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

(see a tutorial at http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html)

cs236607

Page 20: 1 (Server-Side Programming using Java Server Pages) cs236607

20

package my;import javax.servlet.jsp.JspException;import javax.servlet.jsp.tagext.SimpleTagSupport;import java.io.IOException;public class DateTag extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().print(new java.util.Date()); }}

DateTag.java

A Simple TagLib ExampleA Simple TagLib Example

Using the JSP-context, You can also acquire other implicit objects by calling getSession(), getRequest() etc…

The class file is placed in webapps/myapp/WEB-INF/classes/my/

The java file is placed in webapps/myapp/WEB-INF/src/my/

Base class of tags which don’t handle the body or the attributes

We must use a package (not necessarily named like your application) since this is a helper class which is imported form the JSP’s generated Servlet that is placed within a named package

• Goal: <mytag:date/>

cs236607

Page 21: 1 (Server-Side Programming using Java Server Pages) cs236607

21

<taglib>

<tlib-version>1.0</tlib-version><jsp-version>2.0</jsp-version>

<tag>

<name>date</name>

<tagclass>my.DateTag</tagclass>

<body-content>empty</body-content>

</tag>

</taglib>

my-taglib.tld

<%@ taglib prefix=“mytag" uri="/WEB-INF/tags/my-taglib.tld" %>

<html><body>

<h1>Hello. The time is: <mytag:date/></h1>

</body></html>taglibuse.jsp

As you can see from the path, the taglib is specifically defined to the current application context.

The prefix for this tag must appear before the tag itself (looks like a namespace).The Prefix can’t be empty

The path could be a URL.If you choose to use a local path, it must begin with /WEB-INF/tags/

Set this value that indicates your tag library version

Name of the tagTag’s class file in/myapp/WEB-INF/classes/my/

This defined tag contains no body

You can add here more tags…

cs236607

Page 22: 1 (Server-Side Programming using Java Server Pages) cs236607

22

Taglib with Attributespackage my;

import javax.servlet.jsp.JspException;

import javax.servlet.jsp.tagext.TagSupport;

import java.io.IOException;

public class DateTag2 extends TagSupport {

private boolean isLongFormat = false;

public void setIsLongFormat(boolean b) {

isLongFormat = b; }

public boolean getIsLongFormat() {

return isLongFormat; {

DateTag2.java

Base class of tags which do handle attributesIn our example the attribute is defined as not required so it must have a default valueAttribute’s setter method

Attribute’s getter method

This member’s name should be identical to the attribute’s.

The setter/getter methods should be named after the attribute (i.e. “get” + capital (<attribute>))

cs236607

Page 23: 1 (Server-Side Programming using Java Server Pages) cs236607

23

public int doStartTag() throws JspException { try {

if (isLongFormat) { pageContext.getOut().print(new java.util.Date().getTime()); } else { pageContext.getOut().print(new java.util.Date()); }

} catch (Exception e) { throw new JspException("DateTag: " + e.getMessage()); } return SKIP_BODY; }

public int doEndTag() { return EVAL_PAGE; }}

Invoked when the generated Servlet starts processing the “start tag”

Prints the date according to the isLongFormat attribute

Signals the generated Servlet there’s no body within the tag to process

Invoked when the generated Servlet starts processing the “end tag”

Signals the generated Servlet to continue executing the generated Servlet code

cs236607

Page 24: 1 (Server-Side Programming using Java Server Pages) cs236607

24

<tag><name>date2</name><tagclass>my.DateTag2</tagclass><body-content>empty</body-content>

<attribute><name>isLongFormat</name><required>false</required>

</attribute></tag> my-taglib2.tld

<%@ taglib prefix=“mytag" uri="/WEB-INF/tags/my-taglib2.tld" %>

<html><body>

<h1>Hello.</h1>

<h2>The time is: <mytag:date2/></h2>

<h2>Milliseconds since the epoch : <mytag:date2 isLongFormat="true" /></h2>

</body></html>taglibuse2.jsp

Same as before, only with different names for the tagclass

You can put several blocks one after another

The attribute is “not required” so you have to define a default value in DateTag2.java

Uses default attribute value

Uses a given attribute value

cs236607

Page 25: 1 (Server-Side Programming using Java Server Pages) cs236607

25

How does it work?

taglibuse2.jsp

taglibuse2_jsp.java

JspContext

DateTag2

setIsLongFormat()

doStartTag()

doEndTag()

JSP to Java Servlet translation

Create the JspContextWhen the

translation engine first encounters <mytag:date2> it creates a new instance of DateTag2 (so we needn’t worry about concurrency issues) and passes it the JspContext reference

The attribute value is set using the setter method.The translator actually translated the attribute string value as it appears in the JSP source, to a boolean value as the Java tag class expects it…

“Start tag” is reached

“End tag” is reached

cs236607

Page 26: 1 (Server-Side Programming using Java Server Pages) cs236607

26

Tag FilesJSP 2.0 provides an extremely simplified way

of defining tagsThe motivation: JSP programmers prefer not

to write cumbersome code or class filesThe idea: for each custom tag, write a tag file tagName.tag that implements the tag translation using JSP code

This way, the programmer can avoid creating tag handlers and TLD files

cs236607

Page 27: 1 (Server-Side Programming using Java Server Pages) cs236607

27

<%= new java.util.Date() %>

The Simplified Example

<%@ taglib prefix=“mytag" tagdir="/WEB-INF/tags/" %>

<html>

<body>

<h1>Hello. The time is: <mytag:date/></h1>

</body>

</html>

date.tag

taguse.jsp

In this new mechanism we use tagdir instead of uri we used in the old taglib implementation

cs236607

Page 28: 1 (Server-Side Programming using Java Server Pages) cs236607

28

<%@ attribute name="isLongFormat" required="false" %>

<%!private String createDate(String isLong) {

if ((isLong == null) || (isLong.equals("false"))) {

return new java.util.Date().toString();}

else { return new Long(new java.util.Date().getTime()).toString();}

} %>

<%=createDate(isLongFormat)%>

The Attributes Example

<%@ taglib prefix=“mytag" tagdir="/WEB-INF/tags/" %>

<html><body>

<h1>Hello.</h1>

<h2>The time is: <mytag:date3/></h2>

<h2>Milliseconds since the epoch : <mytag:date3 isLongFormat="true" /></h2>

</body></html>

date3.tag

taguse3.jsp

Private method declaration

Default and isLongFormat=“false” case

Calls the private method

isLongFormat=“true” case

Default case

isLongFormat=“true”

A new directive

The isLongFormat parameter is identified as the isLongFormat attribute because we used the attribute directive

cs236607

Page 29: 1 (Server-Side Programming using Java Server Pages) cs236607

29

Other Capabilities of Custom TagsAttributes

You can add validation mechanism for the attributes values

Tag BodyTag translation may choose to ignore, include

or change the tag body

cs236607

Page 30: 1 (Server-Side Programming using Java Server Pages) cs236607

30cs236607

Page 31: 1 (Server-Side Programming using Java Server Pages) cs236607

31

JSP Expression LanguageJSP expression language is a comfortable tool

to access useful objects in JSPThis language provides shortcuts in a

somewhat JavaScript-like syntaxAn expression in EL is written as ${expr}For example:

Hi, ${user}. <em style="${style}">Welcome</em>

Note that the EL expression does not violate the XML syntax as opposed to <%= expression %>

cs236607

Page 32: 1 (Server-Side Programming using Java Server Pages) cs236607

32

EL VariablesJSP EL does not recognize JSP's implicit

objects, but rather has its own setEach of these objects maps names to values

param, paramValues,

header ,headerValues,

cookie,

initParam,

pageScope, requestScope,

sessionScope, applicationScope

For example, use the param[“x”] or param.x to get the value of the parameter x

Map a parameter name to a single value or to multiple valuesMap a header name to a single value or to multiple valuesMaps a cookie name to a single value

Maps a context initialization parameter name to a single value

cs236607

Page 33: 1 (Server-Side Programming using Java Server Pages) cs236607

33

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 pageContext.getAttribute("x"), request.getAttribute("x"), etc.

Might be confusing. Make sure you know what you’re accessing!

cs236607

Page 34: 1 (Server-Side Programming using Java Server Pages) cs236607

34

Object PropertiesIn JSP EL, Property prop of Object o is referred to

as o[prop]Property prop of Object o is evaluated as follows:

If o is a Map object, then o.get(prop) is returned If o is a List or an array, then prop is converted into

an integer and o.get(prop) or o[prop] is returnedOtherwise, treat o “as a bean”, that is: convert p to a

string, and return the corresponding getter of o, that is o.getProp()

The term o.p is equivalent to o["p"]

cs236607

Page 35: 1 (Server-Side Programming using Java Server Pages) cs236607

35

An Example<% response.addCookie(new Cookie(“nameof",“homer"));

session.setAttribute(“homepage", new

java.net.URL("http://www.simpsons.com"));

String[] strs = {"str1","str2"};

session.setAttribute("arr", strs); %>

<html><head><title>JSP Expressions</title></head><body>

<form method="get" action="el.jsp">

<h2>Write the parameter x: <input name="x" type="text" />

<input type="submit" value="send" /></h2>

</form>

</body></html>

elcall.jspcs236607

Page 36: 1 (Server-Side Programming using Java Server Pages) cs236607

36

<%@ page isELIgnored="false" %>

<html>

<head><title>EL Examples</title></head>

<h1>Expression-Language Examples</h1>

<h2>Parameter <code>x</code>: ${param["x"]} </h2>

<h2>Cookie <code>name</code>:

${cookie.nameof.value}</h2>

<h2>Header <code>Connection</code>:

${header.Connection} </h2>

<h2>Path of session attr. <code>homepage</code>:

${sessionScope.homepage.path}</h2>

<h2>Element <code>arr[${param.x}]</code>:

${arr[param.x]} </h2>

</body></html>

el.jsp

The default value is TRUE

cookie[“nameof”].getValue()

header [“Connection”]

sessionScope[“homepage”].getPath(). You can omit the sessionScope

${…} means evaluate the expression inside the {}

Only the ${param.x} is evaluatedsessionScope[“arr”]

[param[“x”]cs236607

Page 37: 1 (Server-Side Programming using Java Server Pages) cs236607

37cs236607

Page 38: 1 (Server-Side Programming using Java Server Pages) cs236607

38

Simple XML Production

<?xml version="1.0"?>

<!DOCTYPE colors SYSTEM "colors.dtd">

<?xml-stylesheet type="text/xsl" href="colors.xsl"?>

<%! static String[] colors = {"red","blue","green"}; %>

<%@ page contentType="text/xml" %>

<colors>

<% for(int i=0; i<3; ++i) { %>

<color id="<%=i%>"><%= colors[i] %></color>

<% } %>

</colors>

JSP directive which sets the MIME-type of the result…

Ordinary XML declarations

Ordinary XML declarations

Link with XSL stylesheet

cs236607

Page 39: 1 (Server-Side Programming using Java Server Pages) cs236607

39

Generated XML<?xml version="1.0"?>

<!DOCTYPE colors SYSTEM "colors.dtd">

<?xml-stylesheet type="text/xsl" href="colors.xsl"?>

<colors>

<color id="0">red </color>

<color id="1">blue</color>

<color id="2">green</color>

</colors>

cs236607

Page 40: 1 (Server-Side Programming using Java Server Pages) cs236607

40

JSPX files are JSP files that have the extension jspx and have XML syntax

JSPX files are also referred to as JSP documentsSpecial JSP tags are used to replace non-XML JSP

symbols (<%, <%@, etc.) (Tags and EL can help too!)

The default content type of JSPX is text/xml (and not text/html)

You can also keep the .jsp suffix and tell the container that a JSP file acts as a JSPX file (and therefore its output is of XML type etc.)

JSPX Files (JSP Documents)

cs236607

Page 41: 1 (Server-Side Programming using Java Server Pages) cs236607

41

Advantages/Disadvantages of JSPXSince JSPX documents conform to a legal XML

structure you can:Check if the document is well formed XMLValidate the document against a DTDNest and scope namespaces within the documentUse all kinds of XML tools (e.g. editors)

The main disadvantage is JSPX documents they can grow very long and very (very) cumbersome

Much ado about nothing? Sometimes the above “advantages” simple aren’t needed or are of little help

cs236607

Page 42: 1 (Server-Side Programming using Java Server Pages) cs236607

42

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

<% Code %><jsp:scriptlet> Code

</jsp:scriptlet>

<%! Declaration %><jsp:declaration> Declaration </jsp:declaration>

<%@ Directive %> <jsp:directive.typeAttribute="value"/>

An empty element

cs236607

Page 43: 1 (Server-Side Programming using Java Server Pages) cs236607

43

Problems on the Way to a Legal XMLThe XML declaration (<?xml version="1.0"?>) and the

DOCTYPE definition are now those of the JSPX file.How do we include the declaration+dtd of the original

XML document in the result XML?Solution: use the <jsp:output> tag to explicitly require

DOCTYPE and XML declarations (next slide…)

How do we generate dynamic attribute values and still keep the document well formed?

Solution 1: use <jsp:element> for explicit element construction

Solution 2: use an EL expression

The following line is an illegal XML opening tag:<color id=“<jsp:expression>i</jsp:expression>“>

cs236607

Page 44: 1 (Server-Side Programming using Java Server Pages) cs236607

44

<?xml version=“1.0” ?><colors xmlns:jsp="http://java.sun.com/JSP/Page"><jsp:output doctype-root-element="colors" doctype-system="colors.dtd" /> <jsp:output omit-xml-declaration="false"/><jsp:declaration>static String[] colors = {"red","blue","green"};</jsp:declaration> <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet>

<jsp:element name="color"><jsp:attribute name="id"> <jsp:expression>i</jsp:expression></jsp:attribute>

<jsp:expression>colors[i]</jsp:expression></jsp:element>

<jsp:scriptlet>} </jsp:scriptlet></colors>

Namespace of basic JSP elements and Tag libraries..

Root element + DTD of the resulting XML

Do not omit the XML declaration of the result

The result is equivalent to the original line:

<color id="<%=i%>"><%= colors[i] %></color>

CDATA is used because of <.Altenatively: use &lt;

cs236607

Page 45: 1 (Server-Side Programming using Java Server Pages) cs236607

45

A Few More Problems on the WayWhere can we add an XSL declaration? It should

be:outside the root element (colors), but alsoafter jsp:output which must be defined after jsp

namespace declaration within the colors element…When using the include directive, the JSP might

become illegal XML with more than a single root

A solution: Use the <jsp:root> element as the document root

Does this solve all the problems which might arise when using the include directive?

cs236607

Page 46: 1 (Server-Side Programming using Java Server Pages) cs236607

46

<?xml version=“1.0” ?><jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page"> <jsp:output doctype-root-element="colors" doctype-system="colors.dtd" /> <jsp:output omit-xml-declaration="false"/> <![CDATA[<?xml-stylesheet type="text/xsl" href="colors.xsl"?>]]> <colors > <jsp:declaration>static String[] colors = {"red","blue","green"}; </jsp:declaration> <jsp:scriptlet><![CDATA[ for(int i=0; i<3; ++i) { ]]></jsp:scriptlet> <jsp:element name="color"> <jsp:attribute name="id"> <jsp:expression>i</jsp:expression></jsp:attribute> <jsp:expression>colors[i]</jsp:expression> </jsp:element> <jsp:scriptlet>}</jsp:scriptlet> </colors>

</jsp:root>

Now we can add the XSL

We use CDATA because of the <?, ?> etc

Still problematic: Which DTD should we use? the DTD should enable every JSP element within every other element…

cs236607

Page 47: 1 (Server-Side Programming using Java Server Pages) cs236607

LinksJSP Tutorial:

http://courses.coreservlets.com/Course-Materials/csajsp2.html

Advanced Tutorials: http://courses.coreservlets.com/Course-Materials/msajsp.html

JSP API: http://tomcat.apache.org/tomcat-5.5-doc/jspapi/

JSP Syntax Reference: http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html

cs236607 47