33
JAVA SERVLETS -OVERVIEW

JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

  • Upload
    others

  • View
    9

  • Download
    0

Embed Size (px)

Citation preview

Page 1: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

JAVA SERVLETS-OVERVIEW

Page 2: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

AGENDA

Servlets

---What are they?

---Why are they needed?

---How do they work?

---Where Used & When ?

Page 3: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

SERVLETS INTRODUCTION

What are Servlets?

Server-side Java Programs run by a Java-enabled web-server

Similar to CGI, but with enhanced performance results,because its multi-threaded.

Responsible for processing client requests

Servlets are to a web server where as applets are to client browsers

In a J2EE Framework, it interacts with middleware business objects(Eg: EJB) to participate in transactions and security.

Page 4: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

CGI Web-Server creates separate processes for each Client Request.

WHY SERVLETS WHEN CGI EXISTS?

CGI-Based

Web Server

Child Process for CGI 1

Child Process for CGI 1

Child Process for CGI 2

CGI

This multi-processing scenario causes multiple processes and a significant amount of server resources, which limits the number of requests a server can handle concurrently.

Request for CGI 1

Request for CGI 1

Request for CGI2

Page 5: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

WHY SERVLETS WHEN CGI EXISTS?

With the advent of FastCGI based web-server, only one persistent process is created for each FastCGI Program.

But, ultimately if this FastCGI program has to handle concurrent requests, it needs a pool of processes, one per request.

Only this is hidden/abstract and managed by the FastCGI Enabled web-server.

FastCGI---Enhanced Version of CGI

FastCGI-Based

Web Server

Child Process for CGI 1

Request for CGI2

Request for CGI 1

Request for CGI 1

Child Process for CGI 2

Page 6: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

WHY SERVLETS WHEN CGI EXISTS?

CGI SERVLETS

Multi-Processing Environment at Server Side

Single Instance of Servlet per JVM(Container),in effect one process New process for each client request

Multiple threads of this instance per request.Multi-Threaded Environment at Server Side.

Not Scaleable.Each process created may be executing a Perl Interpreter(most popular language for CGI) to process client request.

Highly Scaleable. Servlet threads are usually managed(created,executed and destroyed) by the container(JVM)

The CGI scripts are only as portable as the language in which it is written.

Servlets are written in Java and are therefore platform independent,ensuring portability.

CGI Program cannot take advantage of the web server’s abilities once it start execution as it is run as a separate process external to the web-server.For eg: CGI Program cannot write to the server’s log file.

Servlets are alive inside Containers(JVM)attached to the web-server, which talk to the web-server in a well-defined protocol in order to do the threading,security & networking inherent to servlet execution environment. As application developers, you write your business logic and don’t have to worry about,say, the API between Apache Web Server & your web application code.

Page 7: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

HOW DO SERVLETS WORK?

ServletContainer

ServletContainer

response

request

ServletContainer

response

request thread

User clicks a link that has a URL to a servlet

The Container “sees” that the request is for a Servlet.So it creates two objects:

1) HttpServletResponse2) HttpServletRequest

The Container finds the correct servlet based on the URL in the request,creates or allocates a thread for that request and calls the servlet’s service() method,passing the request and response objects as arguments.

GET request

Page 8: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

ServletContainer

HOW DO SERVLETS WORK?

doGET(request,response)

ServletContainer

ServletContainer

response

request

No thread

No requestNo response

The service() method figures out which servlet method to call based on the HTTP Method(GET,POST) etc. sent by the client.

The servlet uses the response object to write out the response to the client.The response goes back to the container.

The service() method completes.So the thread either dies or returns to a container-managed thread pool.The request and response object references fall out of scope,so these are ready for garbage collection.The client gets the response.

Page 9: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

HOW DO SERVLETS WORK?

Servlet Life-Cycle

Load class

ContainerServlet Class

Web Container

Instantiate servlet(constructor runs)

Servlet Object

Your Servlet class no argument constructor runs.You should not write a constructor,just use the compiler-supplied default.

Servlet

Init()

Called only once in the servlet’s life-cycle and must complete before the Container can call the service() method

Initialisedservice()

Handle client requests

Each client request(doGet or doPost) runs as a separate thread.

Initialiseddestroy()

Container calls to give the servlet a chance to clean-up before the servlet is killed(I.e, made ready for garbage collection).Like init() its also called only once.

Page 10: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

HOW DO SERVLETS WORK?

service()

Constructor

init()

Initialised

Does not exist

Destroy()

When did the Servlet Class load?When the Container starts up, it reads a configuration file(usually web.xml) that contains the names of all the servlet class files.These class files are loaded

When was the servlet instance created?The Container then calls the constructor of the servlet classes loaded,inorder to create the servlet instance.

When is init called?The Container calls init() on the servlet instance after the servlet instance is created, but before the servlet service() method is called.Used to initialize the servlet before handling client requests. Eg: Getting a DB Connection or registering your servlet with other objects(maybe CORBA or other distributed objects)

When is service called?When the first client request comes in,the Container starts a new thread or allocates a thread from the pool and causes the servlet’s service() method to be invoked

When is doGET() or doPOST() called?The service() method invokes doGET() or doPOST() based on the HTTP method GET or POST from the request.

What do they do?Its in this method that you write what your servlet is supposed to do.Always override atleast ONE doGet or doPost.Eg: If you don’t override doPost() you are telling the container that this servlet does not support HTTP POST requests.

Page 11: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

HOW DO SERVLETS WORK?<<interface>>

Servlet

Service(ServletRequest,ServletResponse)

Init(ServletConfig)

Destroy()

getServletConfig()

getServletInfo()

GenericServlet

Service(ServletRequest,ServletResponse)

Init(ServletConfig)

Destroy()

Init()

getServletConfig()

getServletInfo()

getInItParameter(String)

getInItParameterNames()

getServletContext()

HttpServlet

Service(HttpServletRequest,HttpServletResponse)

Service(ServletRequest,ServletResponse)

doGet(HttpServletRequest,HttpServletResponse)

doPost(HttpServletRequest,HttpServletResponse)

doHead(HttpServletRequest,HttpServletResponse)

doTrace(HttpServletRequest,HttpServletResponse)

getLastModified()

MyServlet

doPost(HttpServletRequest,HttpServletResponse)

otherBusinessMethods()Abstract class implementing most of the servlet methods we need.

Abstract class implementing the service() method to reflect the Http-nes of the servlet

All servlets have these five methods.The first three are Servlet life-cycle methods.

Page 12: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

HOW DO SERVLETS WORK? Why should we have GenericServlet and ServletRequest and

ServletResponse,if nobody is using anything other than HTTP Servlets?

This was done to instill flexibility into the servlet model so that if we want to use servlets with e.g.: SMTP, or a proprietary custom protocol,we could use these, instead of being stuck with the Http versions.

What special features does a Servlet enjoy?

Before the init() method of the servlet is called by the container, it is also similar to any other ordinary object.After being a servlet, it has the ability to log-events into the web-server’s log file, get references to other resources, store the attributes of other servlets,get information from the Container etc.

What does a Servlet Container do?

--Gives you communication support with the underlying web-server

--Controls the entire life-cycle of your servlets

--Create and manage threads for multiple requests from clients

--XML Deployment Descriptor exists that help avoid hard-coding

--Compiles on the fly JSP into equivalent Servlet code when the need arises.

Page 13: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

BASIC SERVLET STRUCTURE

public class HelloWorld extends javax.servlet.http.HttpServlet{

public void doGet( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response )

throws javax.servlet.ServletException, java.io.IOException{ … }

public void doPost( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response )

throws javax.servlet.ServletException, java.io.IOException{ … }

}

Page 14: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

CONSTRUCTOR AND “MAIN” METHOD Servlet instances are created (invoked) by

servlet container automatically when requested – not by user classes or methods No need to define constructor

The entry point is NOT the “main” method, but the two methods Use “doGet” or “doPost” to perform tasks

For more information http://forum.java.sun.com/thread.jspa?forum

ID=33&messageID=2642093&threadID=543816

Page 15: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

SERVLET EXECUTION

15

Servlet Class

Servlet Instance in Memory

init()

service()doPost()

doGet()

First Request

Subsequent Requests

(can be from different users and sessions)

Page 16: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

REQUEST/RESPONSE BASIC

PROCESSING

Page 17: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

RESPONSE AND REQUEST MESSAGE Web servers and web clients

communicate through HTTP messages (protocols)Request message: client serverResponse message: server client

HTTP message consists of header and bodyHTTP header: information describing the

message and the context of the messageHTTP body: content usually for display

Page 18: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

REQUEST PROCESSING Major request method type

Get User data is sent as part of the request URL No request message body Triggering actions: address bar (in browser),

link, form, …

Post User data is sent in the request message body Triggering actions: form, …

Page 19: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

DOGET() METHOD Servlet class uses the “doGet()” method

to process general (servlet) URL request

public void doGet ( javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response )

throws javax.servlet.ServletException, java.io.IOException{

( generating response message … )}

Page 20: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

RESPONSE PROCESSING Response body

Generating HTML or other content for display

Response headerManipulating response message header

data to affect its behavior

Page 21: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

GENERATING RESPONSE CONTENT Using “response”

(javax.servlet.http.HttpServletResponse) and “java.io.PrintWriter” to generate HTML to the output streamjava.io.PrintWriter out =

response.getWriter();out.println(“<html>”);…out.println(“</html>”);

Page 22: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

HANDLING “GET” PARAMETER

In HTTP “get”, user data are sent with URL

http://…/GetData?p1=value1&p2=value2

Using the request object (given by the doGet method) to retrieve these data

String p1=request.getParameter(“p1”);

String p2=request.getParameter(“p2”);

String p[ ]=request.getParameterValues(“p1”);

Note: parameter names are case sensitive

Page 23: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

NUMBER CONVERSION

All parameter values are String type

String p1=request.getParameter(“p1”);

What if numbers are needed?

Integer.parseInt()Double.parseDouble()

Conversion exception needs to be handled

Page 24: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

IRREGULAR PARAMETERS Missing value (empty string is returned)

…/GetData?data=

Missing parameter (parameter undefined, null)…/GetData? // no parameter at all…/GetData?data // ”data” is still not defined…/GetData?Data=red // case sensitive

Blanks…/GetData?data=hello world

Redundant parameter…/GetData?data=blue&data=red // use

getParameterValues()

Page 25: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

import java.io.*;

import javax.servlet.*;import javax.servlet.http.*;

public class HelloWorldServlet extends HttpServlet {

public void init() throws ServletException { // Initialize and run when loaded. Can use default. } public void destroy() { // Release resources, exit, etc. Can use default. } public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

res.setContentType("text/html");

PrintWriter out = res.getWriter(); out.println("<html>");

out.println("<head><title>Hello World</title></head>"); out.println("<body>"); out.println("<h1>Hello World</h1>"); out.println("</body></html>"); out.close();

}}

Building and Designing ServletsSimple Example

Page 26: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

SESSION MANAGEMENT IN HTTP

Servlet AContainer

doGET(request,response)

HttpSessionA

setAttribute()Thread A

Servlet AContainer HttpSessionA

Thread A

Servlet AContainer

doGET(request,response)

HttpSessionA

setAttribute()Thread B

Same ClientSame ServletDifferent RequestDifferent ThreadSame Session

Seetha

Seetha

Seetha

Page 27: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

Servlet AContainer HttpSessionA

Thread B

SESSION MANAGEMENT IN HTTP

HttpSession A

Geetha

Servlet A

Container

doGET(request,response)

HttpSessionB

setAttribute()Thread C

Seetha

Different ClientSame ServletDifferent RequestDifferent ThreadSame Session

Seetha

Page 28: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

SESSION MANAGEMENT IN HTTP

Http protocol uses stateless connections.The client browser makes a connection to the server, send the request and gets a response,closes the connection. That is, a connection exists for only one single request/response.

Because the connections don’t persist, the Container doesn't recognize that the client making a second request is the same as the client who made the previous request.

Solution: The client needs a unique ID.

Can this ID be the IP Address of the client?

No. If you are on a local IP Network, you have a unique IP Address,but that is not the IP Address the outside world sees. To the server, your IP Address is the same address of the router, so you have the same IP Address as everyone e4lse in the network!

How do we tackle this problem?

Using Session ID and Cookies!

Page 29: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

Servlet AContainer

doGET(request,response)

ID#42 Vanilla

setAttribute(“vanilla”)Thread A

Seetha

SESSION MANAGEMENT IN HTTPRequest,”Vanilla” New request

Response, ID#42

HttpSession

The Container has to get the session ID to the client as part of the response, and the client has to send the session ID as part of the next request. This is done through “Cookies”

Page 30: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

SESSION MANAGEMENT IN HTTP

SAMPLE HTTP REQUEST:

GET /select/myJSp.jsp?name=“Mythili”?ID=100HTTP/1.1

Host: www.myDomain.com

User-Agent: Mozilla/5.0(Macinntosh;PPC Mac OS X Mach-O;en-US)

Accept:text/html,application/xml,text/html,image/jpeg/image/png

Accpet-language: en-us,en

Accept-Encoding:gzip,deflate

Keep-Alive:300

Connection:keep-alive

Page 31: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

SAMPLE HTTP RESPONSE:

HTTP/1/1 200 OK

Set-Cookie:JSESSIONID=0AAB6C8DE414E2E5F307CF334BFCA0C1

Content-type:text/html

Content-Length:397

Date:Thu,01 Dec 2005 11:25:40 GMT

Sever:Apache-Coyote/1/1

Connection:Close

<html>

</html>

Page 32: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

WHEN AND WHERE ARE THEY USED?

Servlets

Used to render dynamic content on the client browser,instead of static HTML Pages,to enable building interactive web-applications

JSPs are automatically complied into servlets when the first client request comes in. JSPs are used to create the presentation layer for the web-browser, by embedding Java code into HTML.

JSPs thus form the View, Servlets the Controller and Simple Java Classes the Model in the MVC Design pattern of the J2EE Framework

In a J2EE Framework, it interacts with middleware business objects(Eg: EJB) to participate in transactions and security.

Page 33: JAVA SERVLETS -OVERVIEW€¦ · Server-side Java Programs run by a Java-enabled web-server Similar to CGI, but with enhanced performance results,because its multi-threaded. Responsible

WHAT IS MVC PATTERN?

<%Shopping Cart Application asking for list of Asterix Comics%>

<%Shopping Cart Application asking for list of Asterix Comics%>

View

JSP

Database

Class DB{Void getDetails(){ /* Talk to Database*/}}

Class DB{Void getDetails(){ /* Talk to Database*/}}

ModelSimple

Java Code

CONTROLLER:Takes User input from request and figures out which Model to call to process the request.

(Eg: Controller Servlet decides to call selectFromDB Java Model as user request involves talking to the database.Also decides which JSP to dispatch the response(result) to.)

VIEW: Responsible for presentation. Accepts user input and displays the response to user requests.

(Eg: The user interface to ask for list of

Asterix Books and their price)

MODEL: Holds the real business logic.If the web application is DB driven, it’s the only part of the system that talks to the database.

(Eg: selectFromDB would be a Java Model that would use other Helper Classes to communicate with the Database to get the Asterix Comics list that the user wanted)

Servlet

Controller