Servlet Lifecycle Lec 28
Servlet Life Cycle Initialize Service Destroy Time
Life Cycle: Initialize Executed once, when the servlet gets loaded for the first time Not called for each client request Put your initialization code here.(No constructor available)
Life Cycle: Service On each request, the server spawns a new thread and calls service()
Life Cycle: Service service() checks HTTP request type and calls doGet() or doPost() Override doGet() or doPost() to provide desired behaviour.
EE557: Server-Side Development Life Cycle: Service
Life Cycle: Destroy destroy() method is called only once Call takes place when Application is stopped Servlet container shuts down Allows resources to be freed freed
EE557: Server-Side Development Servlet Life Cycle Summary
Java Servlets Form Data
How client sends data? When a user submits a browser request to a web server, it sends two categories of data: Form Data: Data that the user explicitly typed into an HTML form. For example: registration information. HTTP Request Header Data: Data that is automatically appended to the HTTP Request from the client. For example: cookies, browser type, browser IP address.
EE557: Server-Side Development Html Form & Servlet HTML is Graphical User Interface (GUI) for a servlet
Example : Reading two explicit parameters
Form Example Our first example consists of one HTML page (index.html), and one servlet (FormServlet.java). The HTML page contains two form parameters: firstname, surname The Servlet extracts these specific parameters and echoes them back to the browser after appending Hello.
index.html
EE557: Server-Side Development Reading Two Parameters Please fill out this form: <FORM METHOD="GET" ACTION=" NAME="myform"> Firstname: Surname: ……….. Form Example (using GET)
EE557: Server-Side Development Form Example cont. (using GET)
EE557: Server-Side Development import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String fName = req.getParameter(“firstname”); String sName = req.getParameter(“surname”); PrintWriter out = res.getWriter(); out.println("Hello: " + fName + “ “ +sName "); out.close(); } FormServlet.java (using GET)
web.xml <web-app> FormServlet FormServlet MyServlet MyServlet FormServlet FormServlet /formservlet /formservlet </web-app> ACTION="
Using NetBeans4.1