J0
1
Marco Ronchetti - [email protected]
Applets, Servlets e JSP
Marco Ronchetti - [email protected]
Applets
J0
2
Special Java programs (without a “main”) callable from
HTML and executed in a graphic context.
They can be executed by:
a Java enabled Web Browser;
ad-hoc programs (e.g. Sun AppletViewer).
Marco Ronchetti - [email protected]
Applets
J0
3
Every applet is implemented by creating a
subclass of the Applet class.
The hierarchy determines much of what an
applet can do and how.
Marco Ronchetti - [email protected]
Applet Lifecycle
J0
4
An applet can react to major events in the following
ways:
It can initialize itself.
init()
It can start running.
start()
It can draw some graphics. paint()
It can respond to user-generated events (Mouse,
keyboard, menus…).
handleEvent()
It can stop running.
stop()
It can perform a final cleanup, in preparation for
being unloaded.
destroy()
Applet Lifecycle
Marco Ronchetti - [email protected]
init()
start()
handleEvent()
stop()
J0
5
Multithreading!
destroy()
Whenever it’s needed,
at lower priority
paint()
Actually, more threads are active
behind the scenes.
handleEvent()
Marco Ronchetti - [email protected]
This code is part of the AWT (1.0 Event Model)
J0
6
public boolean handleEvent(Event evt) {
switch (evt.id) {
case Event.MOUSE_ENTER: return mouseEnter(evt, evt.x, evt.y);
case Event.MOUSE_EXIT:
return mouseExit(evt, evt.x, evt.y);
case Event.MOUSE_MOVE: return mouseMove(evt, evt.x, evt.y);
case Event.MOUSE_DOWN: return mouseDown(evt, evt.x, evt.y);
case Event.MOUSE_DRAG: return mouseDrag(evt, evt.x, evt.y);
case Event.MOUSE_UP:
return mouseUp(evt, evt.x, evt.y);
handleEvent()
Marco Ronchetti - [email protected]
case Event.KEY_PRESS:
case Event.KEY_ACTION:
return keyDown(evt, evt.key);
case Event.KEY_RELEASE:
case Event.KEY_ACTION_RELEASE: return keyUp(evt, evt.key);
case Event.ACTION_EVENT:
case Event.GOT_FOCUS:
case Event.LOST_FOCUS:
}
return false;
}
J0
7
return action(evt, evt.arg);
return gotFocus(evt, evt.arg);
return lostFocus(evt, evt.arg);
Marco Ronchetti - [email protected]
Applets-Event handling
J0
8
To react to an event, an applet must override either
the appropriate event-specific method or the
handleEvent method.
For example, adding the following code to the
Simple applet makes it respond to mouse clicks.
import java.awt.Event;
...
public boolean mouseDown(Event event, int x, int y) {
addItem("click!... ");
return true;
}
Marco Ronchetti - [email protected]
Applets
J0
9
Le applets sono uno scheletro di applicazione che gira nello spazio
concesso loro da un browser.
Il programmatore ha la responsabilita’ di implementare i seguenti
metodi (che possono anche essere lasciati vuoti):
init()
start()
stop()
destroy()
paint()
viene eseguito quando la
viene eseguito quando la
viene eseguito quando la
viene eseguito quando la
viene eseguito quando la
applet viene creata
applet (ri)parte
applet viene fermata
applet viene distrutta
applet viene (ri)disegnata
NOTA: il programmatore puo’ notificare la necessita’ di ridisegnare la
applet tramite la chiamata repaint().
Tuttavia, l’effettivo ridisegno verra’ fatto dal sistema SOLO quando vi
saranno risorse disponibili! (vedi Threads).
Applet methods - 1a
Marco Ronchetti - [email protected]
import java.awt.Graphics;
import java.util.Date;
public class ShowAppletMethods extends java.applet.Applet
Date d;
int count=0;
public void init() {
System.out.println((count++)+" Init Executed");
}
public void start() {
System.out.println((count++)+" Start Executed");
}
<HTML><HEAD>
<TITLE>Another Applet</TITLE>
</HEAD>
<BODY>
<APPLET
CODE="ShowAppletMethods.class"
WIDTH=200 HEIGHT=75>
</APPLET>
</BODY></HTML>
public void stop() {
System.out.println((count++)+" Stop Executed");
}
public void destroy() {
System.out.println((count++)+" Destroy Executed");
}
public void paint(Graphics g) {
System.out.println((count++)+" Paint Executed");
d=new Date();
g.drawString("Time now is "+d.getHours() +":” +d.getMinutes() +":” +d.getSeconds(), 5, 25);
}
}
J0
10
{
Marco Ronchetti - [email protected]
Elementi Grafici
J0
11
import java.awt.*;
import java.awt.event.*;
public class TestPattern extends
java.applet.Applet {
int theta = 45;
public void paint( Graphics g ) {
int Width = size().width;
int Height = size().height;
int width = Width/2;
int height = Height/2;
int x = (Width - width)/2;
int y = (Height- height)/2;
int [] polyx = { 0, Width/2, Width, Width/2 };
int [] polyy = { Height/2, 0, Height/2, Height };
Polygon poly = new Polygon( polyx, polyy, 4 );
g.setColor( Color.black );
g.fillRect( 0, 0, size().width, size().height );
g.setColor( Color.yellow );
g.fillPolygon( poly );
g.setColor( Color.red );
g.fillRect( x, y, width, height );
g.setColor( Color.green );
g.fillOval( x, y, width, height );
g.setColor( Color.blue );
int delta = 90;
g.fillArc( x, y, width, height, theta, delta );
g.setColor( Color.white );
g.drawLine( x, y, x+width, x+height );
}
public void init() {
addMouseListener(
new MouseAdapter() {
public void mousePressed(
MouseEvent e ) {
theta= theta+10)%360;
repaint();
}
} );
}
}
Marco Ronchetti - [email protected]
Metodi grafici di Graphics
J0
12
draw3DRect()
Draws a highlighted, 3D rectangle
drawArc()
Draws an arc
drawLine()
Draws a line
drawOval()
Draws an oval
drawPolygon()
Draws a polygon, connecting endpoints
drawPolyline()
Draws a line connecting a polygon's points
drawRect()
Draws a rectangle
drawRoundRect()
Draws a rounded-corner rectangle
fill3DRect()
Draws a filled, highlighted, 3D rectangle
fillArc()
Draws a filled arc
fillOval()
Draws a filled oval
fillPolygon()
Draws a filled polygon
fillRect()
Draws a filled rectangle
fillRoundRect()
Draws a filled, rounded-corner rectangle
Text & Fonts
Marco Ronchetti - [email protected]
import java.awt.Font;
import java.awt.FontMetrics;
public class ManyFonts extends java.applet.Applet {
public void paint(Graphics g) {
Font f = new Font("TimesRoman", Font.PLAIN, 18);
FontMetrics fm = getFontMetrics(f);
g.setFont(f);
String s = "This is a plain font";
int xstart = (size().width - fm.stringWidth(s)) / 2;
//int ystart = (size().height + fm.getHeight()) / 2;
g.drawString(s, xstart, 25);
Font fb = new Font("TimesRoman", Font.BOLD, 18);
Font fi = new Font("TimesRoman", Font.ITALIC, 18);
Font fbi = new Font("TimesRoman", Font.BOLD + Font.ITALIC, 18);
g.setFont(fb);
g.drawString("This is a bold font", 10, 50);
g.setFont(fi);
g.drawString("This is an italic font", 10, 75);
g.setFont(fbi);
g.drawString("This is a bold italic font", 10, 100);
}
}
J0
13
import java.awt.Graphics;
Colore
import java.awt.Graphics;
Marco Ronchetti - [email protected]
import java.awt.Color;
public class ColorBoxes extends java.applet.Applet {
public void paint(Graphics g) {
int rval, gval, bval;
for (int j = 30; j < (this.size().height -25); j += 30)
for (int i = 5; i < (this.size().width -25); i+= 30) {
rval = (int)Math.floor(Math.random() * 256);
gval = (int)Math.floor(Math.random() * 256);
bval = (int)Math.floor(Math.random() * 256);
g.setColor(new Color(rval,gval,bval));
g.fillRect(i,j,25,25);
g.setColor(Color.black);
g.drawRect(i-1,j-1,25,25);
}
}
}
J0
14
Applet methods - 2
Marco Ronchetti - [email protected]
import java.awt.Graphics;
import java.util.Date;
J0
15
public class ShowAppletMethods extends java.applet.Applet
Date d;
int count=0;
int seconds;
{
<HTML><HEAD>
<TITLE>Another Applet</TITLE>
</HEAD><BODY>
<APPLET CODE="ShowAppletMethods.class"
WIDTH=200 HEIGHT=75>
<PARAM name=secondi value=10>
</APPLET>
</BODY></HTML>
public void init() {
System.out.println((count++)+" Init Executed");
seconds=Integer.parseInt(this.getParameter("Secondi"));
}
public void start() {
System.out.println((count++)+" Start Executed");
while (true) {
try {
public void destroy() {
Thread.sleep(seconds*1000);
System.out.println((count++)+" Destroy Executed");
}
}
catch (InterruptedException e) {}
public void paint(Graphics g) {
System.out.println("==> calling repaint");
System.out.println((count++)+" Paint Executed");
repaint();
d=new Date();
}
g.drawString("Time now is ” +d.getHours() +":”
}
+d.getMinutes() +":” +d.getSeconds(), 5, 25);
}
public void stop() {
}
System.out.println((count++)+" Stop Executed");
}
Marco Ronchetti - [email protected]
Multithreading per la paint()
J0
16
La versione precedente del codice non disegna MAI lo schermo!
Il problema e’ che il programma ha una singola thread,
che e’ sempre occupata: nessuno quindi puo’ eseguire la paint().
La soluzione e’ di creare una nuova thread che faccia il lavoro
vero e proprio, lasciando alla applet meno compiti.
import java.awt.Graphics;
import java.util.Date;
Applet methods - 3
Marco Ronchetti - [email protected]
public class ShowAppletMethods extends java.applet.Applet
Date d;
int count=0;
simpleThread t;
{
class simpleThread extends Thread {
ShowAppletMethods a;
int seconds;
simpleThread(ShowAppletMethods a, int s) {
this.a=a;
seconds=s*1000;
}
public void init() {
System.out.println((count++)+" Init Executed");
int seconds=Integer.parseInt(this.getParameter(
"Secondi"));
t=new simpleThread(this,seconds);
t.start();
}
public void run() {
public void start() {
while (true) {
System.out.println((count++)+" Start Executed");
try {
}
sleep(seconds);
public void stop() {
}
System.out.println((count++)+" Stop Executed");
catch (InterruptedException e) {}
}
System.out.println("==> THREAD: calling
public void destroy() {
repaint");
t.stop();
a.repaint();
System.out.println((count++)+" Destroy Executed");
}
}
}
public void paint(Graphics g) {
}
System.out.println((count++)+" Paint Executed");
d=new Date();
g.drawString("Time now is "+d.getHours() +":” +d.getMinutes() +":” +d.getSeconds(), 5, 25);
J0 }
17}
Marco Ronchetti - [email protected]
Double buffering
J0
18
Le animazioni vengono effettuate cancellando l’immagine
presente e ridisegnando la nuova. Questo da’ origine ad un
fastidioso sfarfallio.
Per evitare questo effetto, la nuova immagine viene disegnata
in memoria anziche’ a video: quando l’immagine e’ pronta,
quella presente a video viene sostituita con la nuova (tecnica
di double buffering).
La tecnica si basa sulla ridefinizione del metodo “update()” che viene chiamato dalla
repaint(), e che a sua volta schedula la paint(). La versione standard di update e’ :
public void update(Graphics g) {
g.setColor(getBackground());
g.fillRect(0,0,width,height);
g.setColor(getForeground());
paint(g);
}
Animazione con flickering
Marco Ronchetti - [email protected]
/* simple applet to show very basic startup and
animation stuff */
public void run() {
while (true) {
for (xpos = 5; xpos <= 105; xpos+=4) {
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
}
xpos=5;
}
}
import java.awt.Graphics;
import java.awt.Color;
public class Checkers extends java.applet.Applet
implements Runnable {
Thread runner;
int xpos;
public void update(Graphics g) {
paint(g);
}
public void start() {
if (runner == null); {
runner = new Thread(this);
runner.start();
}
}
public void paint(Graphics g) {
// Draw background
g.setColor(Color.black);
g.fillRect(0,0,100,100);
g.setColor(Color.white);
g.fillRect(100,0,100,100);
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
J0
19
// Draw checker
g.setColor(Color.red);
g.fillOval(xpos,5,90,90);
}
}
Animazione senza flickering
import java.awt.Graphics;
import java.awt.Color;
import java.awt.Image;
Marco Ronchetti - [email protected]
public class Checkers2 extends java.applet.Applet
implements Runnable {
J0
20
Thread runner;
int xpos;
Image offscreenImg;
Graphics offscreenG;
g.drawImage(offscreenImg,0,0,this);
public void init() {
offscreenImg = createImage(this.size().width,
this.size().height);
offscreenG = offscreenImg.getGraphics();
}
public void start() {
if (runner == null); {
runner = new Thread(this);
runner.start();
}
}
public void stop() {
if (runner != null) {
runner.stop();
runner = null;
}
}
public void paint(Graphics g) {
// Draw background
offscreenG.setColor(Color.black);
offscreenG.fillRect(0,0,100,100);
offscreenG.setColor(Color.white);
offscreenG.fillRect(100,0,100,100);
// Draw checker
offscreenG.setColor(Color.red);
offscreenG.fillOval(xpos,5,90,90);
}
public void destroy() {
offscreenG.dispose();
}
}
NOTA: I contesti grafici non vengono liberati
dalla garbage collection, vanno rilasciati
esplicitamente! (Vedi destroy)
public void run() {
while (true) {
for (xpos = 5; xpos <= 105; xpos+=4) {
repaint();
try { Thread.sleep(100); }
catch (InterruptedException e) { }
}
xpos = 5;
}
}
public void update(Graphics g) {
paint(g);
}
Marco Ronchetti - [email protected]
Launching Applets as Apps
import java.awt.*;
import java.applet.*;
public class ShowAppletMethodsAsApplication
extends ShowAppletMethods {
public static void main(String args[]) {
Applet applet=new ShowAppletMethodsAsApplication();
Frame frame=new AppletFrame("ShowAppletMethodsAsApplication",applet,300,300);
}
}
class AppletFrame extends Frame implements ActionListener {
public AppletFrame (String title, Applet applet,
int width, int height) {
//create Frame with specified title
// add the applet to the window,
super(title);
// set window size, show it
//add a Menubar
this.add("Center",applet);
MenuBar menubar=new MenuBar();
this.resize(width,height);
Menu file = new Menu("File",true);
this.show();
menubar.add(file);
//Start the applet
MenuItem mExit=new MenuItem("Exit");
applet.init();
file.add(mExit);
applet.start();
mExit.addActionListener(this);
}
this.setMenuBar(menubar);
public void actionPerformed(ActionEvent e)
System.exit(0);
J0
}
21
}
Applets and the status line
Marco Ronchetti - [email protected]
Applets display status lines with the showStatus method.
J0
22
showStatus("MyApplet: hello!");
The status line is not usually very prominent, and it can be overwritten
by other applets or by the browser. For these reasons, it's best used
for incidental, transitory information.
Note: Please don't put scrolling text in the status line. Browser users
find such status line abuse highly annoying!
Marco Ronchetti - [email protected]
Applets and HTML text
With the AppletContext showDocument method, an
applet can tell the browser which URL to show and
in which browser window.
public void showDocument(java.net.URL url,
String targetWindow)
For a full example, see
J0
23
http://java.sun.com/docs/books/tutorial/applet/appletsonly/browser.html
Marco Ronchetti - [email protected]
Interaction among applets
Applets can find other applets and send messages to them,
with the following security restrictions:
Many browsers require that the applets originate from the
same server.
Many browsers require that the applets originate from the
same directory on the server (the same code base).
The Java API requires that the applets be running on the
same page, in the same browser window.
For a full example, see
J0
24
http://java.sun.com/docs/books/tutorial/applet/appletsonly/iac.html
Marco Ronchetti - [email protected]
Servlets (JDK 1.2)
Servlets are modules that extend Java-enabled web servers. For
example, a servlet might be responsible for taking data in an HTML
order-entry form and applying the business logic used to update a
company's order database.
Servlets are to servers what applets are to browsers. Unlike applets,
however, servlets have no graphical user interface.
For a full tutorial, see
J0
25
http://java.sun.com/docs/books/tutorial/servlets/overview/index.html
Other uses of servlets
Marco Ronchetti - [email protected]
Allowing collaboration between people.
J0
26
A servlet can handle multiple requests concurrently, and can
synchronize requests. This allows servlets to support systems such
as on-line conferencing.
Forwarding requests.
Servlets can forward requests to other servers and servlets. Thus
servlets can be used to balance load among several servers that
mirror the same content, and to partition a single logical service
over several servers, according to task type or organizational
boundaries.
Marco Ronchetti - [email protected]
Applets vs. Servlets
J0
27
Applet
Servlet
Gira:
Client
Server
Ha un main:
NO
NO
Estende:
java.applet.Applet
Grafica
SI
javax.servlet.http.
HttpServlet
NO
Cuore:
handleEvent()
service()
Marco Ronchetti - [email protected]
Servlet Lifecycle
J0
28
Chiamato solo la prima volta che la
Servlet viene caricato in memoria!
init()
doXXX()
service(HttpServletRequest r,
HttpServletResponse p)
doGet()
doPost()
Se la Servlet implements SingleThreadModel non
ci saranno esecuzioni simultanee di codice
destroy()
Solo quando serve scaricare dalla
memoria!
service()
Marco Ronchetti - [email protected]
This code is part of the class HttpService
J0
29
protected void service (HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String
method = req.getMethod ();
if (method.equals ("GET")) {
long
ifModifiedSince; long
lastModified; long
now;
ifModifiedSince = req.getDateHeader ("If-Modified-Since");
lastModified = getLastModified (req);
maybeSetLastModified (resp, lastModified);
if (ifModifiedSince == -1 || lastModified == -1)
doGet (req, resp);
else {
now = System.currentTimeMillis ();
if (now < ifModifiedSince || ifModifiedSince < lastModified)
doGet (req, resp);
else
resp.sendError (HttpServletResponse.SC_NOT_MODIFIED);
}
service()
Marco Ronchetti - [email protected]
} else if (method.equals ("HEAD")) {
long
lastModified;
lastModified = getLastModified (req);
maybeSetLastModified (resp, lastModified);
doHead (req, resp);
} else if (method.equals ("POST")) {
doPost (req, resp);
} else if (method.equals ("PUT")) {
doPut(req, resp);
} else if (method.equals ("DELETE")) {
doDelete(req, resp);
} else if (method.equals ("OPTIONS")) {
doOptions(req,resp);
} else if (method.equals ("TRACE")) {
doTrace(req,resp);
} else {
resp.sendError (HttpServletResponse.SC_NOT_IMPLEMENTED,
"Method '" + method + "' is not defined in RFC 2068");
}
J0
30
}
A taste of servlet programming-1
Marco Ronchetti - [email protected]
public class SimpleServlet extends HttpServlet {
J0
31
/** Handle the HTTP GET method by building a simple web page. */
public void doGet (HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
PrintWriter out;
String title = "Simple Servlet Output";
A taste of servlet programming-2
// set content type and other response header fields first
Marco Ronchetti - [email protected]
response.setContentType("text/html");
// then write the data of the response
out = response.getWriter();
out.println("<HTML><HEAD><TITLE>");
out.println(title);
out.println("</TITLE></HEAD><BODY>");
out.println("<H1>" + title + "</H1>");
out.println("<P>This is output from SimpleServlet.");
out.println("</BODY></HTML>");
out.close();
}
J0
32
}
Marco Ronchetti - [email protected]
Esempio: ShowParameters
J0
33
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ShowParameters extends HttpServlet {
public void doGet(HttpServletRequest request HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println(“<HEAD><TITLE>”+title + “</TITLE> </HEAD>”)+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name<TH>Parameter Value(s)");
Marco Ronchetti - [email protected]
Esempio: ShowParameters
J0
34
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0) out.println("<I>No Value</I>");
else out.println(paramValue);
} else {
out.println("<UL>");
for(int i=0; i<paramValues.length; i++) {out.println("<LI>" +paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</TABLE>\n</BODY></HTML>");
}
Marco Ronchetti - [email protected]
Esempio: ShowParameters
J0
35
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Marco Ronchetti - [email protected]
Esempio: ShowParameters
J0
36
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>A Sample FORM using POST </TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">A Sample FORM using POST</H1>
<FORM ACTION="/servlet/coreservlets.ShowParameters“ METHOD="POST”>
Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR>
Quantity: <INPUT TYPE="TEXT" NAME="quantity"><BR>
Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
<HR>
First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR>
Last Name: <INPUT TYPE="TEXT" NAME="lastName"><BR>
Middle Initial: <INPUT TYPE="TEXT" NAME="initial"><BR>
Shipping Address:
<TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
Marco Ronchetti - [email protected]
Esempio: ShowParameters
J0
37
Credit Card:<BR>
  <INPUT TYPE="RADIO" NAME="cardType“
VALUE="Visa">Visa<BR>
  <INPUT TYPE="RADIO" NAME="cardType"
VALUE="Master Card">Master Card<BR>
  <INPUT TYPE="RADIO" NAME="cardType"
VALUE="Amex">American Express<BR>
  <INPUT TYPE="RADIO" NAME="cardType“
VALUE="Discover">Discover<BR>
  <INPUT TYPE="RADIO" NAME="cardType"
VALUE="Java SmartCard">Java SmartCard<BR>
Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
Repeat Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR>
<CENTER><INPUT TYPE="SUBMIT" VALUE="Submit Order"></CENTER>
</FORM>
</BODY>
</HTML>
Marco Ronchetti - [email protected]
Cookies: perché?
J0
38
Identificazione di un utente in una sessione di
e-commerce.
Customizzazione di un sito
Pubblicità mirata
Eliminazione di username e password
Marco Ronchetti - [email protected]
Cookies: i metodi
public void setComment(String c)
public String getComment()
public void setVersion(int c)
public int getVersion ()
Version 0: Netscape standard
Version 1: RFC 2109
J0
39
Marco Ronchetti - [email protected]
Cookies: i metodi
J0
40
public void setMaxAge(int c)
public int getMaxAge()
Positive value: secondi di vita
0: delete cookie
Negative value: finchè dura la sessione del browser
Marco Ronchetti - [email protected]
Cookies: i metodi
J0
41
public void setDomain(String c)
public String getDomain()
public void setPath(int c)
public int getPath()
Marco Ronchetti - [email protected]
Cookies: esempio
J0
42
Cookie userCookie = new Cookie(“user”,”uid1234”);
userCookie.setMaxAge(60*60*24*365);
response.addCookie(userCookie);
Marco Ronchetti - [email protected]
SetCookies
J0
43
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
/** Sets six cookies: three that apply only to the current session
* (regardless of how long that session lasts) and three that persist for an hour
* (regardless of whether the browser is restarted).
*/
public class SetCookies extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
for(int i=0; i<3; i++) {
// Default maxAge is -1, indicating cookie
// applies only to current browsing session.
Cookie cookie = new Cookie("Session-Cookie-" + i,
"Cookie-Value-S" + i);
response.addCookie(cookie);
Marco Ronchetti - [email protected]
SetCookies
J0
44
cookie = new Cookie("Persistent-Cookie-" + i,"Cookie-Value-P" + i);
// Cookie is valid for an hour, regardless of whether
// user quits browser, reboots computer, or whatever.
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Setting Cookies";
out.println (ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +"<H1 ALIGN=\"CENTER\">"
+ title + "</H1>\n" +"There are six cookies associated with this page.\n" +
"</BODY></HTML>");
}
}
Marco Ronchetti - [email protected]
ShowCookies
J0
45
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
/** Creates a table of the cookies associated with the current page. */
public class ShowCookies extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Active Cookies";
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + title + "</H1>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Cookie Name\n" + " <TH>Cookie Value");
Marco Ronchetti - [email protected]
ShowCookies
J0
46
Cookie[] cookies = request.getCookies();
Cookie cookie;
for(int i=0; i<cookies.length; i++) {
cookie = cookies[i];
out.println("<TR>\n" +
" <TD>" + cookie.getName() + "\n" +
" <TD>" + cookie.getValue());
}
out.println("</TABLE></BODY></HTML>");
}
}
Marco Ronchetti - [email protected]
Session tracking using cookies
J0
47
String sessionID = makeUniqueString();
Hashtable sessionInfo = new Hashtable();
Hashtable globalTable = getTableStoringSession();
globalTable.put(sessionID,sessionInfo);
Cookie sessionCookie=new Cookie(“SessionID”,sessionID);
sessionCookie.setPath(“/”);
response.addCookie(sessionCookie);
Marco Ronchetti - [email protected]
Session tracking API
J0
48
HttpSession session = request.getSession(true);
ShoppingCart cart =
(ShoppingCart)session.getValue(“carrello”); // 2.1
// 2.2 (ShoppingCart)session.getAttribute(“carrello”);
if (cart==null) {
cart=new ShoppingCart();
session.putValue(“carrello”,cart); //2.1
//2.2 session.putValue(“carrello”,cart);
}
doSomeThingWith(cart);
Marco Ronchetti - [email protected]
Session tracking API
J0
49
public void removeValue(String name);
//2.1
public void removeAttribute(String name); //2.2
public String[] getValueNames()
public Enumeration getAttributeNames()
//2.1
//2.2
Marco Ronchetti - [email protected]
Session tracking API
J0
50
public long getCreationTime();
public long getLastAccessdTime();
Secondi dal 1.1.1970, mezzanotte
public void removeAttribute(String name);
public int getMaxInactiveInterval();
public void setMaxInactiveInterval(int sec);
public void invalidate();
Marco Ronchetti - [email protected]
ShowSession
J0
51
import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
import java.net.*; import java.util.*;
/** Simple example of session tracking. */
public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
HttpSession session = request.getSession(true);
String heading;
// Use getAttribute instead of getValue in version 2.2.
Integer accessCount = (Integer)session.getValue("accessCount");
Marco Ronchetti - [email protected]
ShowSession
J0
52
if (accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
// Use setAttribute instead of putValue in version 2.2.
session.putValue("accessCount", accessCount);
Marco Ronchetti - [email protected]
ShowSession
J0
53
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=\"CENTER\">" + heading + "</H1>\n" +
"<H2>Information on Your Session:</H2>\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
" <TH>Info Type<TH>Value\n" +
"<TR>\n" +" <TD>ID\n" +" <TD>" + session.getId() + "\n" +
"<TR>\n" +" <TD>Creation Time\n" +
" <TD>" + new Date(session.getCreationTime()) + "\n" +
"<TR>\n" +" <TD>Time of Last Access\n" +
" <TD>" +new Date(session.getLastAccessedTime()) + "\n" +
"<TR>\n" +" <TD>Number of Previous Accesses\n" +" <TD>" +
accessCount + "\n" + "</TABLE>\n" +"</BODY></HTML>");
}
ShowSession
Marco Ronchetti - [email protected]
/** Handle GET and POST requests identically. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
J0
54
Marco Ronchetti - [email protected]
Simple.jsp
J0
55
<html>
<body>
<% out.println(“Hello World”); %>
</body>
</html>
Marco Ronchetti - [email protected]
JSP Lifecycle
Server Web
Pagina JSP
Browser
Servlet generato
Servlet compilato
J0
56
Direttive
Marco Ronchetti - [email protected]
<%@ DIRETTIVA {attributo=valore} %>
J0
57
Esempi:
<%@ page language=java %>
<%@ page import=java.awt.*,java.util.* session=true
%>
Dichiarazioni
Marco Ronchetti - [email protected]
<%! DICHIARAZIONE %>
J0
58
Esempi:
<%! String nome=pippo %>
<%! public String getName() {return nome} %>
Espressioni
Marco Ronchetti - [email protected]
<%= ESPRESSIONE%>
J0
59
Esempi:
<%= getName() %>
<%@ page import=java.util.* %>
Sono le <%= new Date().toString(); %>
Marco Ronchetti - [email protected]
Esempio
J0
60
<html><body>
<%! String nome=pippo %>
<%! public String getName() {return nome} %>
<H1>
Buongiorno
<%= getName() %>
</H1>
</body></html>
Marco Ronchetti - [email protected]
Azioni
<jsp:AZIONE>
Esempi:
<jsp:forward page=URL>
<jsp:include page=URL flush=true>
<jsp:useBean>
J0
61
Scriptlet
Marco Ronchetti - [email protected]
<% SCRIPTLET %>
J0
62
Esempi:
<% z=z+1; %>
<%
// Get the Employee's Name from the request
out.println("<b>Employee: </b>" +
request.getParameter("employee"));
// Get the Employee's Title from the request
out.println("<br><b>Title: </b>" +
request.getParameter("title"));
%>
Marco Ronchetti - [email protected]
Oggetti predefiniti
J0
63
out
request
response
session
page
application
Writer
HttpServletRequest
HttpServletResponse
HttpSession
this nel Servlet
servlet.getServletContext
area condivisa tra i servlet
config
exception
pageContext
ServletConfig
solo nella errorPage
sorgente degli oggetti, raramente usato
Marco Ronchetti - [email protected]
request
J0
64
<%@ page errorPage="errorpage.jsp" %>
<html>
<head>
<title>UseRequest</title>
</head>
<body>
<%
// Get the User's Name from the request
out.println("<b>Hello: " + request.getParameter("user") +
"</b>");
%>
</body>
</html>
session
Marco Ronchetti - [email protected]
<%@ page errorPage="errorpage.jsp" %>
J0
65
<html> <head> <title>UseSession</title> </head>
<body>
<%
// Try and get the current count from the session
Integer count = (Integer)session.getAttribute("COUNT");
// If COUNT is not found, create it and add it to the session
if ( count == null ) {
count = new Integer(1);
session.setAttribute("COUNT", count);
}
Marco Ronchetti - [email protected]
session
J0
66
else {
count = new Integer(count.intValue() + 1);
session.setAttribute("COUNT", count);
}
// Get the User's Name from the request
out.println("<b>Hello you have visited this site: "
+ count + " times.</b>");
%>
</body>
</html>
Marco Ronchetti - [email protected]
Direttive
J0
67
include file=“URL”
taglib uri=“URL” prefix=“prefisso”
definisce un meccanismo di estensione delle tag
esistenti!
Marco Ronchetti - [email protected]
Azioni
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:forward
jsp:plugin
J0
68