Servlets O. De Pertat. Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

4 Copyright © 2005, Oracle. All rights reserved. Creating the Web Tier: Servlets.
6 Copyright © 2005, Oracle. All rights reserved. Using Advanced Techniques in Servlets.
CGI programming. Common Gateway Interface interface between web server and other programs (cgi scripts) information passed as environment variables passed.
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
 2002 Prentice Hall. All rights reserved. Chapter 9: Servlets Outline 9.1 Introduction 9.2 Servlet Overview and Architecture Interface Servlet and.
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.
An introduction to Java Servlet Programming
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 CS-328 Dick Steflik. What is a servlet A Java application run on a thread of the webserver in response to an HTTP GET or POST request. The servlet.
IBM Labs in Haifa Dynamic Web programming with Servlets Gal Shachor.
Java Server and Servlet CS616 Team 9 Kim Doyle, Susan Kroha, Arunima Palchowdhury, Wei Xu.
COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
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. Our Project 3-tier application Develop our own multi-threaded server Socket level communication.
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.
Ch 3 - Java Servlets COSC 617 Jeff Schmitt September 21, 2006.
Java Servlet Technology. Introduction Servlets are Java programs that run on a Web server, handle HTTP requests and build Web pages Servlet specification.
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
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.
CMPUT 391 – Database Management Systems Department of Computing Science University of Alberta CMPUT 391 Database Management Systems Web based Applications,
COMP201 Java Programming Part III: Advanced Features Topic 14: Servlets Servlets and JavaServer Pages (JSP) 1.0: A Tutorial
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.
1 Servlets Modified slides from Dr.Sagiv. 2 Introduction.
20-Nov-15introServlets.ppt Intro to servlets. 20-Nov-15introServlets.ppt typical web page – source Hello Hello.
Java Servlet API CGI / HTTP Concepts Java Servlet API.
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
Copyright © 2002 ProsoftTraining. All rights reserved. Java 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.
ORIGINAL BY WENDY LIU CURRENT API: Java Servlet and JSP 1.
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
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.
® IBM Software Group © 2007 IBM Corporation Servlet API (Part II)
Advanced Java Session 6 New York University School of Continuing and Professional Studies.
K. K. Wagh Polytechnic, Nashik
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 21 Java Servlets Wed. 11/22/00 based on material.
SERVLET THETOPPERSWAY.COM
Introduction To HTML Dr. Magdi AMER. HTML elements.
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.
Java Servlets References: Karen Anewalt, Mary Washington College.
CS122B: Projects in Databases and Web Applications Spring 2017
CS122B: Projects in Databases and Web Applications Winter 2017
Servlets.
Servlet Fudamentals.
Pre-assessment Questions
Java Servlets 9/21/2018.
Chapter 26 Servlets.
CS122B: Projects in Databases and Web Applications Winter 2018
CS122B: Projects in Databases and Web Applications Spring 2018
Servlet APIs Every servlet must implement javax.servlet.Servlet interface Most servlets implement the interface by extending one of these classes javax.servlet.GenericServlet.
Introduction to Java Servlets
CS122B: Projects in Databases and Web Applications Winter 2019
Presentation transcript:

Servlets O. De Pertat

Servlets Overview Generic Server Business logic API Java Syntax: classes extending the javax.servlet.Servlet interface or any sub-class. Packages: javax.servlet javax.servlet.http.*. Features: Thread–oriented instead of process management (like CGI or Fast- CGI) High level API Performance for parameters transmission Runs on every operating system Secure : no SHELL escapes, no buffer overflows Java programming language (PHP, VB.NET, Python)

Servlets Container used Apache – Jakarta Tomcat : Conteneur de référence Officiel IBM – WebSphere BEA – WebLogic Alliance - iPlanet (Sun & NetScape) Oracle – IAS Allaire – Jrun Caucho’s Resin

Javax.servlet

Javax.servlet.http

Servlets types Servlet interface is the contract passed between a Servlet and its container. GenericServlet basic implement of a Servlet. Implementation is not protocol specific. HttpServlet HTTP protocol implementation of a Servlet. Every class that extends of the previously described class.

Servlets life cycle

Servlet Initialization Handle by the init method that we can overload: Open Database connection Variables initializations… getInitParameter() method allows to retrieve the declared parameters set into the web container configuration. Into TOMCAT: foo bar

Handling requests The WebContainer invoke the service(ServletRequest req, ServletResponse res) method. For an HTTP Servlet the service method is overloaded and call the method that fit to the HTTP Command: GET : protected void doGet (HttpServletRequest req, HttpServletResponse resp) POST : protected void doPost (HttpServletRequest req, HttpServletResponse resp) HEAD : protected void doPost (HttpServletRequest req, HttpServletResponse resp) PUT : protected void doPut (HttpServletRequest req, HttpServletResponse resp)....

Servlet Response ServletResponse interface implemention getOutputStream() getWriter() HttpServletResponse : STATUS CODE : SC_OK, SC_NOT_FOUND setContentType() : "text/html", "image/gif" setStatus() : 200, SC_OK, SC_NOT_FOUND… addCookie() : add a cookie to the HTTP response setDateHeader() : sets Date in HTTP response’s header setHeader() : to set any HTTP Header sendError() : to send an HTTP error to the client

Servlet Request HttpServletRequest. Interface implementation getInputStream(),getReader() : binary & text streams handling getScheme() : what protocol is used? (http, https) getParameterNames(), getParameterValues() : parameters handling getContentType() : text/html, … getRemoteAddr(), getRemoteHost() HttpServletRequest : getHeaderNames() : HTTP header management getMethod() : HTTP Method used HTTP: GET,POST getRequestURI() : What URI the client asked for? Cookies management Session handling

Hello World ! public class Hello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) HttpServletResponse resp) throws ServletException, IOException throws ServletException, IOException { resp.setContentType("text/html"); resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); PrintWriter out = resp.getWriter(); String name = req.getParameter("name"); String name = req.getParameter("name"); if(name==null) name="World !"; if(name==null) name="World !"; out.println(" "); out.println(" "); out.println("Hello " + name ); out.println("Hello " + name ); out.println(" "); out.println(" "); }}

Ways to call a Servlet JSP (Java Server Page) From a Document or WebBrowser From an other Servlet BookDBServlet database = (BookDBServlet) this.getServletConfig().getServletContext().getServlet ("bookdb"); SSI

Including external elements Including Servlet output into an other one: ServletContext sc = getServletContext(); RequestDispatcher d = sc.getRequestDispatcher( "/AnOtherServlet"); req.setAttribute("Param", "Value"); d.include(req, resp); Non dynamic element inclusion: URL url = sc.getResource(« /hello.html"); Out.print(url.getContent());

Multi-Threaded Environment Warning! Servlet’s Data are not thread- protected ! Two protections: Synchronized method; Implements SingleThreadModel Interface

Cookies Data stored on the client-side by the server Structure: Name, Value, Expiration date, domain, path Managed by the class javax.servlet.http.Cookie Java Class Cookie allows to read, add & remove HTTP Cookies (RFC 2109). Allows user’s session handling above HTTP Protocol

Reading / Adding Cookies Reading Cookies : Cookie [] cookies = req.getCookies(); for (int i=0 ; i < cookies.length ; i++) { out.print(cookies[i].getName() +"=" ); out.println(cookies[i].getValue() ); } Adding Cookies : userid = generationIDUtilisateur(); Cookie c = new Cookie("userid", userid); c.setDomain(".i2sconsulting.fr"); c.setPath("/"); resp.addCookie(c);

HTTP Session Session handling: Cookies Long URL Opening/retrieving a session javax.servlet.http.HttpSession session = req.getSession(false); // la session est récupérée ou null si elle n ’existait pas déjà javax.servlet.http.HttpSession session = req.getSession(true); // la session est récupérée ou ouverte si elle n ’existait pas déjà Session invalidation javax.servlet.http.HttpSession session = req.getSession(false); session.invalidate(); // la session est invalidée (i.e. fermée)

HttpSession - 1 Identification String sessionid= session.getId(); // Example: To1010mC At Creation date long datecreation= session.getCreationTime(); // nb de ms depuis 1/1/1970:00:00 Last access date long datelastaccess= session.getLastAccessedTime(); Example HttpSession session = req.getSession(true); if(session.getLastAccessedTime() - session.getCreationTime() > 5*60*1000 ) { session.invalidate(); }

HttpSession - 2 Session handling boolean HttpServletRequest.isRequestedSessionIdFromCookie() // is this session opened with a cookie? boolean HttpServletRequest.isRequestedSessionIdFromURL() // do we use URL rewrite method? URL Rewrite (if isRequestedSessionIdFromURL) URL generated must be encoded in order to keep the session String HttpServletResponse.encodeRedirectURL(String url) String HttpServletResponse.encodeURL(String url) Example res.sendRedirect(res.encodeRedirectURL("/servlet/login");

Adding Objects to a Session Used: database connection, carts… Adding/replacing a value void HttpSession.putValue(String name, Object value) Deleting a value void HttpSession.removeValue(String name) Getting objects associated to session String[] HttpSession.getValueNames() Object HttpSession.getValue(String name) Example HttpSession session = req.getSession(true); if(session.getLastAccessedTime() - session.getCreationTime() > 5*60*1000) { session.invalidate(); }

WebContainer Architecture