You are on page 1of 5

Bipin S Rupadiya

07/02/12

GUJARAT TECHNOLOGICAL UNIVERSITY


MASTER OF COMPUTER APPLICATIONS (MCA)
SEMESTER: IV

Server Setup & Configuration

Subject Name:
Web Technology & Application Development
(WTAD)
Subject Code: 640002

Mr. Bipin Rupadiya

Servlet Basics,
Basic Servlet Structure,
Servlets Generating text/plain and text/html
content,
Packaging Servlets,
The Servlet Life-Cycle

7-Feb-12

Mr. Bipin Rupadiya

Mr. Bipin Rupadiya

What is Servlet ...?

Servlet is a Java program that run on Web


or application servers,
It behave like a middle layer between
requests coming from the clients Web
browsers and databases server or
applications on the HTTP server
Mr. Bipin Rupadiya

What servlet does...

Read explicit data sent by client

form data which client want to process

Read implicit data sent by client

Benefits

request headers information

Generate the results

Send the explicit data back to client

Send the implicit data to client

Saves time
Response time increases
It is scalable

Process the summited data

Only one copy of servlet is loaded into JVM.


Each request begins a new thread to servlet than a
process.

JVM
Servlet 1

Request for Servlet 1

After processing result is posted back to client

Request for Servlet 2

thread

Servlet 2

Request for Servlet 1

status codes and response headers

www.bipinrupadiya.blogspot.com

Mr. Bipin Rupadiya

Mr. Bipin Rupadiya

Bipin S Rupadiya

07/02/12

Benefits

Efficient

Convenient

Powerful

Portable

Secure

Inexpensive

Servlet Basics,

Servlet use Threads instead of OS processes, so one servlet copy of servlet


persistence on server
Servlet is Lots of high-level utilities for web development
It has very powerful feature like Sharing data, pooling, persistence
It can run on all operating systems and servers
No shell escapes, no buffer overflows
There are many free and low-cost servers available to run servlet.
Mr. Bipin Rupadiya

Mr. Bipin Rupadiya

Servlet Implementation

Basic Servlet Structure


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletName extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
// Use "req object to read incoming HTTP headers
// Example : cookies and query data from HTML forms.
// Use "res" object to specify the HTTP response status
// code and headers Example: the content type, cookies.
PrintWriter out = response.getWriter();
// Use "out" object to send content to browser.
}
}

Servlet use classes and interfaces from two packages

javax.servlet

It contains classes to support generic protocol

javax.servlet.http

It extends classes in servlet package to add HTTP specific


functionality.

Mr. Bipin Rupadiya

10

Mr. Bipin Rupadiya

Basic Servlet element

doGet

doPost

HttpServletRequest

HttpServletResponse

Servlets Generating text/plain


and text/html content

Use for an HTTP GET request.


Use for and HTTP GET request
Contains anything that comes from the client browser
Used to send data/result to the browser. Using PrintWriter
object that points to the browser.

11

www.bipinrupadiya.blogspot.com

Mr. Bipin Rupadiya

12

Mr. Bipin Rupadiya

Bipin S Rupadiya

07/02/12

A Servlet response

Specify which kind of data you are sending

Example

response.setContentType("text/html");
response.setContentType("application/vnd.ms-excel");
response.setContentType("image/jpeg");
Etc

Modify the println statements to build HTML page

Use HTML tags in Print statements which generate html


output

Mr. Bipin Rupadiya

13

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>WTAD</TITLE></HEAD> <body>");
String str="<h1>welcome to </h1>";
str=str+"<br>www.bipinrupadiya.blogspot.com";
out.println(str);
out.println("</body> </html>");
}
}

Mr. Bipin Rupadiya

14

Tomcat install directory / webapps

web.xml structure

Application Name

Give name to servlet


<servlet>
<servlet-name>MyName</servlet-name>
<servlet-class>myPackage.MyServlet</servlet-class>

WEB-INF

</servlet>

classes

<servlet-mapping>

FileName.class

<servlet-name>MyName</servlet-name>
<url-pattern>/my-address</url-pattern>

</servlet-mapping>

web.xml
Mr. Bipin Rupadiya

15

Resultant URL
Any identifier for servlet name
But both must be identical

<servlet-name>bipin1984</servlet-name>
<servlet-class>oet</servlet-class>

http://hostname/appName/my-address

http://localhost:8081/bipin/wtad/bsr.co.in

</servlet> Fully qualified class name


<servlet-mapping>

<servlet-name>bipin1984</servlet-name>
<url-pattern>/wtad/bsr.co.in</url-pattern>

</servlet-mapping>
<web-app>

Mr. Bipin Rupadiya

16

Example of web.xml
<web-app>
<servlet>

Give address (URL mapping) to servlet

Protocol
Custom URL for servlet
Web Application name
Host / domain name

Servlet custom URL

17

www.bipinrupadiya.blogspot.com

Mr. Bipin Rupadiya

18

Mr. Bipin Rupadiya

Bipin S Rupadiya

07/02/12

Output

Packaging Servlets

As in OOP Code must be organized and should be


reused
Package provide the grouping of all related classes
To put our servlets in packages, we need to perform the
following two step

Mr. Bipin Rupadiya

19

Mr. Bipin Rupadiya

20

Tomcat install directory / webapps

Example

Application Name

WEB-INF
classes
Package
FileName.class

web.xml
Mr. Bipin Rupadiya

21

package bsr; // bsr is the sub directory of classes


import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ServletDemo extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>WTAD</TITLE></HEAD> <body>");
String str="<h1>welcome to </h1>";
str=str+"<br>www.bipinrupadiya.blogspot.com";
out.println(str);
out.println("</body> </html>");
}
}

Mr. Bipin Rupadiya

22

Output

Servlet Life Cycle

init

www.bipinrupadiya.blogspot.com

24

Handles GET, POST, etc. requests.


Override these to provide desired behavior.

destroy

Mr. Bipin Rupadiya

Called in a new thread by server for each request.


Dispatches to doGet, doPost, etc.
Do not override this method!

doGet, doPost

Executed once when the servlet is first loaded.


Not called for each request.

service

23

Place the files in a subdirectory that matches the intended


package name
Insert a package statement in the class file

Called when server deletes servlet instance.


Not called after each request.
Mr. Bipin Rupadiya

Bipin S Rupadiya

07/02/12

Servlet Life Cycle

1. Servlet Initialisation
In this first stage, the servlets constructor is

1. Servlet Initialisation

called together with the servlet method init( ) this


is called automatically once during the servlets

2. Servlet Execution

execution life cycle and can be used to place any


one-off initialisation such as opening a connection

3. Servlet Destruction

to a database.
Mr. Bipin Rupadiya

25

2. Servlet Execution

3. Servlet Destruction

Once your Servlet is initialised and its init()


method called, any request that the Servlet Container
receives will be forwarded to your Servlets service()
method. HttpServlet class breaks this service() method
into more useful doGet(), doPost(), doDelete(),
doOptions(), doPut() and doTrace() methods depending
on the type of HTTP request it receives. So in order to
generate response you should override the doGet() or
doPost() method as per your requirement.

Mr. Bipin Rupadiya

27

When your application is stopped or Servlet


Container shuts down, your Servlet's destroy() method
will be called to clean up any resources allocated during
initialisation and to shutdown gracefully. Hence, this
acts as a good place to deallocate resources such as an
open file or open database connection.

www.bipinrupadiya.blogspot.com

Mr. Bipin Rupadiya

28

Example

Thanks . . .

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LotteryNumber extends HttpServlet {
private int[] numbers = new int[10];
public void init() throws ServletException {
for(int i=0; i<numbers.length; i++) {
numbers[i] = randomNum();
} }
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML><HEAD><TITLE>Bipin Rupadiya</TITLE></HEAD><BODY><OL>");
for(int i=0; i<numbers.length; i++) {
out.println(" <LI>" + numbers[i]);
}
out.println("</OL></BODY></HTML>");
}
private int randomNum() {
return((int)(Math.random() * 100));
}}

29

Mr. Bipin Rupadiya

26

Mr. Bipin Rupadiya

Contact:
Bipin S. Rupadiya
(MCA, PGDCA, BCA)

Assistant Professor, JVIMS


Mo. : +91-9228582425
Email : rupadiyabipin@gmail.com
Blog : www.rupadiyabipin.blogspot.com

30

Mr. Bipin Rupadiya

You might also like