Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
-config : FilterConfig
-logPrefix : String
init(FilterConfig)
doFilter(ServletRequest,
ServletResponse,
FilterChain)
destroy()
FilterConfig
interface
getFilterName():String
getInitParameter(name):String
getInitParameterNames():Enum
getServletContext():ServletContext
FilterChain
interface
doFilter(ServletRequest,
ServletResponse)
Filter
interface
init(FilterConfig)
doFilter(ServletRequest,
ServletResponse,
FilterChain)
destroy()
The web container implements the
FilterConfig and FilterChain
interfaces.
Your filter class must implement
the Filter interface.
PerformanceFilter
Web Component Development With Servlet and JSP Technologies Module 9, slide 24 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Performance Filter Example
1 package sl314.web;
2
3 import java.io.IOException;
4
5 import javax.servlet.ServletRequest;
6 import javax.servlet.ServletResponse;
7 import javax.servlet.ServletException;
8 import javax.servlet.http.HttpServletRequest;
9
10 import javax.servlet.Filter;
11 import javax.servlet.FilterChain;
12 import javax.servlet.FilterConfig;
13
14 public class PerformanceFilter implements Filter {
15
16 private FilterConfig config;
17 private String logPrefix;
18
19 public void init(FilterConfig config)
20 throws ServletException {
21 this.config = config;
22 logPrefix = config.getInitParameter(Log Entry Prefix);
23 }
Web Component Development With Servlet and JSP Technologies Module 9, slide 25 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Performance Filter Example
24
25 public void doFilter(ServletRequest request,
26 ServletResponse response, FilterChain chain)
27 throws ServletException, IOException {
28
29 long begin = System.currentTimeMillis();
30 chain.doFilter(request, response);
31 long end = System.currentTimeMillis();
32
33 StringBuffer logMessage = new StringBuffer();
34 if (request instanceof HttpServletRequest) {
35 logMessage = ((HttpServletRequest)request).getRequestURL();
36 }
37 logMessage.append(: );
38 logMessage.append(end - begin);
39 logMessage.append( ms);
40
41 if(logPrefix != null) {
42 logMessage.insert(0,logPrefix);
43 }
44
45 config.getServletContext().log(logMessage.toString());
46 }
Web Component Development With Servlet and JSP Technologies Module 9, slide 26 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Performance Filter Example
47
48 public void destroy() {
49 config = null;
50 logPrefix = null;
51 }
52
53 }
Web Component Development With Servlet and JSP Technologies Module 9, slide 27 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Configuring the Filter
Using Annotations
@WebFilter(filterName="PerfFilter",
urlPatterns={"*.do"},
dispatcherTypes={
DispatcherType.FORWARD,
DispatcherType.ERROR,
DispatcherType.REQUEST,
DispatcherType.INCLUDE},
initParams={
@WebInitParam(
name="Log Entry Prefix",
value="Performance:"
)
})
Web Component Development With Servlet and JSP Technologies Module 9, slide 28 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Configuring the Filter
Using a deployment descriptor
<filter>
<filter-name>perfFilter</filter-name>
<filter-class>
sl314.web.PerformanceFilter
</filter-class>
<init-param>
<param-name>Log Entry Prefix</param-name>
<param-value>Performance: </param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>perfFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Web Component Development With Servlet and JSP Technologies Module 9, slide 29 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Configuring the Filter
<servlet-name> element can replace <url-pattern> so that a
filter can be mapped to a servlet rather than a URL pattern
Multiple filters can be specified for a URL or a servlet,
resulting in chains
Web Component Development With Servlet and JSP Technologies Module 9, slide 30 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Filter Chaining Example
<servlet-mapping>
<servlet-name>FrontController</servlet-name>
</url-pattern>*.do</url-pattern>
</servlet-mapping>
<filter-mapping>
<filter-name>perfFilter</filter-name>
<servlet-name>FrontController</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>auditFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>transformFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
Web Component Development With Servlet and JSP Technologies Module 9, slide 31 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Filter Chaining Example
For a request to:
/admin/add_league.do
Filter specification calls (in order)
auditFilter
transformFilter
perfFilter
Web Component Development With Servlet and JSP Technologies Module 9, slide 32 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Filter Dispatch Options
Filters may be applied to the initial request from a client
Or to requests to:
Include a page
Forward to a page
Invoke an error page
Control this with the <dispatcher> element:
<filter-mapping>
<filter-name>auditFilter</filter-name>
<url-pattern>*.do</url-pattern>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
Note this this example configuration does not invoke based
on initial client request
Web Component Development With Servlet and JSP Technologies Module 9, slide 33 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handling Multipart Forms
Part
getContentType()
getInputStream()
delete()
write(String filename)
request.getPart(String)
Collection <Part> request.getParts()
MultipartConfig
fileSizeThreshold
maxRequestSize
maxFileSize
location
Web Component Development With Servlet and JSP Technologies Module 9, slide 34 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handling Multipart Forms
@WebServlet(name="Upload", urlPatterns={"/Upload"})
@MultipartConfig(location="/tmp")
public class Upload extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
Part p = request.getPart("desc");
BufferedReader r = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String desc = r.readLine();
request.setAttribute("desc", desc);
p = request.getPart("data");
p.write("DATAFILE");
RequestDispatcher rd =
request.getRequestDispatcher("acknowledge.jsp");
rd.forward(request, response);
}
}
Web Component Development With Servlet and JSP Technologies Module 9, slide 35 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handling Multipart Forms
<form action="Upload" enctype="multipart/form-data" method="post">
Description: <input type="text" name="desc"/>
File: <input type="file" name="data"/>
<input type="submit" value="Upload"/>
</form>
Web Component Development With Servlet and JSP Technologies Module 9, slide 36 of 36
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Summary
The lifecycle of a servlet
The threading model of a servlet
Filters and how to apply them to groups of servlets or JSPs
Handling multipart form data
Web Component Development With Servlet and JSP Technologies
Module 10
More Options for the Model
Module 10
More Options for
the Model
Web Component Development With Servlet and JSP Technologies Module 10, slide 2 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Objectives
Understand the nature of the model as a macro-pattern
Implement persistent storage for your web applications using
JDBC or Java Persistence API
Web Component Development With Servlet and JSP Technologies Module 10, slide 3 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Relevance
What goes into a model component? Is it actually just a
simple piece of the application, or more than that?
How can you provide persistent storage for data in your web
applications?
Web Component Development With Servlet and JSP Technologies Module 10, slide 4 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
The Model as a Macro-Pattern
Model responsibilities
Present an interface to the controller
Implement the business logic
Present data to the view component
OO suggests this might require multiple objects
Web Component Development With Servlet and JSP Technologies Module 10, slide 5 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
The View Helper Pattern
OO designs without regard to use
View using EL benefits from convenient data presentation
Consider an adapter component that reformats the models
interface for the convenience of the view
Web Component Development With Servlet and JSP Technologies Module 10, slide 6 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
The Data Access Object Pattern
Persistence is not a natural function of a data model
OO says it should be separate
Result is the Data Access Object pattern (DAO)
RegisterService
+getLeague
+getPlayer
+register
LeagueService
+getLeague
+createLeague
AddLeagueAction
execute
execute
PlayerDAO
package-private
insert
LeagueDAO
package-private
retrieve
insert
ObjectIDDAO
League
Player
package-private
getNextObjectID
SelectDivisionAction
Database
Web Component Development With Servlet and JSP Technologies Module 10, slide 7 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
DAO Pattern Advantages
Separates domain object from persistence logic
Promotes reuse and flexibility
Data access code can be reused
Facilitates changes to front-end technologies
Facilitates changes to back-end technologies
Web Component Development With Servlet and JSP Technologies Module 10, slide 8 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
JDBC API
Provides connectivity with databases
Interfaces support connections, statements, and results
Connection pooling is advised
Supported directly by JDBC v2
Web Component Development With Servlet and JSP Technologies Module 10, slide 9 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Developing a Web Application Using a
Database
java.sql.DriverManager.getConnection obtains an
exclusive connection
Poor scaling behavior
javax.sql.DataSource simplifies pooling and is
portable across application servers and deployments
javax.sql.DataSource is obtained from a JNDI lookup
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup(java:comp/env/
jdbc/leagueDB);
Web Component Development With Servlet and JSP Technologies Module 10, slide 10 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Obtaining a Pooled Connection
DataSource.getConnection usually returns a
connection from a pool
prepareStatement()
getConnection()
lookup(jdbc/leagueDB)
Web Container
:DataSource
:DataSource
:LeagueDAO
Database
JNDI Subsystem
in use
available
c1
c4
c3 c5
3
1
2
2a
c2:Connection
c2
Web Component Development With Servlet and JSP Technologies Module 10, slide 11 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Releasing a Pooled Connection
Closing the connection returns it to the pool
close()
Web Container
:DataSource
:LeagueDAO
Database
in use
available
c1
c4
c3 c5
1a
c2:Connection
c2
1
Web Component Development With Servlet and JSP Technologies Module 10, slide 12 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Executing SQL
1 ds = (DataSource)ctx.lookup(
2 java:comp/env/jdbc/leagueDB);
3 if ( ds == null ) {
4 throw new RuntimeException(DataSource not found.);
5 }
6 connection = ds.getConnection();
7 stmt = connection.prepareStatement(
8 SELECT * FROM LEAGUE_TABLE WHERE year=?1 and season=?2);
9 stmt.setInt(1, year);
10 stmt.setString(2, season);
11 results = stmt.executeQuery();
12 while ( results.next() ) {
13 int objectID = results.getInt(LID);
14 num_of_rows++;
15 if ( num_of_rows > 1 ) {
16 throw new SQLException(Too many rows.);
17 }
18 int theYear = results.getInt(year),
19 String theSeason = results.getString(season),
20 }
Web Component Development With Servlet and JSP Technologies Module 10, slide 13 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Configuring a DataSource
The database and tables must exist
A connection pool must be prepared for that database
A JNDI entry must refer to the pool
These actions require platform specific knowledge and
techniques
Web Component Development With Servlet and JSP Technologies Module 10, slide 14 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Object Relational Mapping Software
Computation is done with objects, persistence is done with
relational databases
Object relational mapping (ORM) software seeks to simplify
the integration of these two
ORM uses declarative mapping instrutions, in preference to
hand-written code
Customer
Entity
Component
Customer
Web Component Development With Servlet and JSP Technologies Module 10, slide 15 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Mapping Relationships
Customer
Customer
Account
Account
Address
Address
Customer
Entity
Component
Customer
Account
Address
Basic mapping One-to-Many Mapping
Web Component Development With Servlet and JSP Technologies Module 10, slide 16 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Java Persistence API Structure
An entity, defined by the programmer
Mappings from entity to the database
Annotations or default rules
persistence.xml specifying the DataSource
JNDI lookup service
A DataSource connected to a connection pool
A connection pool connected to the database
The database with appropriate tables
Web Component Development With Servlet and JSP Technologies Module 10, slide 17 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Entity Class Requirements
Declare a public class
Class must not be final, methods cannot be final
Class may be abstract
Class must not be inner
Annotate the class with javax.persistence.Entity
Declare the attributes, these must not be public
Declare public business, accessor, and mutator methods as
necessary
Annotate the primary key field or accessor methodusing the
Id annotation
Verify and override the default mapping
Web Component Development With Servlet and JSP Technologies Module 10, slide 18 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Entity Class Example
1 package entity;
2
3 import java.io.Serializable;
4 import javax.persistence.Column;
5 import javax.persistence.Entity;
6 import javax.persistence.GeneratedValue;
7 import javax.persistence.GenerationType;
8 import javax.persistence.Id;
9
10 @Entity
11 public class Airplane implements Serializable {
12 private static final long serialVersionUID = 1L;
13 @Id
14 @GeneratedValue(strategy = GenerationType.AUTO)
15 private String id;
16 @Column private String type;
17 @Column private int engines;
Web Component Development With Servlet and JSP Technologies Module 10, slide 19 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Entity Class Example
18
19 public String getId() { return id; }
20
21 public void setId(String id) { this.id = id; }
22
23 public String getType(){ return type; }
24
25 public void setType(String type){ this.type = type; }
26
27 public int getEngines() { return engines; }
28
29 public void setEngines(int engines){ this.engines = engines; }
30
31 }
Web Component Development With Servlet and JSP Technologies Module 10, slide 20 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Verifying and Overriding the Default Mapping
Mapped items:
Overriding default table mapping
@Entity
@Table(name = Cust) // Use Cust db table
Overriding default column mapping
public class Client {
@Column(name = cname)
private String clientName;
Object Tier Element Database Tier Element
Entity class Database table
Field of entity class Database table column
Entity instance Database table record
Web Component Development With Servlet and JSP Technologies Module 10, slide 21 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Primary Key Generation
Specifying automatic primary key generation
public class Client {
@Id
@GeneratedValue(strategy =
GenerationType.AUTO)
private int clientReference;
Web Component Development With Servlet and JSP Technologies Module 10, slide 22 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Persistence Units
persistence.xml file defines entities controlled by the
manager
Persistence unit is limited to a single DataSource
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://
java.sun.com/xml/ns/persistence">
<persistence-unit name=
"BrokerTool-ejb" transaction-type="JTA">
<jta-data-source>
StockMarket
</jta-data-source>
<jar-file>BrokerLibrary.jar</jar-file>
<properties/>
</persistence-unit>
</persistence>
Web Component Development With Servlet and JSP Technologies Module 10, slide 23 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Persistence Context
Working copy of persistence unit
Lifetime typically per-transaction
Limits entity instances to one per identity
Managed through EntityManager
Web Component Development With Servlet and JSP Technologies Module 10, slide 24 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
EntityManager
Methods, such as flush, find, and createQuery
Provides some of the EJB 2.1 home interface functionality
Obtained through dependency injection
@PersistenceContext private EntityManager em;
find loads a specific entity by primary key
createQuery prepares a lookup, getResultList might
be used to execute the query
persist inserts a new entity
merge updates a modified entity
remove deletes an entity
Web Component Development With Servlet and JSP Technologies Module 10, slide 25 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
User Transactions
Allows control over transaction boundaries
Created by injection
import javax.transaction.UserTransaction;
[...]
// Declaring a field in the class:
@Resource UserTransaction utx;
begin, commit, rollback, setRollbackOnly
Web Component Development With Servlet and JSP Technologies Module 10, slide 26 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Java Persistence API Example
1 @WebServlet(name="AddServlet", urlPatterns={"/AddServlet"})
2 public class AddServlet extends HttpServlet {
3 @PersistenceContext EntityManager em;
4 @Resource UserTransaction utx;
5
6 protected void processRequest(HttpServletRequest request,
7 HttpServletResponse response)
8 throws ServletException, IOException {
9 try {
10 assert em != null;
11 String id = request.getParameter("id");
12 String type = request.getParameter("type");
13 int engines =
14 Integer.parseInt(request.getParameter("engines"));
15 Airplane a = new Airplane();
16 a.setId(id);
17 a.setType(type);
18 a.setEngines(engines);
19 utx.begin();
20 em.persist(a);
21 utx.commit();
Web Component Development With Servlet and JSP Technologies Module 10, slide 27 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Java Persistence API Example
22
23 List <Airplane> l = em.createQuery(
24 "select a from Airplane a").getResultList();
25 request.setAttribute("airplaneList", l);
26 RequestDispatcher rd = request.getRequestDispatcher(
27 "ListView.jsp");
28 rd.forward(request, response);
29 } catch (Exception ex) {
30 request.setAttribute("exception", ex);
31 RequestDispatcher rd = request.getRequestDispatcher(
32 "ExceptionView.jsp");
33 rd.forward(request, response);
34 }
35 }
36 }
Web Component Development With Servlet and JSP Technologies Module 10, slide 28 of 28
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Summary
The nature of the model as a macro-pattern
Techniques for implementing persistent storage for your web
applications
Web Component Development With Servlet and JSP Technologies
Module 11
Asynchronous Servlets and Clients
Module 11
Asynchronous Servlets
and Clients
Web Component Development With Servlet and JSP Technologies Module 11, slide 2 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Objectives
Use the Asynchronous Servlet mechanism
Use JavaScript to send an HTTP request from a client
Process an HTTP response entirely in JavaScript
Combine these techniques to create the effect of server-push
Web Component Development With Servlet and JSP Technologies Module 11, slide 3 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Relevance
What happens if the response to an HTTP request cannot be
made until a message is rteceived from a third party? Must
the servlet thread be blocked indefinitely?
Suppose dozens of clients are cooperating, for example, in a
chat room. Must a request from every client be blocked
waiting until one client triggers an update?
Web Component Development With Servlet and JSP Technologies Module 11, slide 4 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Asynchronous Servlets
Added with Java EE 6
Avoids blocking servlet threads waiting for external
conditions triggering completion
Allows HTTP response to be generated by an arbitrary thread
Distinct from, but might be used with, AJAX techniques
Web Component Development With Servlet and JSP Technologies Module 11, slide 5 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Asynchronous Servlet Example
Servlet code:
1 // imports omitted...
2
3 @WebServlet(name="Update", urlPatterns={"/update"},
asyncSupported = true)
4 public class Update extends HttpServlet {
5 private static Handler handler = Handler.getHandler();
6 @Override
7 public void destroy() {
8 handler.stop();
9 handler = null;
10 }
11
12 protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
13 throws ServletException, IOException {
14 // Can't process this now, pass it off to the handler
15 AsyncContext ac = request.startAsync();
16 handler.addJob(ac);
17 }
18 //...
Web Component Development With Servlet and JSP Technologies Module 11, slide 6 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handler Class Implementation
1 package service;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5 import java.util.List;
6 import javax.servlet.AsyncContext;
7 import javax.servlet.ServletRequest;
8
9 public class Handler implements Runnable {
10
11 private static final Handler self;
12 private static final String[] words = {
13 "long", "short", "big", "small", "clever", "foolish",
"tidy", "disorganized"
14 };
15 private Thread myThread;
16 private boolean stop = false;
17 private List<AsyncContext> queue =
new ArrayList<AsyncContext>(100);
18 private List<AsyncContext> inProgress =
new ArrayList<AsyncContext>(100);
19
Web Component Development With Servlet and JSP Technologies Module 11, slide 7 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handler Class Implementation
20 static {
21 self = new Handler();
22 }
23
24 private Handler() {
25 }
26
27 public static Handler getHandler() {
28 return self;
29 }
30
31 public void stop() {
32 stop = true;
33 }
34
Web Component Development With Servlet and JSP Technologies Module 11, slide 8 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handler Class Implementation
35 public synchronized void addJob(AsyncContext job) {
36 queue.add(job);
37 System.out.println(
"Added a job, queue length is " + queue.size());
38 if (myThread == null) {
39 System.out.println("Started handler thread");
40 myThread = new Thread(this);
41 myThread.start();
42 }
43 }
44
Web Component Development With Servlet and JSP Technologies Module 11, slide 9 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handler Class Implementation
45 public void run() {
46 while (!stop) {
47 System.out.println("Handler loop running");
48 try {
49 Thread.sleep(5000 + ((int) (Math.random() * 5000)));
50 } catch (InterruptedException ex) {
51 ex.printStackTrace();
52 }
53 // check the "queue"
54 synchronized (this) {
55 List<AsyncContext> l = inProgress;
56 l.clear();
57 inProgress = queue;
58 queue = l;
59 }
Web Component Development With Servlet and JSP Technologies Module 11, slide 10 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Handler Class Implementation
60 if (!inProgress.isEmpty()) {
61 System.out.println("Queue contains " + inProgress.size()
+ " elements");
62 // Create the new information
63 String value = "The word is: " + words[(int)
(Math.random() * words.length)] + " and the number is: " +
Math.random() * 1000000;
64 Iterator<AsyncContext> iac = inProgress.iterator();
65 while (iac.hasNext()) {
66 // generate responses
67 AsyncContext ac = iac.next();
68 ServletRequest req = ac.getRequest();
69 req.setAttribute("value", value);
70 System.out.println("Handler dispatching to a jsp");
71 ac.dispatch("asyncResponse.jsp");
72 }
73 }
74
75 }
76 System.out.println("Stopping handler thread");
77 }
78 }
Web Component Development With Servlet and JSP Technologies Module 11, slide 11 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Forwarding and Filtering
Asynchronous handlers may dispatch or forward
Target need not be asynchronous
Allows fast-responding pages to be used in any case
AsyncContext.dispatch invokes filters with a
dispatcher type of ASYNC
Web Component Development With Servlet and JSP Technologies Module 11, slide 12 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Asynchronous Listeners
AsyncContext.addListener(AsyncListener)
AsyncListener interface defines:
onComplete(AsyncEvent)
onError(AsyncEvent)
onTimeout(AsyncEvent)
onStartAsync(AsyncEvent)
Delivery order is the same as listener registration order
Web Component Development With Servlet and JSP Technologies Module 11, slide 13 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Asynchronous JavaScript Clients
JavaScript can modify a page in-situ
JavaScript can make a network request and use the response
data in the update
These ideas are the basis of AJAX
Strictly AJAX sends and receives XML messages
Web Component Development With Servlet and JSP Technologies Module 11, slide 14 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Simple Asynchronous Client Example
1 <html>
2 <head>
3 <title>Async JavaScript Page</title>
4 </head>
5 <body>
6 <h1>Hello World!</h1>
7 <form>
8 <input id="inputField" type="text" onkeyup="doUpdate()">
9 </form>
10 <div id="wisdom">
11 </div>
12 <script type=text/javascript>
13 wisdomTag = document.getElementById("wisdom");
14 inputTag = document.getElementById("inputField");
15
16 function doUpdate() {
17 var req;
18 if (window.XMLHttpRequest) {
19 req = new XMLHttpRequest();
20 } else if (window.ActiveXObject) {
21 req = new ActiveXObject("Microsoft.XMLHTTP");
22 } else {
23 alert("AJAX not supported");
Web Component Development With Servlet and JSP Technologies Module 11, slide 15 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Simple Asynchronous Client Example
24 }
25
26 req.onreadystatechange = function() {
27 if (req.readyState == 4 && req.status == 200) {
28 wisdomTag.innerHTML = req.responseText;
29 }
30 }
31
32 text = inputTag.value;
33 req.open("GET", "update.jsp?text=" + text, true);
34 req.send(null);
35 }
36 </script>
37 </body>
38 </html>
Supporting servlet
1 <p>You asked ${param["text"]}</p>
2 <p>It's <%= new java.util.Date() %> </p>
Web Component Development With Servlet and JSP Technologies Module 11, slide 16 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Server Response Content in an AJAX System
Example used trivial HTML data
XML
JSON
Web Component Development With Servlet and JSP Technologies Module 11, slide 17 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Combining Asynchronous Servlets With
Asynchronous JavaScript
Together, these can create a server-push effect
JavaScript issues a request
Processing is long running, awaiting data
User page is live while waiting, user is not inconvenienced
Response is sent later, JavaScript updates page contents
Web Component Development With Servlet and JSP Technologies Module 11, slide 18 of 18
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Summary
The Asynchronous Servlet mechanism
Using JavaScript to send an HTTP request from a client
Processing an HTTP response entirely in JavaScript
Combining these techniques to create the effect of server-
push
Web Component Development With Servlet and JSP Technologies
Module 12
Implementing Security
Module 12
Implementing Security
Web Component Development With Servlet and JSP Technologies Module 12, slide 2 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Objectives
Describe a common failure mode in security
Require that a user log in before accessing specific pages in
your web application
Describe the Java EE security model
Require SSL encrypted communication for certain URLs or
servlets
Web Component Development With Servlet and JSP Technologies Module 12, slide 3 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Relevance
If your application uses data that are private to your company
or your users, how can you be sure that malicious users
cannot inappropriately access or modify those data?
Web Component Development With Servlet and JSP Technologies Module 12, slide 4 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Security Considerations
Confusion of code and data
Encryption of data in transit over the network
Authentication and authorization of users
Web Component Development With Servlet and JSP Technologies Module 12, slide 5 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Confusion of Code and Data
Data do not perform operations, code does
Systems often freely accept user data
Some data might be interpreted as code later
SQL injection is an example
Template code (XXXXXX is a placeholder):
SELECT count from ITEMTABLE where
itemcode=XXXXXX;
User submits data:
unk; DROP TABLE ITEMTABLE;
Resulting execution:
SELECT count from ITEMTABLE where
itemcode=unk; DROP TABLE ITEMTABLE;;
Shellcoding and cross-site scripting are other examples
Web Component Development With Servlet and JSP Technologies Module 12, slide 6 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Preventing Code as Data Attacks
In SQL, use prepared statements, do not concatenate
Strings
Filter all input
Allow only expected characters
Be careful if you echo user data in error reports
Web Component Development With Servlet and JSP Technologies Module 12, slide 7 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Authentication and Authorization
Reject
Request
Fail
Client calls
enterprise bean method
Transport
data protection
required
Client
Platform
Encrypt
Yes
No
Internet / Intranet
Decrypt
Authenticate
User
Pass
Authorized
User
Check
Reject
Request
Fail
Service
Request
Pass
Java EE
Application
Server
Web Component Development With Servlet and JSP Technologies Module 12, slide 8 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Java EE Security Characteristics
Portable, no direct reference to environment
Declarative, may be augmented with programmatic
Based on Java Authentication and Authorization Service
(JAAS) for interoperability
End-to-end security model makes credentials available
where needed
Web Component Development With Servlet and JSP Technologies Module 12, slide 9 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Authenticating the Caller
BASIC
No logout
No control of login window
Requires HTTPS to protect password
DIGEST
No logout
No control of login window
Protects password on-the-wire, but not in server
Web Component Development With Servlet and JSP Technologies Module 12, slide 10 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Authenticating the Caller
FORM
Supports logout
Full control of login window
Requires HTTPS to protect password
CLIENT CERTIFICATE
Requires client to have a public key certificate
Can be very secure
Usually only used for business-to-business
Web Component Development With Servlet and JSP Technologies Module 12, slide 11 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Authenticating the Caller
Web Component Development With Servlet and JSP Technologies Module 12, slide 12 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Establishing User Identities
Principals
JAAS authenticates users and packages the credentials as a
Principal
Native Domain
Authenticated
Users
Java EE Security Domain
Principals
DR1242 WD3352
JDR1242
JJY3986
JWD3352
JIY8976
JY3986
HT9384 IY8976
JHT9384
Web Component Development With Servlet and JSP Technologies Module 12, slide 13 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Establishing User Identities
Roles
Permissions are granted to roles
Auction
Admin
Member
Roles
Native Domain
Authenticated
Users
Java EE Security Domain
Principals
DR1242 WD3352
JDR1242
JJY3986
JWD3352
JIY8976
JY3986
HT9384 IY8976
JHT9384
Public
Web Component Development With Servlet and JSP Technologies Module 12, slide 14 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Examining the Java EE Authorization
Strategies
Strategy:
- Declarative
People involved:
- Bean developer
- Application assembler
- Deployer
Item Used:
- Annotation/
Deployment descriptor
Strategy:
- Programmatic
Person involved:
- Bean developer
Item Used:
- Bean code
Java EE Security Domain
Principals
Roles
Beans
Native Security Domain
User
Web Component Development With Servlet and JSP Technologies Module 12, slide 15 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Examining the Java EE Authorization
Strategies
Bean
Hard-Coded
Security
TM
Developer
Assembler
Deployer
Programmatic Security
Bean
TM
Developer
Assembler
Deployer
Declarative Security
Annotation
Deployment
Descriptor
Deployment
Tool
Web Component Development With Servlet and JSP Technologies Module 12, slide 16 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Using Declarative Authorization
Collect user credentials into a database
Platform dependent
Declare roles
<security-role> and <role-name> elements in
deployment descriptor (web.xml)
<security-role>
<description>
Needs to create/delete auctions
</description>
<role-name>auction-admin</role-name>
</security-role>
Web Component Development With Servlet and JSP Technologies Module 12, slide 17 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Using Declarative Authorization
Map users to roles
Platform dependent, for example, sun-web.xml
Specify role requirements for access to URLs
In a deployment descriptor (web.xml)
1 <security-constraint>
2 <display-name>Constraint1</display-name>
3 <web-resource-collection>
4 <web-resource-name>Private</web-resource-name>
5 <description/>
6 <url-pattern>/PrivateServlet</url-pattern>
7 </web-resource-collection>
8 <auth-constraint>
9 <description/>
10 <role-name>Trusted</role-name>
11 </auth-constraint>
12 </security-constraint>
In an annotation
@ServletSecurity(@HttpConstraint(rolesAllowed = "Trusted"))
Web Component Development With Servlet and JSP Technologies Module 12, slide 18 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Using Programmatic Authorization
More expressive than declarative
Harder to maintain
More error prone
HttpServletRequest provides:
boolean isUserInRole(String role)
Principal getUserPrincipal()
Web Component Development With Servlet and JSP Technologies Module 12, slide 19 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Mapping Role References
Roles declared at deployment time do not exist at coding
time, so programmer uses a role reference
Role references are mapped to roles in the deployment
descriptor
<web-app>
<servlet>
<servlet-name>AuctionManager</servlet-name>
<servlet-class>web.AuctionManagerServlet</servlet-class>
<security-role-ref>
<description>
Needs to be able to create and delete auctions
</description>
<role-name>auction-admin</role-name>
<role-link>Administrator</role-link>
</security-role-ref>
</servlet>
<role-link> name is used in code
Web Component Development With Servlet and JSP Technologies Module 12, slide 20 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Enforcing Encrypted Transport
In the deployment descriptor
13 <security-constraint>
14 <display-name>Constraint1</display-name>
15 <web-resource-collection>
16 <web-resource-name>Private</web-resource-name>
17 <description/>
18 <url-pattern>/PrivateServlet</url-pattern>
19 </web-resource-collection>
20 <auth-constraint>
21 <description/>
22 <role-name>Trusted</role-name>
23 </auth-constraint>
24 <user-data-constraint>
25 <description/>
26 <transport-guarantee>CONFIDENTIAL</transport-guarantee>
27 </user-data-constraint>
28 </security-constraint>
In an annotation
@ServletSecurity(@HttpConstraint(transportGuarantee
= TransportGuarantee.CONFIDENTIAL))
Web Component Development With Servlet and JSP Technologies Module 12, slide 21 of 21
Copyright 2010 Sun Microsystems, Inc. All Rights Reserved. Sun Services, Revision D
Summary
A common failure mode in security
How to require a user log in before accessing specific pages
in your web application
The nature of the Java EE security model
Enforcing SSL encrypted communication