Download presentation
Presentation is loading. Please wait.
1
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages
2
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.
3
J2EE Technologies J2SE JAX-RPC Web Service for J2EE J2EE Management J2EE Deployment JMX JMS JTA Servlet JSP EJB JAXR Connector JACC JAXP JavaMail JAF
4
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
5
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
6
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(" First Servlet "); out.println(" Hello Code Camp! "); } Java code that produces html output
7
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)
8
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,...
9
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
10
Servlet Life Cycle Http request Http response Load Invoke No Yes ClientServer Is Servlet Loaded? Servlet Container Run Servlet
11
Servlet Life-Cycle methods Ready doGet( )doPost( ) destroy( )init( ) Request parameters Init parameters Methods invoked by Container defined in javax.servlet.http.HttpServlet and super classes Programming a servlet consists of overriding these methods
12
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
13
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(); }
14
/** 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 = " \n"; out.println(docType + " \n" + " " + title + " \n" + " \n" + " " + title + " \n" + " 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. " + " "); for(int i=0; i<numbers.length; i++) { out.println(" " + numbers[i]); } out.println(" "); }
15
/** 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 not 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)); }
16
Example - result
17
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
18
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
19
Handling Form Data Client Information Form Client id Client name Client birthdate
20
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 }
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.