Top Banner

Click here to load reader

© Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher

Dec 23, 2015

ReportDownload

Documents

  • Slide 1
  • Yaron Kanza Servlets Written by Dr. Yaron Kanza, Edited by permission from author by Liron Blecher
  • Slide 2
  • Agenda What is a Servlet Handling HTTP Requests User Input in HTML Handling HTTP Response Servlet Life Cycle Servlet Context Request Dispatcher Sessions
  • Slide 3
  • A Java application that is being run by a Web server Can receive parameters in an HTTP request Generates an HTTP response Web browser Web server request response Servlet What is a Servlet 3
  • Slide 4 Friendly Time What is your name? 4 The n"> Friendly Time What is your name? 4 The name of the application (Servlet) The name of a parameter What is a Servlet - Example"> Friendly Time What is your name? 4 The n" title=" Friendly Time What is your name? 4 The n">
  • Friendly Time What is your name? 4 The name of the application (Servlet) The name of a parameter What is a Servlet - Example
  • Slide 5
  • 5 send What is a Servlet - Example
  • Slide 6
  • 6 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class TimeServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); Calendar cal = new GregorianCalendar(); String username = req.getParameter("username"); out.println(" Time "); out.println( " \n Hello " + username + ". The time is: " + " " + cal.get(Calendar.HOUR_OF_DAY) + ":" + cal.get(Calendar.MINUTE) + ":" + cal.get(Calendar.SECOND) + " " + " \n \n "); } }
  • Slide 7
  • 7 What is a Servlet - Example http:// localhost:8080/Examples/time/show?username=Homer
  • Slide 8
  • Web Application File Structure 8 time.html TimeServlet.class TimeServlet.java web.xml
  • Slide 9
  • 9 hello examples.HelloServlet time TimeServlet hello /hello time /time/show Servlet web.xml
  • Slide 10
  • Servlet Annotations As of Java EE 6 you can use Annotation instead of web.xml @WebServlet(name = "TestServlet", urlPatterns = {"/search"}) public class TestServlet extends HttpServlet {... { @WebServlet the annotation that defines the class as a servlet Name the servlet name urlPattern one or more patterns that will be handled by the servlet 10
  • Slide 11
  • Java provides the interface Servlet Specific Servlets implement this interface Whenever the Web server is asked to invoke a specific Servlet, it activates the method service() of an instance of this Servlet service(request,response) MyServlet (HTTP) request (HTTP) response 11 The Servlet Interface
  • Slide 12
  • YourOwnServlet HttpServlet Generic Servlet Servlet service(ServletRequest, ServletResponse) doGet(HttpServletRequest, HttpServletResponse) doPost(HttpServletRequest HttpServletResponse) doPut doTrace Called by the servlet container to allow the servlet to respond to a specific request method A generic, protocol-independent class, implementing Servlet Servlet Hierarchy 12 Called by the servlet container to allow the servlet to respond to any request method
  • Slide 13
  • Class HttpServlet handles requests and responses according to the HTTP protocol The service() method of HttpServlet checks the request method and calls the appropriate HttpServlet method: doGet, doPost, doPut, doDelete, doTrace, doOptions or doHead 13 Class HttpServlet
  • Slide 14
  • Extend the class HTTPServlet Implement doGet or doPost (or both; also maybe others) Both methods get: HttpServletRequest: methods for getting form (query) data, HTTP request headers, etc. HttpServletResponse: methods for setting HTTP status codes, HTTP response headers, and get an output stream used for sending data to the client Many times, we implement doPost by calling doGet, or vice-versa 14 Creating a Servlet
  • Slide 15
  • import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class TextHelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println("Hello World"); } public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { doGet(req, res); } Creating a Servlet Hello World 15
  • Slide 16
  • DEMO Examples.servlets.DateServlet 16
  • Slide 17
  • Agenda What is a Servlet Handling HTTP Requests User Input in HTML Handling HTTP Response Servlet Life Cycle Servlet Context Request Dispatcher Sessions
  • Slide 18
  • Getting HTTP Headers Values of the HTTP request can be accessed through the HttpServletRequest object Methods for specific request information: getCookies, getContentLength, getContentType, getMethod, getProtocol, etc. 18
  • Slide 19
  • Agenda What is a Servlet Handling HTTP Requests User Input in HTML Handling HTTP Response Servlet Life Cycle Servlet Context Request Dispatcher Sessions
  • Slide 20
  • Using HTML forms, we can pass parameters to Web applications comprises a single form action: the address of the application to which the form data is sent (should be relative to the current page) method: the HTTP method to use when passing parameters to the application (e.g. get or post) 20 User Input in HTML
  • Slide 21
  • The Tag Inside a form, INPUT tags define fields for data entry Standard input types include: buttons, checkboxes, password fields, radio buttons, text fields, image- buttons, text areas, hidden fields, etc. Each one associates a single (string) value with a named parameter 21
  • Slide 22
  • Getting user input in the servlet Use the following HTTPServleRequest methods to get the user input: getParameter( ); getParameterNames returns an enumeration of all the parameters that came on the request getParameterMap return a map of all the parameters and their values 22
  • Slide 23
  • DEMO Examples.htmlinput 23
  • Slide 24
  • Agenda What is a Servlet Handling HTTP Requests User Input in HTML Handling HTTP Response Servlet Life Cycle Servlet Context Request Dispatcher Sessions
  • Slide 25
  • Class HTTPServletResponse provides setters for some specific headers: -setContentType -setContentLength automatically set if the entire response fits inside the response buffer -setDateHeader -setCharacterEncoding 25 Setting Response HeadersSetting Response Header
  • Slide 26
  • The response body is buffered Data is sent to the client when the buffer is full or when the buffer is explicitly flushed Once the first data chunk is sent to the client, the response is committed You cannot set the response line nor change the headers. Such operations are either ignored or cause an exception to be thrown 26 The Response Content Buffer
  • Slide 27
  • Agenda What is a Servlet Handling HTTP Requests User Input in HTML Handling HTTP Response Servlet Life Cycle Servlet Context Request Dispatcher Sessions
  • Slide 28
  • When a URL that a servlet is mapped to is requested, the server loads the Servlet class and initializes one instance of it Each client request is handled by the Serlvet instance in a separate thread The server can remove the Servlet The Servlet can remain loaded to handle additional requests Servlet Life Cycle 28
  • Slide 29
  • Servlet Life Cycle cont When the Servlet in instantiated, its method init() is invoked (in our case, by Tomcat) External parameters can be provided Upon a request, its method service() is invoked Before the Servlet removal, its method destroy() is invoked 29
  • Slide 30
  • Servlet Class Calling the init method Servlet Instance Deal with requests: call the service method Destroy the Servlet: call the destroy method Garbage Collection ServletConfig In our case by servlet we refer to any class extending HttpServlet Servlet Life Cycle cont 30
  • Slide 31
  • The method init has a parameter of type ServletConfig ServletConfig has methods to get external initialization parameters (getInitParameter()) In Tomcat, these parameters are set in web.xml To make initializations, override init() and not init(ServletConfig) The former is automatically called by the latter after performing default initializations If we use init(), how can we obtain a reference to the ServletConfig ? Servlet.getServletConfig() 31 Initializing Servlets
  • Slide 32
  • InitExample ServletInit login Homer 32 A web.xml Example
  • Slide 33
  • A Servlet is usually loaded when it is first being called You can set Tomcat to load a specific Servlet on startup in the Servlet declaration inside web.xml InitExample ServletInit 33 Loading a Servlet on Startup
  • Slide 34
  • DEMO Examples.servlets 34
  • Slide 35
  • Agenda What is a Servlet Handling HTTP Requests User Input in HTML Handling HTTP Response Servlet Life Cycle Servlet Context Request Dispatcher Sessions
  • Slide 36
  • Servlet Context Allows servlets that belong to the same application to share data and communicate For instance, can be used to store details for a JDBC connection (details that are shared by different servlets) Allows setting and getting attributes Provides information
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.