200 likes | 326 Views
Based on: Hall, Brown, Core Servlets and JavaServer Pages. Introduction to Servlets. Java2 Enterprise Edition(J2EE) Framework. Developed by SUN open standard Offers a suite of software specification to design, develop, assemble and deploy enterprise applications
E N D
Based on: Hall, Brown, Core Servlets and JavaServer Pages Introduction to Servlets
Java2 Enterprise Edition(J2EE) Framework • Developed by SUN • open standard • Offers a suite of software specification to design, develop, assemble and deploy enterprise applications • n-tier, Web-enabled,server-centric, component-based • Provides a distributed, component-based, loosely coupled, reliable and secure, platform independent application environment.
J2EE Technologies • Servlet • JSP • EJB • JAXR • Connector • JACC • JAXP • JavaMail • JAF • J2SE • JAX-RPC • Web Service for J2EE • J2EE Management • J2EE Deployment • JMX • JMS • JTA
What are Servlets ? • Java technology for dynamic (web) content generation • Run in a Servlet Container • Receives requests from clients (web browsers), process them and generate response (html pages) that are sent back to clients
Why Build Web Pages Dynamically ? • Static html web pages are very limited • Dynamic generation is needed when for instance • The web page is based on data sent by the client • search results • login to personal page • order page at online store • ... • The web page is derived from data that changes frequently • weather page • stock market quotes • ... • The web page uses information from databases or other server-side sources
Example of servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; Public class HelloServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<title>First Servlet</title>"); out.println("<big>Hello Code Camp!</big>"); } } Java code that produces html output
What does a servlet do ? • Receives client request (mostly in the form of HTTP request) • Extract some information from the request • Do content generation or business logic process (possibly by accessing database, invoking EJBs, etc) • Create and send response to client (mostly in the form of HTTP response) or forward the request to another servlet (or JSP page)
Servlet Containers • Servlet runs in a “Servlet Container” • cooperates with a http server process • maps URLs to servlets • provides standard services (life cycle management, resource usage, deployment mechanisms, security, possibly transaction management) • Several existing “Servlet Containers” • all need to satisfy a servlet container specification • examples: Apache Tomcat, Jetty, Redhat JBoss, BEA Weblogic, SUN Java System Web Server, IBM Websphere, ...
Requests • Carry information sent from a client (e.g. web browser) to a server • The most common client requests • HTTP GET & HTTP POST • GET requests: • User entered information is appended to the URL in a query string • Can only send limited amount of data • .../servlet/ViewCourse?FirstName=John&LastName=Wayne • POST requests: • User entered information is sent as data (not appended to URL) • Can send any amount of data
Servlet Life Cycle Is Servlet Loaded? Http request No Invoke Load Yes Http response RunServlet Servlet Container Client Server
Servlet Life-Cycle methods • Methods invoked by Container • defined in javax.servlet.http.HttpServlet and super classes • Programming a servlet consists of overriding these methods init( ) destroy( ) Ready Init parameters doGet ( ) doPost ( ) Request parameters
Servlet Life-Cycle methods • init() • Invoked once when the servlet is first instantiated • Perform any set-up in this method • destroy() • Invoked before servlet instance is removed • Perform any clean-up • Closing a previously created database connection • doGet(), doPost(), doXxx() • Handles HTTP GET, POST, etc. requests • Override these methods in your servlet to provide desired behavior
Servlet Life-Cycle methods - example import javax.servlet.*; import javax.servlet.http.*; public class LotteryNumbers extends HttpServlet { private long modTime; private int[] numbers = new int[10]; /** The init method is called only when the servlet * is first loaded, before the first request * is processed. */ public void init() throws ServletException { // Round to nearest second (i.e, 1000 milliseconds) modTime = System.currentTimeMillis()/1000*1000; for(int i=0; i<numbers.length; i++) { numbers[i] = randomNum(); } } }
/** Return the list of numbers that init computed. */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Your Lottery Numbers"; String docType = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">\n"; out.println(docType + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n" + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<B>Based upon extensive research of " + "astro-illogical trends, psychic farces, " + "and detailed statistical claptrap, " + "we have chosen the " + numbers.length + " best lottery numbers for you.</B>" + "<OL>"); for(int i=0; i<numbers.length; i++) { out.println(" <LI>" + numbers[i]); } out.println("</OL></BODY></HTML>"); }
/** The standard service method compares this date * against any date specified in the If-Modified-Since * request header. If the getLastModified date is * later or if there is no If-Modified-Since header, * the doGet method is called normally. But if the * getLastModified date is the same or earlier, * the service method sends back a 304 (Not Modified) * response and does <B>not</B> call doGet. * The browser should use its cached version of * the page in such a case. */ public long getLastModified(HttpServletRequest request) { return(modTime); } // A random int from 0 to 99. private int randomNum() { return((int)(Math.random() * 100)); } }
Handling Form Data • Forms are used to submit request through web pages • data is send using GET or POST • data received as request parameters by Servlets
Handling Form Data • A request can come with any number of parameters • Parameters are sent from HTML forms: • GET: as a query string, appended to a URL • POST: as encoded POST data, not appeared in the URL • getParameter("paraName") • Returns the value of paraName • Returns null if no such parameter is present • Works identically for GET and POST requests
Handling Form Data <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <h1>Client Information Form</h1> <form name="userForm" action="lookup"method="POST"> Client id <input type="text" name="id" value=""/> Client name <input type="text" name="name" value="" /> Client birthdate <input type="text" name="birthdate" value="" /> <input type="submit" value="Lookup" name="lookup" /> <input type="submit" value="Add" name="add" /> <input type="reset" value="Cancel" name="cancel" /> </form> </body> </html>
public class LookupServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ... // get value of id field String id = request.getParameter("id"); // get value of name field String name = request.getParameter("name"); // get value of birthdate file Date birthdate = request.getParameter("birthdate"); ... // check if lookup is pressed if (request.getParameter("lookup" != null)) { // do whatever should be done } // check if add is pressed if (request.getParameter("add" != null)) { // do whatever should be done } } }