20
Introduction to Servlets Based on: Hall, Brown, Core Servlets and JavaServer Pages

Introduction to Servlets

Embed Size (px)

DESCRIPTION

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 - PowerPoint PPT Presentation

Citation preview

Page 1: Introduction to Servlets

Introduction to Servlets

Based on: Hall, Brown, Core Servlets and JavaServer Pages

Page 2: 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.

Page 3: Introduction to Servlets

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

Page 4: Introduction to Servlets

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

Servlet

Response

Request

BrowserHTTP

WebWebServerServer

Servlet Container

Response

Request

Page 5: Introduction to Servlets

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

Page 6: Introduction to Servlets

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

Page 7: Introduction to Servlets

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)

Page 8: Introduction to Servlets

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, ...

Page 9: Introduction to Servlets

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

Page 10: Introduction to Servlets

Servlet Life Cycle

Http request

Http response

Load Invoke No

Yes

Client Server

Is Servlet Loaded?

Servlet Container

RunServlet

Page 11: Introduction to Servlets

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

Page 12: Introduction to Servlets

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

Page 13: Introduction to Servlets

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(); } }}

Page 14: Introduction to Servlets

/** 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>"); }

Page 15: Introduction to Servlets

/** 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)); }}

Page 16: Introduction to Servlets

Example - result

Page 17: Introduction to Servlets

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

Page 18: Introduction to 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

Page 19: Introduction to Servlets

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>

Page 20: Introduction to Servlets

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 } }}