Java Collections Framework, Web Applications - Andres Teder

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

3 Νοε 2013 (πριν από 3 χρόνια και 7 μήνες)

88 εμφανίσεις

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
•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
–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
Add(Eelement) ,Remove(), Size()
Linked list
Circular Array
Doubly-linked list
14.10.2005Lecture 7 / Andres Teder8
•Always use the Interface type to hold the
Queue<Person> busStopQueue= new CircularArrayQueue<Person>(5);
or without Generics
Queue busStopPeople= new CircularArrayQueue(5);
14.10.2005Lecture 7 / Andres Teder9
•Collection-The root interface in the
collection hierarchy
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
•General implementations are not
synchronized, use:
public static <T>
<T> synchronizedCollection(
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>
<E> checkedCollection(
Collection<String> c = Collections.checkedCollection(newHashSet<String>(), String.class);
14.10.2005Lecture 7 / Andres Teder12
E next();
void remove();
•while (iter.hasNext() {
String element =;
•Order depends on the collection type
Element returned
14.10.2005Lecture 7 / Andres Teder13
Extending Collections
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
•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
•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
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
•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
–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
–the deployment descriptor
–directory for servlet and utility classes
–JAR archives
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
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
14.10.2005Lecture 7 / Andres Teder25
•Java Community Process
•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
•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
•Formally defined through JCP
–Can be thought of as generic server
–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
14.10.2005Lecture 7 / Andres Teder29
How Servlets Work
ClientWeb Server
J2EE Web
The Client Tier
The Web Tier
14.10.2005Lecture 7 / Andres Teder30
Enterprise Tiers
14.10.2005Lecture 7 / Andres Teder31
•Provide a hosting environment for software
components to run in
•Also: environment in which an application runs
–EJB container
–Web Container, Servlet Container, JSP Container
•Glossary -
14.10.2005Lecture 7 / Andres Teder32
•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
Interface defining methods all
servletsmust implement:
destroy(), init(), service(), ..
Abstract class defining a generic,
protocol independent servlet.
getInitParameters(), log(), …
Provides an abstract class to be
subclassedto create an HTTP
servlet: doGet(), doPost(), …
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
2.Servlet Container calls service()
•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
14.10.2005Lecture 7 / Andres Teder36
Simple Servlet
import javax.servlet.http.*;
import javax.servlet.*;
public class HelloServletextends HttpServlet{
public void doGet(HttpServletRequestreq,
throws ServletException, IOException{
PrintWriterout = res.getWriter();
out.println("Hello, world!");
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
•Contains key/value pairs of
•strings that are sent with the client request to the server in the query
String or posted form data
•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
•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
•For each web application an object
implementing javax.servlet.ServletContextis
•Context attributes are LOCAL to the JVM in
which they were created –should not be used
as a shared memory store in a distributed
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
–Session attributes–No, as multiple request threads
can access it
–Context attributes-No
14.10.2005Lecture 7 / Andres Teder42
Servlets And Thread Safety
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);
14.10.2005Lecture 7 / Andres Teder43
Servlets And Thread Safety
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);
14.10.2005Lecture 7 / Andres Teder44
Forward vs. Redirect
1. HTTP Request
2. Processing
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
•All objects stored in request attributes are lost
14.10.2005Lecture 7 / Andres Teder45
Forward vs. Redirect
•request is sent to another resource on the server,
without informing the client that a different resource is
going to process the request
1. HTTP Request
4. HTTP Response
2. Process
3. Perform
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
•Can be used for:
–Content compression (smaller downloads)
14.10.2005Lecture 7 / Andres Teder48
Mapping Servlet Filters
14.10.2005Lecture 7 / Andres Teder49
Servlet Filters
•Filter, FilterChain, FilterConfigin the javax.servletpackage
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
•Java Collections Framework
•Java Community Process
•Web Applications and Containers
•Thread issues