Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 An introduction to Java Servlet Alessandro Marchetto Fondazione Bruno Kessler-IRST,

Similar presentations


Presentation on theme: "1 An introduction to Java Servlet Alessandro Marchetto Fondazione Bruno Kessler-IRST,"— Presentation transcript:

1 1 An introduction to Java Servlet Alessandro Marchetto Fondazione Bruno Kessler-IRST,

2 2 Outline Web applications Java Servlet Servlet engine How to write a servlet How to Process a request (Form data) Servlet session tracking Just a quick introduction After this lecture you will be able to read and write simple Servlets

3 3 Web applications The Web server distributes pages of formatted information to clients that request it. HTML Pages are transmitted using the http protocol The browser renders (static) HTML pages. HTML pages are stored in a file system (database) contained on the web server.

4 4 Dynamic Web applications In some cases the content of a page (HTML) is not necessarily stored inside a file. The content can be assembled at run-time according to user inputs and informations stored in a database. It can come from the output of a program (server script). Servlets and JavaServer Pages are the Java technologys answer to dynamic Web sites. They are programs that run on a Web server and build Web pages. Client Web Server http requesthttp response DB Script/program

5 5 HTML and DOM The HTML Document Object Model (HTML DOM) defines a standard way for accessing and manipulating HTML documents. The DOM presents an HTML document as a tree-structure (a node tree), with elements, attributes, and text. My title My header My link its DOM

6 6 Outline Just a quick introduction After this lecture you will be able to read and write simple servlets Web applications Java Servlet Servlet engine How to write a servlet How to Process a request (i.e., Form data) Servlet session tracking

7 7 Servlet Engine A servlet engine (or servlet container) provides the run-time environment in which a servlet is executed. The servlet engine manages the life-cycle of servlets (i.e., from their creation to their destruction). The servlet engine: loads, executes and destroyes servlets Apache Tomcat is a servlet container Relationships between Web server, Servlet engine and Servlets.

8 8 The Life-Cycle of a Servlet Servlet are Java classes. To execute them it is necessary compiling them in bytecode. The servlet engine perform the following tasks: it loads the servlet when it is requested (only the first time). it calls the init() method of the servlet. it handles the requests calling the service() method of the servlet. at the end, it calls the destroy() method.

9 9 How to write a Java servlet All servlets implement the Servlet interface or extend a class the implements it. We will use HttpServlet and these methods: doGet doPost init destroy getServletInfo To write a servlet some of these methods must be overridden..... HttpServlet implements the Servlet interface …

10 10 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use request to read incoming HTML form data (e.g. submitted data) // Use response to specify the HTTP response status (e.g., content type) PrintWriter out = response.getWriter(); // Use out to send content to browser } Generic Template The generic template to write Servlet

11 11 Helloworld First example of servlet We override doGet() The execution of it produces a HTML response import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloClientServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(text/html); PrintWriter out = response.getWriter(); out.println( Hello Client! + Hello Client! ); out.close(); }

12 12 Context The Context can be used to store global information shared among the servlets of a given application. The Context is initialized when the Servlet container starts and destroyed when it shuts down. For this reason, it is suited for keeping the long lived information It is implemented with: javax.servlet.ServletContext The methods: -getServletContext(): obtain the context -getAttribute(String key): get an attribute from the context -setAttribute(String key, Object value): set an attribute ServletContext Common Data 1 1 Servlets

13 13 First Par Second Par Third Par Submit ~hall ~gates ~mcnealy First Par: Second Par: Third Par: Forms and Servlets (1) How to exchange data between client and server? GET: In a URL the part after the question mark (?) is known as form data, and is a way to send data from a Web page to a server-side program POST: a data packege is created and attached to the HTTP requests sent to the server ? param1= ~hall¶m2= ~gates¶m3= ~mcnealy

14 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters"; out.println( ServletUtilities.headWithTitle(title) + " \n" + " " + title + " \n" + " \n" + " param1: " + request.getParameter("param1") + "\n" + " param2: " + request.getParameter("param2") + "\n" + " param3: " + request.getParameter("param3") + "\n" + " \n" + " "); } Forms and Servlets (2) ~hall ~ gate ~mcnealy HTML CODE

15 15 Forms and Servlets (3)

16 16 HTTP - Stateless protocol (1) The Web server cant remember previous transactions since HTTP is a stateless protocol. E.g., a shopping cart: it contains all items that have been selected from an online store's catalog by a customer; the customer can check the content of the cart at any time during the session; thus, the server must be able to maintain the cart of the user across several Web page requests.

17 17 There are four ways to maintain the state: 1. Cookies javax.servlet.http.Cookie(String nome, String val) methods: setName(String cookieName), setValue(String cookieValue), etc. 2. Hidden fields in forms /> 3. URL rewriting e.g., String encodeURL(String url) of the class HttpServletResponse where: url is the original lURL and the output is the rewritten one 4. Servlets (HttpSession API) HTTP - Stateless protocol (2) How to maintain the state

18 18 Saving the state in general First request The Server marks the client with an unique ID and creates a memory partition that will contain the data (state) Every subsequent connection must send the ID. In this way the server recognize/identify the client xyz5

19 19 Servlet Sessions (3) Assuming ShoppingCart is some class you have defined yourself that stores information on items being purchased HttpSession session = request.getSession(true); ShoppingCart previousItems = (ShoppingCart)session.getAttribute("previousItems"); if (previousItems == null) { previousItems = new ShoppingCart(...); } String itemID = request.getParameter("itemID"); previousItems.addEntry(Catalog.getEntry(itemID)); session.setAttribute("previousItems", previousItems); Recover the session connected to the client Recover the cart Add a new product to the cart Store the cart in the session

20 20 References Tutorial about Servlets and JSP Understanding Architecture 2 Sun Sun (Servlet and JSP) API Sun (Servlet) Documentation Sun J2EE Tutorial Apache Tomcat Tomcat (servlet) API Tomcat (jsp) API Tomcat in Eclipse (a Tomcat installation is required)http://www.sysdeo.com/eclipse/tomcatplugin Tutorial about how to intregrate Tomcat in Eclipse

21 21 Tomcat configuration (1) Tomcat directory organization: In the directory: $TOMCAT_HOME$/webapps./myApplication./myApplication/*.html./myApplication/WEB-INF/./myApplication/WEB-INF/web.xml./myApplication/WEB-INF/classes/*.class./myApplication/WEB-INF/lib/*.jar [./myApplication/WEB-INF/src/*.java]

22 22 web.xml: – XML file used by Tomcat – it is a deployment descriptor – used to set specific parameters for the current application, such as: name of the servlet (that can be reached though HTTP) URL corresponding to servlet files (e.g., into /WEB-INF/classes/) sessions timeout etc. – it is loaded during the application installation It is composed of the tags: – servlet: set alias and parameters to initialize a given servlet – servlet-mapping: set URL(s) to a given servlet Tomcat configuration (2)

23 23 HelloServlet HelloClientServlet HelloServlet / HelloClientServlet Sample of web.xml Alias to use in HTTP request Name of the class (with package)

24 24 Steps to build a new Web application using Tomcat in Eclipse: 1.Define a new Tomcat Project 2.Write our servlet file in the subdirectory WEB-INF/src 3.Write the servlet configutation file (web.xml) in the subdirectory WEB-INF 4.Start Tomcat or in the right-menu clcik on Tomcat project and reload the context 5.Open a browser, and call the servelt such as Servlet in Eclipse+Tomcat

25 25 How to compile and execute a Servlet? How to use Eclipse to done this task?... Helloworld demo...


Download ppt "1 An introduction to Java Servlet Alessandro Marchetto Fondazione Bruno Kessler-IRST,"

Similar presentations


Ads by Google