Java Collections Framework, Web Applications - Andres Teder

sizzledgooseΛογισμικό & κατασκευή λογ/κού

3 Νοε 2013 (πριν από 4 χρόνια και 5 μέρες)

100 εμφανίσεις

14.10.2005Lecture 7 / Andres Teder1
Java Collections Framework
Web Applications
14.10.2005Lecture 7 / Andres Teder2
When talking about Java 5 …
•Java 6 has been on the way already for a
while

http://today.java.net/download/jdk6/
•Can download the source under Java
Research Licence replaces the SCSL
14.10.2005Lecture 7 / Andres Teder3
Java Collections Framework
•Way of structuring data inside classes
•Before JDK 1.2
–Vector –growablearray of objects
–Hashtable
–BitSet–Vector of bits
–Enumeration –abstract mechanism for
visiting elements in an arbitrary container
14.10.2005Lecture 7 / Andres Teder4
Java Collections Framework
14.10.2005Lecture 7 / Andres Teder5
Java Collections Framework
•Legacy classes
14.10.2005Lecture 7 / Andres Teder6
Java Collections Framework
•Separating interfaces and implementations
14.10.2005Lecture 7 / Andres Teder7
Queues
Add(Eelement) ,Remove(), Size()
Implementations
Linked list
Circular Array
Interface
Doubly-linked list
14.10.2005Lecture 7 / Andres Teder8
Collections
•Always use the Interface type to hold the
reference
Queue<Person> busStopQueue= new CircularArrayQueue<Person>(5);
or without Generics
Queue busStopPeople= new CircularArrayQueue(5);
14.10.2005Lecture 7 / Andres Teder9
Collection
•Collection-The root interface in the
collection hierarchy
booleanadd(Eelement);
Iterator<E> iterator();

lots of different utility methods isEmpty() etc
14.10.2005Lecture 7 / Andres Teder10
Collection interfaces
•All modification methods are optional
•Some terms
–modifiable –supports modification operations
(opposite: unmodifiable)
–immutable –collections that cannot be changed by
the client AND will never change for any other reason
(opposite: mutable)
–fixed-size–collections the size of which remains
constant (opposite: variable size)
–random-access–collections that support fast indexed
access (opposite: sequential-access)
14.10.2005Lecture 7 / Andres Teder11
Collections
•General implementations are not
synchronized, use:
public static <T>
Collection
<T> synchronizedCollection(
Collection
<T>c)
EXAMPLES:
Collection c = Collections.synchronizedCollection(newArrayList());
List list= Collections.synchronizedList(newArrayList());
Set s = Collections.synchronizedSet(newHashSet());
Map m = Collections.synchronizedMap(newHashMap());
•Dynamically typesafeview
public static <E>
Collection
<E> checkedCollection(
Collection
<E>c,
Class
<E>type)
EXAMPLE:
Collection<String> c = Collections.checkedCollection(newHashSet<String>(), String.class);
14.10.2005Lecture 7 / Andres Teder12
Iteration
•Iterator
E next();
booleanhasNext();
void remove();
•while (iter.hasNext() {
String element = iter.next();
dosomethingwithelement
}
•Order depends on the collection type
IteratorIteratorIterator
Element returned
14.10.2005Lecture 7 / Andres Teder13
Extending Collections
•AbstractCollection
•AbstractQueue
•…
14.10.2005Lecture 7 / Andres Teder14
Concrete Collection Classes
•ArrayList-An indexed sequence that grows and shrinks dynamically
–ArrayListvs. Vector = ArrayListis not synchronized
•LinkedList-An ordered sequence that allows efficient insertions and
removal at any location
–Also listIterator(); for adding/removing elements
•Hashset-An unordered collection that rejects duplicates
–Useful when order is not important, but finding elements quicklyis
•TreeSet-A sorted set
–By default expects elements to implement Comparableinterface
–Can also pass a Comparatorto the constructor
•EnumSet–A set of enumerated type values
•LinkedHashSet–A set that remembers the order in which elements
were inserted
•PriorityQueue–A collection that allows efficient removal of the
smallest element
14.10.2005Lecture 7 / Andres Teder15
Concrete Collection Classes
•HashMap–A data structure that stores key/value
associations
•TreeMap–A map in which the keys are sorted
•EnumMap–A map in which the keys belong to an
enumerated type
•LinkedHashMap–A map that remembers the order in
which entries were added
•WeakHashMap–A map with values that can be
reclaimed by the garbage collector if they are not used
elsewhere
•IdentityHashMap–A map where keys are compared by
==not equals(), different key objects are considered
distinct even if they have equal contents
14.10.2005Lecture 7 / Andres Teder16
Learning more about Collections
•http://java.sun.com/docs/books/tutorial/coll
ections/
14.10.2005Lecture 7 / Andres Teder17
Java Web Applications
Java Web Applications
14.10.2005Lecture 7 / Andres Teder18
Defining Web Applications
•A Web application is a collection of
Servlets, HTML pages, classes, and other
resources that make up a complete
application on a Web server. The Web
application can be bundled and run on
multiple containers from multiple vendors.
14.10.2005Lecture 7 / Andres Teder19
Web Application Contents
•Java Server Pages
•Servlets
•Different Utility Classes
•Static documents (HTML, images, ..)
•Client-side classes (Applets, beans, ..)
•Meta information bundling it all together
14.10.2005Lecture 7 / Andres Teder20
Web-Application structure
•Structured hierarchy of directories
•WEB-INF
–All the things of the application
that are not in the document root
–The contents may not be directly
served to the clients by the container
14.10.2005Lecture 7 / Andres Teder21
WEB-INF
•/mywebapp(root)
login.html
index.html
/images
frontimage.jpg
/WEB-INF/
web.xml
–the deployment descriptor
/classes
–directory for servlet and utility classes
/lib
–JAR archives
/META-INF
MANIFEST.MF
14.10.2005Lecture 7 / Andres Teder22
Deployment Descriptor
•DTD part of the Java Servlet Specification
•Initialization Parameters
•Session Configuration
•Servlet/JSP Definitions
•Servlet/JSP Mappings
•MIME Type Mappings
•Welcome File List
•Error Pages
•Security
14.10.2005Lecture 7 / Andres Teder23
Web Application Archives
•WAR files
–Standard way of Web Application deployment
–JAR (zipped) files
–Contain the web application with a correct
directory structure
–Can be auto-deployed by the container
14.10.2005Lecture 7 / Andres Teder24
JCP
14.10.2005Lecture 7 / Andres Teder25
JCP
•Java Community Process

http://www.jcp.org
•Established in 1995, process that “guards”
the evolution of the Java platform
•JSR –Java Specification Requests are
formal documents that describe proposed
specifications and technologies to be
added to the Java platform.
14.10.2005Lecture 7 / Andres Teder26
JCP
•A final JSR provides a reference implementationwhich
provides a free implementation of the technology in
source code form and a Technology Compatibility Kitto
verify the APIspecification
•At the moment –925 JSRs
14.10.2005Lecture 7 / Andres Teder27
Servlets
•Formally defined through JCP
•Servlets
–Can be thought of as generic server
extensions
–Application that is run by the server-side on
behalf of the client
–Sun: A servletis a Java programming
language class used to extend the capabilities
of servers that host applications accessed via
a request-response programming model
14.10.2005Lecture 7 / Andres Teder28
Latest Servlet Specification
•Version 2.4 JSR-154 (24 Nov, 2003)
•Part of J2EE 1.4 (24 Nov, 2003)
•Requires HTTP/1.1
•web.xmluses Schema
•The Servlet APIdefines the expected
interactions of a web containerand a
servlet
14.10.2005Lecture 7 / Andres Teder29
How Servlets Work
ClientWeb Server
J2EE Web
Container
JSP
Servlets
The Client Tier
The Web Tier
14.10.2005Lecture 7 / Andres Teder30
Enterprise Tiers
14.10.2005Lecture 7 / Andres Teder31
Containers
•Provide a hosting environment for software
components to run in
•Also: environment in which an application runs
•J2EE
–EJB container
–Web Container, Servlet Container, JSP Container
•Glossary -http://java.sun.com/j2ee/1.4/docs/glossary.html
14.10.2005Lecture 7 / Andres Teder32
Servlets
•Are not run by web servers directly –they need a special
container -servlet engine / servlet container
•A single heavyweight process
•Each user has a lightweight thread, handled by JVM to
process requests –by default servletsare multithreaded
•SingleThreadModel-Ensures that servletshandle only
one request at a time.
Note! Deprecated in Spec 2.4
•Mapped to URLs
•Can exploit the whole set of Java APIs
14.10.2005Lecture 7 / Andres Teder33
Servlets
Servlet
GenericServlet
HttpServlet
Interface defining methods all
servletsmust implement:
destroy(), init(), service(), ..
Abstract class defining a generic,
protocol independent servlet.
getInitParameters(), log(), …
ServletConfig
Provides an abstract class to be
subclassedto create an HTTP
servlet: doGet(), doPost(), …
MyHttpServlet
14.10.2005Lecture 7 / Andres Teder34
Servlet Lifecycle
1.Servlet Container calls init()
•javax.servlet.ServletConfigobject initialized
•Called only once during Servlet’slifetime
•Developers not required to implement this
method
2.Servlet Container calls service()
service(ServletRequest,ServletResponse)
•Called in response to a request
14.10.2005Lecture 7 / Andres Teder35
Servlet Lifecycle II
3.When servlet container is to remove the
servlet it calls the destroy()method,
where the Servlet can release its
resources
14.10.2005Lecture 7 / Andres Teder36
Simple Servlet
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServletextends HttpServlet{
public void doGet(HttpServletRequestreq,
HttpServletResponseres)
throws ServletException, IOException{
PrintWriterout = res.getWriter();
out.println("Hello, world!");
out.close();
}
}
14.10.2005Lecture 7 / Andres Teder37
Scope -Request
•Scope -range in which a variable can be referenced
•Request Scope
–Each time a client issues an HTTP request, the server creates
an object that implements the
javax.servlet.http.HttpServletRequestinterface
•Contains key/value pairs of
–Parameters
•strings that are sent with the client request to the server in the query
String or posted form data
•getParameter(String)
•getParameterValues(String)
–Attributes
•When the response is fulfilled the JVM can garbage
collect the request and attributes
14.10.2005Lecture 7 / Andres Teder38
Scope -Session
•The web container will create an object that
implements the javax.servlet.http.HttpSession
interface to identify a user across multiple page
requests.
•Times out –configurable
•Can be terminated by calling invalidate()
•Can also store attributes as key/value pairs
•No synchronization provided by the container!
14.10.2005Lecture 7 / Andres Teder39
Scope -Application
•Objects that are visible to all client and threads
of the current web application
•Live until explicitly removed or application
terminates
•For each web application an object
implementing javax.servlet.ServletContextis
created
•Context attributes are LOCAL to the JVM in
which they were created –should not be used
as a shared memory store in a distributed
container
14.10.2005Lecture 7 / Andres Teder40
Scope -Page
•JSP related
•Only accessible within the JSP page that
they are created
•Stored in the
javax.servlet.jsp.PageContextobject for
each page
14.10.2005Lecture 7 / Andres Teder41
Servlets and Thread safety
•Which attribute scopes are Thread-safe?
–Local variables–Yes, new instance for each calls
–Instance variables–No, as they can be accessed by
concurrent threads
–Class variables–Not in any way
–Request attributes–No, because the request object
is re-used between service requests and cannot hold
a reference to the request object beyond the service
method
–Session attributes–No, as multiple request threads
can access it
–Context attributes-No
14.10.2005Lecture 7 / Andres Teder42
Servlets And Thread Safety
Example
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServletextends HttpServlet{
String requestAction;
public void doGet(HttpServletRequestreq,HttpServletResponseres) throws
ServletException, IOException{
requestAction= req.getParameter(“action”);
// Other processing…(lengthy operations)
PrintWriterout = res.getWriter();
out.println(“Requestaction is:“+requestAction);
out.close();
}
}
14.10.2005Lecture 7 / Andres Teder43
Servlets And Thread Safety
Example
import java.io.*;
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServletextends HttpServlet{
public void doGet(HttpServletRequestreq,HttpServletResponseres) throws
ServletException, IOException{
String requestAction;
requestAction= req.getParameter(“action”);
// Other processing…(lengthy operations)
PrintWriterout = res.getWriter();
out.println(“Requestaction is:“+requestAction);
out.close();
}
}
14.10.2005Lecture 7 / Andres Teder44
Forward vs. Redirect
Browser
Web
Container
1. HTTP Request
2. Processing
Request
3. 302 Response Returned
4. New HTTP Request
5. HTTP Response
•A way to share control of a request by more than a
single component
•Redirect
•All objects stored in request attributes are lost
•response.sendRedirect(String);
14.10.2005Lecture 7 / Andres Teder45
Forward vs. Redirect
•Forward
•request is sent to another resource on the server,
without informing the client that a different resource is
going to process the request
•RequestDispatcher.forward(Stringpath);
Client
Web
Container
1. HTTP Request
4. HTTP Response
2. Process
Request
3. Perform
Forward
14.10.2005Lecture 7 / Andres Teder46
Forward vs. Redirect
•Generally forward preferred
•Forward is more efficient
•Redirect though leaves the client
application in a correct state
14.10.2005Lecture 7 / Andres Teder47
Servlet Filters
•Introduced in Spec 2.3
•A filterprovides an abstracted method of
manipulating a client's request and/or response
before it actually reaches the endpoint of the
request
•Can be used for:
–Authentication
–Content compression (smaller downloads)
–Logging
–…
14.10.2005Lecture 7 / Andres Teder48
Mapping Servlet Filters
14.10.2005Lecture 7 / Andres Teder49
Servlet Filters
•Filter, FilterChain, FilterConfigin the javax.servletpackage
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TimerFilterimplements Filter {
private FilterConfigconfig= null;
public void init(FilterConfigconfig) throws ServletException{
this.config= config;
}
public void destroy() {
config= null;
}
public void doFilter(ServletRequestrequest, ServletResponseresponse,
FilterChainchain) throws IOException, ServletException{
long before = System.currentTimeMillis();
chain.doFilter(request, response);
long after = System.currentTimeMillis();
String name = "";
if (request instanceofHttpServletRequest) {
name = ((HttpServletRequest)request).getRequestURI();
}
config.getServletContext().log(name+ ": " + (after -before) + "ms");
}
}
14.10.2005Lecture 7 / Andres Teder50
Summary
•Java Collections Framework
•Java Community Process
•Web Applications and Containers
•Servlets
•Scope
•Thread issues
•Filters