J0 1 Marco Ronchetti - Servlets e JSP.

Slides:



Advertisements
Similar presentations
Servlets & JSPs - Sharad Ballepu.
Advertisements

Internet i jego zastosowania 1 J2EE Servlets. Internet i jego zastosowania 2 Agenda Overview Servlet Interface Servlet Context Request Response Sample.
Servlets. Servlets are modules that extend Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry.
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
J0 1 Marco Ronchetti - Basi di Dati Web e Distribuite – Laurea Specialitica in Informatica – Università di Trento.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
7 Copyright © 2005, Oracle. All rights reserved. Maintaining State in J2EE Applications.
4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
8 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: JavaServer Pages.
JSP and Servelets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
20 Maart 2006ISS - Internet Applications Part 21 Internet Applications part 2 René de Vries Based on slides by M.L. Liu and Marko van Eekelen.
1 Web Search Interfaces. 2 Web Search Interface Web search engines of course need a web-based interface. Search page must accept a query string and submit.
Servlets, JSP and JavaBeans Joshua Scotton.  Getting Started  Servlets  JSP  JavaBeans  MVC  Conclusion.
Cookie in a servlet. Cookies are small bits of textual information that a Web server sends to a browser and that the browser returns unchanged when visiting.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
Apache Tomcat as a container for Servlets and JSP
Java Server Pages (JSP)
Java Servlets Java Server Pages (JSP)
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
 2003 Prentice Hall, Inc. All rights reserved. Chapter 24: Servlets Outline 24.1 Introduction 24.2 Servlet Overview and Architecture Interface.
Multivalued parameters Some type of parameters may have more than one value. This is the case for the checkbox. What IDEs do you use? NetBeans Eclipse.
1 Fac.Scienze – Università di Trento Programmazione 2 - Marco Ronchetti Events Gestione degli eventi.
J.Sant Servlets Joseph Sant Sheridan Institute of Technology.
Objectives Ch. D - 1 At the end of this chapter students will: Know the general architecture and purpose of servlets Understand how to create a basic servlet.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
1 CS6320 – Servlet Structure and Lifecycle L. Grewe.
Servlets Replace Common Gateway Interface Scripts Extend Server Functionality Modules (software components) Like applets to browsers No GUI.
Comp2513 Java Servlet Basics Daniel L. Silver, Ph.D.
Chapter 4 Servlets Concept of Servlets (What, Why, and How) Servlet API Third-party tools to run servlets Examples of Using Servlets HTML tag with GET.
Definition Servlet: Servlet is a java class which extends the functionality of web server by dynamically generating web pages. Web server: It is a server.
Servlets Compiled by Dr. Billy B. L. Lim. Servlets Servlets are Java programs which are invoked to service client requests on a Web server. Servlets extend.
Servlets Life Cycle. The Servlet Life Cycle A servlet life cycle can be defined as the entire process from its creation till the destruction. The following.
Servlets. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
A Servlet’s Job Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results Send the explicit.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Java Servlets. What Are Servlets? Basically, a java program that runs on the server Basically, a java program that runs on the server Creates dynamic.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
Java Servelets. What Is a Servlet? A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed.
Servlets. - Java technology for Common Gateway Interface (CGI) programming. - It is a Java class that dynamically extends the function of a web server.
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
J2EE training: 1 Course Material Usage Rules PowerPoint slides for use only in full-semester, for-credit courses at degree-granting.
SKT-SSU IT Training Center Servlet and JSP. Chapter Three: Servlet Basics.
Copyright, 1996 © Dale Carnegie & Associates, Inc. Presented by Hsiuling Hsieh Christine Liu.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
Servlet Lifecycle Lec 28. Servlet Life Cycle  Initialize  Service  Destroy Time.
Chapter 3 Servlet Basics. 1.Recall the Servlet Role 2.Basic Servlet Structure 3.A simple servlet that generates plain text 4.A servlet that generates.
CSC 205 – Java Programming II Applet. Types of Java Programs Applets Applications Console applications Graphics applications Applications are stand-alone.
Threading Servlets Can handle multiple clients concurrently Shared resources must be synchronized or create a servlet that handles one request at a time.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
L.MARIA MICHAEL VISUWASAM UNIT-4
1 Java Servlets l Servlets : programs that run within the context of a server, analogous to applets that run within the context of a browser. l Used to.
Middleware 3/29/2001 Kang, Seungwoo Lee, Jinwon. Description of Topics 1. CGI, Servlets, JSPs 2. Sessions/Cookies 3. Database Connection(JDBC, Connection.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, written in Java code, that.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
HTTP protocol Java Servlets. HTTP protocol Web system communicates with end-user via HTTP protocol HTTP protocol methods: GET, POST, HEAD, PUT, OPTIONS,
SERVLET THETOPPERSWAY.COM
Chapter 4 Request and Response. Servlets are controlled by the container.
S ERVLETS Form Data 19-Mar-16. F ORM P ROCESSING You must have come across many situations when you need to pass some information from your browser to.
HTTP Servlet Overview Servlets are modules that extend request/response-oriented servers, such as Java-enabled web servers. For example, a servlet might.
Chapter 26 Servlets.
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
CS122B: Projects in Databases and Web Applications Winter 2019
Basic servlet structure
Presentation transcript:

J0 1 Marco Ronchetti - Servlets e JSP

J0 2 Marco Ronchetti - 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 ).

J0 3 Marco Ronchetti - 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.

J0 4 Marco Ronchetti - 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()

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

J0 6 Marco Ronchetti - 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);

J0 7 Marco Ronchetti - 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; }

J0 8 Marco Ronchetti - 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; }

J0 9 Marco Ronchetti - 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 10 Marco Ronchetti - 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.

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

J0 12 Marco Ronchetti - 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

J0 13 Marco Ronchetti - service() This code is part of the class HttpService protected void service (HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getMethod (); if (method.equals ("GET")) { long ifModifiedSince = req.getDateHeader ("If-Modified-Since"); long lastModified = getLastModified (req); maybeSetLastModified (resp, lastModified); if (ifModifiedSince == -1 || lastModified == -1) doGet (req, resp); else { long now = System.currentTimeMillis (); if (now < ifModifiedSince || ifModifiedSince < lastModified) doGet (req, resp); else resp.sendError (HttpServletResponse.SC_NOT_MODIFIED); }

J0 14 Marco Ronchetti - 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"); }

J0 15 Marco Ronchetti - 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";

J0 16 Marco Ronchetti - 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(); }

J0 17 Marco Ronchetti - 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(ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " \n" + " Parameter Name Parameter Value(s)");

J0 18 Marco Ronchetti - 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 "); }

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

J0 20 Marco Ronchetti - 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:

J0 21 Marco Ronchetti - Esempio: ShowParameters Credit Card: Visa <INPUT TYPE="RADIO" NAME="cardType" VALUE="Master Card">Master Card <INPUT TYPE="RADIO" NAME="cardType" VALUE="Amex">American Express Discover <INPUT TYPE="RADIO" NAME="cardType" VALUE="Java SmartCard">Java SmartCard Credit Card Number: Repeat Credit Card Number:

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

J0 23 Marco Ronchetti - 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 24 Marco Ronchetti - 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

J0 25 Marco Ronchetti - Cookies: i metodi public void setDomain(String c) public String getDomain() public void setPath(int c) public int getPath()

J0 26 Marco Ronchetti - Cookies: esempio Cookie userCookie = new Cookie(user,uid1234); userCookie.setMaxAge(60*60*24*365); response.addCookie(userCookie);

J0 27 Marco Ronchetti - 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);

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

J0 29 Marco Ronchetti - 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) + " \n" + " " + title + " \n" + " \n" + " Cookie Name\n" + " Cookie Value"); ShowCookies

J0 30 Marco Ronchetti - Cookie[] cookies = request.getCookies(); Cookie cookie; for(int i=0; i<cookies.length; i++) { cookie = cookies[i]; out.println(" \n" + " " + cookie.getName() + "\n" + " " + cookie.getValue()); } out.println(" "); } ShowCookies

J0 31 Marco Ronchetti - 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

J0 32 Marco Ronchetti - 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

J0 33 Marco Ronchetti - 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

J0 34 Marco Ronchetti - public long getCreationTime(); public long getLastAccessdTime(); Secondi dal , mezzanotte public void removeAttribute(String name); public int getMaxInactiveInterval(); public void setMaxInactiveInterval(int sec); public void invalidate(); Session tracking API

J0 35 Marco Ronchetti - 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

J0 36 Marco Ronchetti - 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

J0 37 Marco Ronchetti - out.println(ServletUtilities.headWithTitle(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

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

J0 39 Marco Ronchetti - Simple.jsp

J0 40 Marco Ronchetti - JSP Lifecycle Browser Servlet generato Servlet compilato Pagina JSP Server Web

J0 41 Marco Ronchetti - Esempi: Direttive

J0 42 Marco Ronchetti - Esempi: Dichiarazioni

J0 43 Marco Ronchetti - Esempi: Sono le Espressioni

J0 44 Marco Ronchetti - Buongiorno Esempio

J0 45 Marco Ronchetti - Esempi: Azioni

J0 46 Marco Ronchetti - Esempi: <% // Get the Employee's Name from the request out.println(" Employee: " + request.getParameter("employee")); // Get the Employee's Title from the request out.println(" Title: " + request.getParameter("title")); %> Scriptlet

J0 47 Marco Ronchetti - outWriter requestHttpServletRequest responseHttpServletResponse sessionHttpSession pagethis nel Servlet applicationservlet.getServletContext area condivisa tra i servlet configServletConfig exceptionsolo nella errorPage pageContext sorgente degli oggetti, raramente usato Oggetti predefiniti

J0 48 Marco Ronchetti - UseRequest <% // Get the User's Name from the request out.println(" Hello: " + request.getParameter("user") + " "); %> request

J0 49 Marco Ronchetti - UseSession <% // 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); } session

J0 50 Marco Ronchetti - else { count = new Integer(count.intValue() + 1); session.setAttribute("COUNT", count); } // Get the User's Name from the request out.println(" Hello you have visited this site: " + count + " times. "); %> session

J0 51 Marco Ronchetti - include file=URL taglib uri=URL prefix=prefisso definisce un meccanismo di estensione delle tag esistenti! Direttive

J0 52 Marco Ronchetti - jsp:useBean jsp:setProperty jsp:getProperty jsp:forward jsp:plugin Azioni