An introduction to Java Servlet

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

Servlets & JSPs - Sharad Ballepu.
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.
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.
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.
1 Servlets Based on Notes by Dave Hollinger & Ethan Cerami Also, the Online Java Tutorial by Sun.
CS4273: Distributed System Technologies and Programming I Lecture 11: JavaServer Pages (JSP)
Apache Tomcat as a container for Servlets and JSP
Java Server Pages (JSP)
Java Servlets Java Server Pages (JSP)
JSP1 Java Server Pages (JSP) Introducing JavaServer Pages TM (JSP TM ) JSP scripting elements.
 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.
Servlets and a little bit of Web Services Russell Beale.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 34 Servlets.
JSP Java Server Pages Reference:
All You Ever Wanted To Know About Servlets But Were Afraid to Ask.
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. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
SE-2840 Dr. Mark L. Hornick1 Java Servlet-based web apps Servlet Architecture.
Java Servlets and JSP.
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.
Gayle J Yaverbaum, PhD Professor of Information Systems Penn State Harrisburg.
Java Server Pages B.Ramamurthy. Topics for Discussion 8/20/20152 Inheritance and Polymorphism Develop an example for inheritance and polymorphism JSP.
1 CIS336 Website design, implementation and management (also Semester 2 of CIS219, CIS221 and IT226) Lecture 8 Servlets (Based on Møller and Schwartzbach,
1 Servlet How can a HTML page, displayed using a browser, cause a program on a server to be executed?
Servlets Pranav Maydeo. What is a Servlet ? Servlets are modules of Java code that run in a server application to answer client requests. Servlets are.
Objectives Java Servlet Web Components
Java support for WWW Babak Esfandiari (sources: Qusay Mahmoud, Roger Impey, textbook)
CSC 2720 Building Web Applications
Chapter 5 Java Servlets. Objectives Explain the nature of a servlet and its operation Use the appropriate servlet methods in a web application Code the.
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.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
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.
Java Servlets & Java Server Pages Lecture July 2013.
Java Servlets Lec 27. Creating a Simple Web Application in Tomcat.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Introduction to Server-Side Web Development Introduction to Server-Side Web Development Session II: Introduction to Server-Side Web Development with Servlets.
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.
Servlets.
CSI 3125, Preliminaries, page 1 SERVLET. CSI 3125, Preliminaries, page 2 SERVLET A servlet is a server-side software program, Responds oriented other.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JS (Java Servlets). Internet evolution [1] The internet Internet started of as a static content dispersal and delivery mechanism, where files residing.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
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,
Bayu Priyambadha, S.Kom. Static content  Web Server delivers contents of a file (html) 1. Browser sends request to Web Server 3. Web Server sends HTML.
1 Web Programming with Servlets & JSPs WEB APPLICATIONS – AN OVERVIEW.
CS320 Web and Internet Programming Introduction to Java Servlets Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Introduction to Java Servlets
Java Servlets By: Tejashri Udavant..
Course Outcomes of Advanced Java Programming AJP (17625, C603)
Chapter 6 Server-side Programming: Java Servlets
Chapter 26 Servlets.
Servlets and Java Server Pages
Web Search Interfaces.
Java Servlets and JSP.
CS3220 Web and Internet Programming Introduction to Java Servlets
Presentation transcript:

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

Outline Web applications Java Servlet Servlet engine 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 (Form data) Servlet session tracking

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.

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 technology’s answer to dynamic Web sites. They are programs that run on a Web server and build Web pages. Web Server Script/program DB http request http response Client

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. <html> <head> <title>My title</title> </head> <body> <h1>My header</h\> <a href=“”>My link</a> </body> </html> its DOM http://www.w3.org/TR/html401/ http://www.w3.org/TR/DOM-Level-2-HTML/html.html

Outline Web applications Java Servlet Servlet engine 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

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 http://tomcat.apache.org Relationships between Web server, Servlet engine and Servlets.

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.

How to write a Java servlet HttpServlet implements the Servlet interface … 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 ..... http://java.sun.com/javaee/5/docs/api/

Generic Template The generic template to write Servlet 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 }

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(“<HTML><HEAD><TITLE>Hello Client!</TITLE>”+ “</HEAD><BODY>Hello Client!</BODY></HTML>”); out.close(); }

Context ServletContext 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 1 1 Common Data Servlets

Forms and Servlets (1) How to exchange data between client and server? First Par Second Par Third Par Submit ~hall ~gates ~mcnealy <form method=“GET/POST” action=“ThreeParams”> First Par: <input type=“text” name=“param1” /> Second Par: <input type=“text” name=“param2” /> Third Par: <input type=“text” name=“param3” /> <input type=“submit” value=“Submit” /> </form> 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 http://host/ThreeParams POST: a data packege is created and attached to the HTTP requests sent to the server ? param1= ~hall&param2= ~gates&param3= ~mcnealy

Forms and Servlets (2) ~hall ~ gate ~mcnealy 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) + "<BODY>\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<UL>\n" + " <LI>param1: " + request.getParameter("param1") + "\n" + " <LI>param2: " + request.getParameter("param2") + "\n" + " <LI>param3: " + request.getParameter("param3") + "\n" + "</UL>\n" + "</BODY></HTML>"); } HTML CODE ~hall ~ gate ~mcnealy

Forms and Servlets (3)

HTTP - Stateless protocol (1) The Web server can’t 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.

HTTP - Stateless protocol (2) How to maintain the state HTTP - Stateless protocol (2) There are four ways to maintain the state: Cookies javax.servlet.http.Cookie(String nome, String val) methods: setName(String cookieName), setValue(String cookieValue), etc. Hidden fields in forms <input type=“hidden” value=“<valore>” /> URL rewriting e.g., http://host/serveltPages/ShowSession;jsessionid=E4D371A0710 String encodeURL(String url) of the class HttpServletResponse where: url is the original l’URL and the output is the rewritten one Servlets (HttpSession API)

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) xyz5 Every subsequent connection must send the ID. In this way the server recognize/identify the client

Servlet Sessions (3) HttpSession session = request.getSession(true); Assuming ShoppingCart is some class you have defined yourself that stores information on items being purchased Recover the session connected to the client 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 cart Add a new product to the cart Store the cart in the session

References Tutorial about Servlets and JSP www.apl.jhu/%7Ehall/java/Servlet-Tutorial Understanding “Architecture 2” www.javaworld.com/javaworld/jw-12-1999/jw-12-ssj-jspmvc.html Sun http://java.sun.com/products/servlet/ Sun (Servlet and JSP) API http://java.sun.com/javaee/5/docs/api/ Sun (Servlet) Documentation http://java.sun.com/products/servlet/docs.html Sun J2EE Tutorial http://java.sun.com/javaee/5/docs/tutorial/doc/ Apache Tomcat http://tomcat.apache.org/ Tomcat (servlet) API http://tomcat.apache.org/tomcat-5.0-doc/servletapi/index.html Tomcat (jsp) API http://tomcat.apache.org/tomcat-5.0-doc/jspapi/index.html Tomcat in Eclipse http://www.sysdeo.com/eclipse/tomcatplugin (a Tomcat installation is required) Tutorial about how to intregrate Tomcat in Eclipse http://plato.acadiau.ca/courses/comp/dsilver/2513/EclipseAndTomcatTutorial/

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]

Tomcat configuration (2) 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

Sample of web.xml <?xml version="1.0" encoding="ISO-8859-1"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd" version="2.5"> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>HelloClientServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern>/HelloClientServlet</url-pattern> </servlet-mapping> </web-app> Name of the class (with package) Alias to use in HTTP request

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

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