Java Server Pages (JSP) 11-11-2013 - Clarkson Confluencejsearlem/cs242/fa13/lectures/32.jsp.pdf ·...

Preview:

Citation preview

Java Server Pages (JSP)

11-11-2013

Safe copies cloning – take a second look at the contract copy constructor

Collections & Iterators Interfaces: List, Map, Set, … Implementations: ArrayList, LinkedList, HashMap, … use of for-each as an iterator

I/O Reader/Writer vs. Stream Scanner & Parsing a line of text into tokens Serialization

JavaFX GUIs and Design Patterns Event Handling Model

MVC, Observer, Strategy, Iterator, Composite

Review Session: 5:30 – 7:00 pm in the ITL

Practice problems

Understanding the Cloneable interface

no clone() method in the interface

the clone() method in Object is protected

A class must both implement Cloneable plus override the clone() method

essentially creates an object without using a constructor (although non-primitive fields within the object may be copied by calling their constructors)

the contract for clone is weak

must correct fields containing mutable objects, so final fields referring to mutable objects are a problem

A field that is a collection must be corrected (even if final)

There are cases where cloning is not a good design

… Complete this list Example?

A copy constructor for class X is of the form:

public X( X source )

i.e. the constructor has one argument which is an object of type X itself // Example: Copy constructor for class Swimmer

public Swimmer(Swimmer original) { this.name = original.name; this.swimTime = original.swimTime; this.eventDate = new Date(original.eventDate); // Date has copy ctr

}

Item 39: Make defensive copies when needed

What is a defensive copy?

Why is it important?

Key idea: separate Interfaces (ADT), Implementation (concrete code), Algorithms (polymorphic)

Collection of individual elements:

java.util Interface Collection<E> Subinterfaces: List, Set, Queue, Deque, SortedSet, etc.

Implementations: LinkedList, ArrayList, HashSet, etc.

Mapping: pairs <key, value>

java.util Interface Map<K,V> Implementations: HashMap, Hashtable, TreeMap etc.

Chapter 8, Item 52: Refer to objects by their interfaces

Why?

List<Student> roster = new ArrayList<Student>();

roster.add( new Student(“Jim”, … ) ); // adds to the end

traversing a collection

// when to use an interator?

for (Iterator itr = c.iterator(); itr.hasNext(); )

doSomethingWith(itr.next());

// preferred for most uses

for (Object o : collection)

doSomethingWith(o);

Suppose that compareTo() is inconsistent w/ equals() in some class X.

Sorted collections use compareTo(), but Collection/Set/Map use equals()

TreeSet of X will behave differently than HashSet of X if X.equals() is not consistent with X.compareTo()

(cf. Effective Java 2, pp. 63-64)

try {

Scanner scan = new Scanner(new File(“sample.txt”));

int val = scan.nextInt();

System.out.println(“Integer value is: “ + val);

} catch (InputMismatchException e) {

System.err.println(“Next token is not an int”);

} catch (FileNotFoundException e) {

System.err.println(“Could not open file for reading”);

} catch (IOException e) {

System.err.println(“Unexpected IO error: “ + e);

}

// Read and echo lines, using Scanner

try {

Scanner scan = new Scanner(new File(“MyData.txt”) );

scan.useDelimiter(

System.getProperty(“line.separator”));

while ( scan.hasNext() )

System.out.println( scan.next() );

scan.close();

} catch // appropriate exceptions

Any object that implements the serializable interface can be converted into a sequence of bytes

Implements “lightweight persistence”;

persistance – object’s lifetime is independent of program execution (lives even when the program terminates)

Serializable interface – no methods, just tagging

// what are the issues and potential problems?

Item 74: Implement Serializable judiciously

Effective Java 2, pp. 289 – 294

Major cost – decreases flexibility to change a class’s implementation once it has been released

Potential for bugs and security holes (deserialization is another way to create an object)

Increases testing associated with releasing a new version of a class

revisited

cf. Head First Servlets & JSP, 2nd Edition, 2008

cf. Head First Servlets & JSP, 2nd Edition, 2008

Write a servlet class (extends HttpServlet)

Create a deployment descriptor (DD) web.xml

one DD per web application

a single DD can declare many servlets

a <servlet-name> ties the <servlet> element to the <servlet-mapping> element

a <servlet-class> is the Java class name

a <url-pattern> is the name the client uses for the request

Build a directory tree under tomcat/webapps

the web.xml file goes in WEB-INF

the Java class file goes in WEB-INF/classes

Client-known URL name

e.g. click a link to a servlet

Deployer-known internal name

known only to the deployer

doesn’t have to match the public URL used by the client, or the real file and path to the servlet class

Actual file name developer’s servlet class file

Note: mapping servlet names improves flexibility and security

web.xml

a single DD can declare many servlets

the <servlet-name> is used only by the deployer

end-users don’t see it;

<servlet-name> ties the <servlet> element to the <servlet-mapping> element

<servlet-class> is the fully-qualified Java class name (without the .class extension)

<url-pattern> is what the client uses for the request

<servlet-mapping> is what the Container uses at

runtime when a request comes in

web.xml

the DD can also customize security roles, error pages, tag libraries, initial configuration information

If using a full J2EE server, the DD can also specify specific enterprise javabeans that will be used

lets you adapt your application to different resources, such as databases, without having to re-compile and test any code

makes it easier to maintain dynamic security info like access control lists and security roles

MVC takes the business logic out of the servlet and puts it in a “Model” – a reusable Java class

cf. Head First Servlets & JSP, 2nd Edition, 2008

specifies the static HTML code and the dynamic information that the user of the web application sees in a browser

provides a connection to JavaBeans that carry out computations

each JSP page is automatically translated into a servlet

servlet/CGI tightly interleaves programming logic with HTML generation

related technologies (used with XML) include: ASP (Microsoft Active Server Pages) & ASP.NET (JScript,

VBScript and C#) PHP – perl-like scripting language

Python (with a Web Framework like DJANGO)

idea: separate programming & presentation embed code related to presentation within a web document

A JavaBean is a Java class with the following properties:

By convention the name of the bean ends in Bean

It must have a default constructor

A JavaBean exposes its properties through get and set

methods, which follow a naming convention

If the property name is propertyName and the type is Type accessor method: Type getPropertyName()

mutator method: void setpropertyName(Type newValue)

A boolean property uses a different convention boolean isPropertyName() void setPropertyName(boolean newValue)

To use a bean in a JSP page, use the jsp:useBean directive

The following directive invokes the default constructor of

StudentBean, and makes an object with the name user

<jsp:useBean id ="user" class=“StudentBean"/>

To set a property in the bean, use the setProperty directive

<jsp:setProperty name="user" property=“major" value=“36"/>

To get a property in the bean, use the getProperty directive

<jsp:getProperty name="user" property="major"/>

This returns a string that becomes part of the HTML page

Display just the current time, not the whole date, on a page

Get the time with the getTimeInstance method of the

DateFormat class

Put this code in a bean class: TimeFormatter.java

File: TimeFormatterBean.Java

import java.text.DateFormat;

import java.util.Date;

/**

This bean formats the time of day from a given date.

*/

public class TimeFormatterBean {

private DateFormat timeFormatter;

private Date theDate;

/**

Initializes the formatter.

*/

public TimeFormatterBean() {

timeFormatter = DateFormat.getTimeInstance();

}

/** Write-only data property */

public void setDate(Date aDate) {

theDate = aDate;

}

/** Read-only time property */

public String getTime()

{

String timeString = timeFormatter.format(theDate);

return timeString;

}

} // end TimeFormatterBean

TimeFormatterBean, continued

File: time.jsp

<jsp:useBean id="formatter" class="TimeFormatterBean"/>

<jsp:setProperty name="formatter" property="date"

value="<%= new java.util.Date() %>"/>

<html>

<head>

<title>Time JSP</title>

</head>

<body>

<h1>Time JSP</h1>

<p>The current time is:

<jsp:getProperty name="formatter" property="time"/>

</p>

</body>

</html>

It is a good idea to put the bean directive at the beginning of

the JSP file, before the HTML

Both time.jsp and TimeFormatterBean must be

deployed to the proper directories

time.jsp into $CATALINA\webapps\cs242

TimeFormatterBean into $CATALINA\webapps\cs242\WEB-INF\classes

Executable Jar

Web Start RMI app Servlets

100% Local 100% Remote

■ Executable JAR

■ Web Start

■ RMI

■ Java Server Faces, JSP & Servlets

Note: “thin” (web) clients run mostly on the server; “rich” clients run mainly on the client machine

The client runs a web browser. The client also needs Java and the Java Web Start “helper app”.

client can easily download JWS client can easily download Java or update the

version

The server has a web page with a link to a file which can “launch” the executable JAR (more on this later)

When the client clicks on that link, JWS downloads and launches the app on the client machine by invoking the main() method

Once downloaded, the app runs on the client machine, as a stand-alone application

Since the app has been downloaded to the client, it can run from the JWS helper app independently of the browser.

If the code is changed on the server side, JWS automatically downloads and integrates the updated code