Presentation is loading. Please wait.

Presentation is loading. Please wait.

Servlets. Applets Special Java programs (without a main) callable from HTML and executed in a graphic context. They can be executed by: a Java enabled.

Similar presentations


Presentation on theme: "Servlets. Applets Special Java programs (without a main) callable from HTML and executed in a graphic context. They can be executed by: a Java enabled."— Presentation transcript:

1 Servlets

2 Applets 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 ).

3 Applets Every applet is implemented by creating a subclass of the Applet class. The hierarchy determines much of what an applet can do and how.

4 Applet Lifecycle 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()

5 Applet Lifecycle Whenever its needed, at lower priority init() stop() destroy() start() handleEvent() Multithreading! Actually, more threads are active behind the scenes. paint()

6 handleEvent() This code is part of the AWT (1.0 Event Model) 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);

7 handleEvent() 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: return action(evt, evt.arg); case Event.GOT_FOCUS: return gotFocus(evt, evt.arg); case Event.LOST_FOCUS: return lostFocus(evt, evt.arg); } return false; }

8 Applets-Event handling 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; }

9 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 http://java.sun.com/docs/books/tutorial/servlets/overview/index.html http://java.sun.com/docs/books/tutorial/servlets/overview/index.html

10 Other uses of servlets Allowing collaboration between people. 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.

11 Applets vs. Servlets AppletServlet Gira:ClientServer Ha un main:NO Estende:java.applet.Appletjavax.servlet.http. HttpServlet GraficaSINO Cuore:handleEvent()service()

12 Servlet Lifecycle init() destroy() service(HttpServletRequest r, HttpServletResponse p) Chiamato solo la prima volta che la Servlet viene caricato in memoria! doGet() doPost() doXXX() Solo quando serve scaricare dalla memoria! Se la Servlet implements SingleThreadModel non ci saranno esecuzioni simultanee di codice

13 service() This code is part of the class HttpServlet protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod (); if (method.equals ("GET")) { longifModifiedSince; longlastModified; longnow; 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); }

14 service() } else if (method.equals ("HEAD")) { longlastModified; 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"); }

15 A taste of servlet programming-1 public class SimpleServlet extends HttpServlet { /** 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";

16 A taste of servlet programming-2 // set content type and other response header fields first response.setContentType("text/html"); // then write the data of the response out = response.getWriter(); out.println(" "); out.println(title); out.println(" "); out.println(" " + title + " "); out.println(" This is output from SimpleServlet."); out.println(" "); out.close(); }

17 Esempio: ShowParameters 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 (" " +title+ " + " \n" + " " + title + " \n" + " \n" + " Parameter Name Parameter Value(s)");

18 Esempio: ShowParameters Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print(" " + paramName + "\n "); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println(" No Value "); else out.println(paramValue); } else { out.println(" "); for(int i=0; i " +paramValues[i]); } out.println(" "); } out.println(" \n "); }

19 Esempio: ShowParameters public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); }

20 Esempio: ShowParameters A Sample FORM using POST A Sample FORM using POST Item Number: Quantity: Price Each: First Name: Last Name: Middle Initial: Shipping Address:

21 Esempio: ShowParameters Credit Card: Visa Master Card American Express Discover Java SmartCard Credit Card Number: Repeat Credit Card Number:

22 Cookies

23 Cookies: perché? Identificazione di un utente in una sessione di e- commerce. Customizzazione di un sito Pubblicità mirata Eliminazione di username e password

24 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

25 Cookies: i metodi public void setMaxAge(int c) public int getMaxAge() Positive value: secondi di vita 0: delete cookie Negative value: finchè dura la sessione del browser

26 Cookies: i metodi public void setDomain(String c) public String getDomain() public void setPath(int c) public int getPath()

27 Cookies: esempio Cookie userCookie = new Cookie(user,uid1234); userCookie.setMaxAge(60*60*24*365); response.addCookie(userCookie);

28 SetCookies 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);

29 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 ( (" " +title+ " + " \n" +" " + title + " \n" +"There are six cookies associated with this page.\n" + " "); } SetCookies

30 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( (" " +title+ " + " \n" + " " + title + " \n" + " \n" + " Cookie Name\n" + " Cookie Value"); ShowCookies

31 Cookie[] cookies = request.getCookies(); Cookie cookie; for(int i=0; i { "@context": "http://schema.org", "@type": "ImageObject", "contentUrl": "http://images.slideplayer.com/570849/1/slides/slide_30.jpg", "name": "Cookie[] cookies = request.getCookies(); Cookie cookie; for(int i=0; i

32 Sessions

33 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); Session tracking using cookies

34 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); Session tracking API

35 public void removeValue(String name);//2.1 public void removeAttribute(String name); //2.2 public String[] getValueNames()//2.1 public Enumeration getAttributeNames()//2.2 Session tracking API

36 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(); Session tracking API

37 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"); ShowSession

38 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); ShowSession

39 out.println( (" " +title+ " + " \n" + " " + heading + " \n" + " Information on Your Session: \n" + " \n" + " Info Type Value\n" + " \n" +" ID\n" +" " + session.getId() + "\n" + " \n" +" Creation Time\n" + " " + new Date(session.getCreationTime()) + "\n" + " \n" +" Time of Last Access\n" + " " +new Date(session.getLastAccessedTime()) + "\n" + " \n" +" Number of Previous Accesses\n" +" " + accessCount + "\n" + " \n" +" "); } ShowSession

40 /** Handle GET and POST requests identically. */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } ShowSession

41 WebApps (Tomcat configuration)

42 Static pages To let Tomcat serve static pages, we must define a Web Application. That is, in the Tomcat Document Root (by default $CATALINA_HOME/webapps/) we must create a folder named after our Web Application (e.g. myApp). In that myApp folder, we MUST create a WEB-INF folder (that can be empy). In the myApp folder we can then depost the static html files. On our Tomcat server, the URL for the hello.html file becomes: http://machine/port/myApp/hello.html To actually see the webapp, we must then restart Tomcat myApp hello.html WEB-INF webapps

43 JSP pages To let Tomcat serve JSP pages, we follow the same procedure that we described for static pages. In the myApp folder we can depost the JSP files. On our Tomcat server, the URL for the hello.jsp file becomes: http://machine/port/myApp/hello.jsp The WEB-INF directory is still empty. To actually see the webapp, we must then restart Tomcat myApp hello.jsp WEB-INF webapps

44 Servlets To let Tomcat serve servlet, we need add some info. The compiled servlets (.class) must be stored in a classes directory in WEB-INF. Moreover, the web.xml file MUST contain at least: invoker /magic/* The magic word is the servlet activation keyword (you can of course customize this word). To execute the servlet called MyServlet.class, the URL will be: http://machine/port/myApp/magic/MyServlet

45 Servlets The web.xml file CAN contain many additional info. For instance, it can contain a section defining an alias name for the servlet: … pippo Servlet1 … In such case, the servlet called MyServlet.class Can be activated ALSO by the URL: http://machine/port/myApp/magic/pippo myApp web.xml WEB-INF webapps classes MyServlet.class


Download ppt "Servlets. Applets Special Java programs (without a main) callable from HTML and executed in a graphic context. They can be executed by: a Java enabled."

Similar presentations


Ads by Google