+ All Categories
Home > Documents > Servlet Introduction

Servlet Introduction

Date post: 28-Dec-2015
Category:
Upload: zircon2014
View: 19 times
Download: 1 times
Share this document with a friend
Description:
Servlet Introduction
Popular Tags:
52
Servlet: Introduction
Transcript
Page 1: Servlet Introduction

Servlet: Introduction

Page 2: Servlet Introduction

New methods added in HTTPServlet10

HTTPServlet9

GenericServlet8

Servlet Class hierarchy7

Servlet instance6

Servlet Life Cycle5

Servlet interface4

JSDK3

Servlet Request Response Mechanism2

Definition1

Contents

Page 3: Servlet Introduction

Deploying20

Packaging19

Writing web.xml18

web.xml17

Brief introduction to XML16

Deployment Descriptors15

HTML file with a link to servlet14

Steps to deploy a web application13

A Simple Servlet 12

Request and Response object11

Contents

Page 4: Servlet Introduction

Getting single parameters30

HttpServletResponse Interface29

ServletResponse Interface28

HttpServletRequest Interface27

ServletRequest26

Request and Response hierarchy25

Execution24

Deployment23

Steps for packaging22

Packaging and deploying the servlet21

Contents

Page 5: Servlet Introduction

SingleThreadModel Interface34

Servlet variable initialization33

Servlet to get multiple param32

Getting multiple parameters31

Contents

Page 6: Servlet Introduction

Know

• What a servlet is and its lifecycle• The Request Response Mechanism• Servlet classes

• HttpServletRequest and HttpServletResponse classes

Page 7: Servlet Introduction

Be Able To

• Write a simple servlet

Page 8: Servlet Introduction

Definition

• A servlet is a server side program written in Java that resides and executes in an application server

• It enables the delivery of dynamic content

Page 9: Servlet Introduction

Servlet Request Response Mechanism

Servlet

Database

Client Web Server

Application ServerRequest

Response

If request is for static page return the page as responseElsePass the request to application server

Page 10: Servlet Introduction

JSDK

• Java Servlet Development Kit (JSDK) contains the class library that is required to create servlets and JSP.

• The 2 packages that are required to create servlets are javax.servlet and javax.servlet.http.

• A java class is a servlet if it directly or indirectly implements the Servlet interface.

Page 11: Servlet Introduction

Servlet interface

• public void init(ServletConfig config) throws ServletException

• public void service(ServletRequest req, ServletResponse res) throws ServletException, java.io.IOException

• public void destroy()• public ServletConfig getServletConfig()

• public String getServletInfo()

Life cycle methods

Page 12: Servlet Introduction

Servlet instanceServletInstantiation

New instance created on first request

Initialized Servlet init() is called

Application Server

Request servicing Servlet

service() is called

Destroyed Servlet

destroy() is called

Initialization

Begin service

Destruction

Servlet Life Cycle

First request

Subsequent requests

Page 13: Servlet Introduction

Servlet instance

• Only one instance of a particular servlet class is created. The same instance is used for all the requests.

• When the container shuts down, this instance is destroyed.

Page 14: Servlet Introduction

Servlet instance

• The container runs multiple threads on the service() method to process multiple requests.

• Only a single instance of servlet of each type ensures minimum number of servlet objects created and destroyed on the server – adds to scalability

Page 15: Servlet Introduction

Servlet Class hierarchy

javax.servlet.GenericServlet

javax.servlet.http.HttpServlet

javax.servlet.Servlet

Page 16: Servlet Introduction

GenericServlet• GenericServlet class provides basic

implementation of the Servlet interface.

• This is an abstract class. It implements all the methods except service() method.

Page 17: Servlet Introduction

GenericServlet• Other methods included are:

– public void log(String message)– public void init() throws ServletException

• The implementation of init(ServletConfig config)calls init()method.

Page 18: Servlet Introduction

HTTPServlet

• HTTPServlet inherits from the GenericServlet and provides a HTTP specific implementation of the Servlet interface.

• The service(ServletRequest req, ServletResponse res) method is implemented.

Page 19: Servlet Introduction

HTTPServlet

• Since this implementation specific to HTTP protocol, there are methods that specific to each HTTP methods like GET, POST, TRACE etc.

• It is an abstract class and is subclassed to create an HTTP servlet suitable for a Web site.

Page 20: Servlet Introduction

New methods added in HTTPServlet

protected void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, java.io.IOException

protected void doXXX(HttpServletRequest req, HttpServletResponse res)

XXX is GET, POST, TRACE, PUT, DELETE• A subclass of HttpServlet must override

• at least one method, usually one of doGet, doPost, doDelete, doPut, doHead

• init and destroy to manage resources that are held for the life of the servlet.

Our focus

Page 21: Servlet Introduction

Request and Response object

Servlet A

Request for servlet A

Response

Client

Web Server

Application server

HTTP request packet

HttpServletRequest Object

HttpServletResponse Object

Web Container

HTTP response packet

Page 22: Servlet Introduction

A Simple Servletimport javax.servlet.http.*;import javax.servlet.*;import java.io.*;

public class GreetingServlet extends HttpServlet {

String welcomeMsg=“Welcome to simple servlet”;

java.util.Date currDate;

greet.war

Page 23: Servlet Introduction

public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {currDate=new java.util.Date();PrintWriter out = response.getWriter();response.setContentType("text/html"); out.println("<html><head><title>Greetings Servlet </title></head>”);

out.println("<body>”+ welcomeMsg+”<br>”+currDate+”</body></html>");}}

Page 24: Servlet Introduction

Steps to deploy a web application

Write servlets. Compile them.

• Write html and jsp files.

• Write deployment descriptor web.xml.• Package the application

• Deploy the application

Page 25: Servlet Introduction

HTML file with a link to servlet

<html><head><title>Greet</title></head><body><h1>Simple Example</h1>Click to invoke the servlet<a href=“greet.do”>Greetings</a></body></html>

index.html

We will map the servlet and the url shortly

Page 26: Servlet Introduction

Deployment Descriptor• Deployment descriptors is an xml file that helps in

managing the configuration of an application.• This is the file using which an application can

communicate with the container and vice versa.• For a web application, the deployment descriptor file

name is web.xml.• The Java Servlet specifies a document type

definition for deployment descriptor which is available at

http://java.sun.com/j2ee/dtds/web_app_2_2.dtd

Page 27: Servlet Introduction

Brief introduction to XML• XML stands for EXtensible Markup Language.

XML is a markup language much like HTML. • XML was designed to describe data. XML was

created to structure, store and to send information.

• XML is a cross-platform, software and hardware independent tool for transmitting information.

• XML tags are not predefined. You must define your own tags.

• One of the uses of XML is to exchange data.

Page 28: Servlet Introduction

web.xml• Servlet components that are used in web

application along with their fully qualified class names

• URLs for servlets • Welcome file name

• Initialization parameters if any • Session Configuration• Application Lifecycle Listener classes• Filter Definitions and Filter Mappings• Error Pages

• Environment Variable Mappings• Mime type mapping

Our focus in this chapter

Page 29: Servlet Introduction

Writing web.xml <web-app> <display-name>Greet</display-name> <servlet>

<servlet-name>Greet</servlet-name>

<display-name>simple</display-name>

<servlet-class>GreetingServlet</servlet-class>

</servlet>

Optional. IDE’s use it for listing web application name

Identifier for this servlet in the web appliaction

Fully qualified name for the servlet

Page 30: Servlet Introduction

<servlet-mapping> <servlet-name>Greet</servlet-name> <url-pattern>

/greet.do</url-pattern> </servlet-mapping>

</web-app>

Append a / for tomcat

URL that is going to used to access this component

specify the identifier for which component url is going to be mapped

<welcome-file-list><welcome-file>index.html</welcome-file><welcome-file>default.jsp</welcome-file></welcome-file-list>

Optional because index.html is welcome file by default!

If index.html is not found, container will look for default.jsp.

Page 31: Servlet Introduction

Packaging• Packaging application means placing the

files in the appropriate placeholders (directory).

Page 32: Servlet Introduction

Packaging

• Servlet specification lays out the rules of how enterprise applications should be packaged.

• This is necessary so that the container (any j2ee container) knows where to find the files (the servlet class files, html class files etc.)

• Since a web application is composed of many files, the specification also tells us how to archive the files and deploy it as single file application.

Page 33: Servlet Introduction

Deploying• Deploying means uploading the

application on the server.

• If there is any problem with the packaging, the application will not be uploaded.

• There are many J2EE IDEs that help in developing and packaging the application.

Page 34: Servlet Introduction

Deploying• Most of the application servers support hot

deployment.

• Most of the application servers support start and stop of applications that are deployed.

Page 35: Servlet Introduction

Packaging and deploying the servlet

Web Application 1

Servlets

JSPs/HTML

Java Classes

Deployment Descriptor(web.xml)

Web Application 2

Servlets

JSPs/HTML

Java Classes

Deployment Descriptor(web.xml)

Components forming the web application.

xxx.war

Page 36: Servlet Introduction

Steps for packaging• Create a folder.

Let us name the folder as slide1ex1.• Place htmls and jsps in folder

Place the index.html inside slide1ex1• Create a folder called WEB-INF.

Created! Note the case is important here.• Place web.xml inside the folder

Placed!• Create a folder called classes inside WEB-INF

and all the java classes created inside it.Created and placed GreetingServlet.class.

Page 37: Servlet Introduction

Deployment

• As per j2ee specification, a jar file should be created with the extension .war. This war file has to be then deployed depending on the application server.

• Jar Command to create war• path/simple:> jar –cvf simple.war *.*

• For tomcat, just copy the simple folder into the folder called webapps.

Page 38: Servlet Introduction

Deployment

• Start the tomcat server.

• Type in the following url in the address bar• http://localhost:8080/slide1ex1 /index.html

• Or simply • http://localhost:8080/slide1ex1

Server nameDefault protocol where tomcat runsprotocol

Folder name

Page 39: Servlet Introduction

According to j2ee specs, war file has to

be created. For tomcat we don’t do

so. So, does this mean that tomcat does not strictly

follow j2ee specs?

Tomcat follows j2ee specs! It just gives you a simple way to deploy your

application. Another option to

deploy would be to place the war file in the webapps

folder!

Page 40: Servlet Introduction

Request and Response hierarchy

HttpServletResponse

ServletResponse

HttpServletRequest

ServletRequest

Page 41: Servlet Introduction

ServletRequest

• BufferedReader getReader()• ServletInputStream getInputStream()

• int getContentLength()• Enumeration getParameterNames()• String getParameter(String name)• String[] getParameterValues(String name)

Example ahead

Allows you to read raw bytes or characters from the stream

Page 42: Servlet Introduction

HttpServletRequest Interface

• String getMethod()• String getHeader(String name)• Enumeration getHeaderNames()• String getQueryString()• Cookies[] getCookies()• HttpSession getSession()

HTTP protocol specific methods

Later

Page 43: Servlet Introduction

ServletResponse Interface

• void setContentType(String type)• void setContentLength(int len)• ServletOutputStream getOutputStream()

• PrintWriter getWriter()

Allows us to write into the response stream

We have seen this !

Page 44: Servlet Introduction

HttpServletResponse Interface

• void addCookies(Cookie c)• String addHeader(String name,String value)

• void sendRedirect(String url)• void sendError(int ecode)

Page 45: Servlet Introduction

Getting single parameters

In the doGet() method we can get the value entered by the user in the html form using:String booktitle= request.getParameter(“name”);

…<h1>Locate Books</h1><form action=“book.do”><input type=“text” name=“name”><input type=“submit”></form>…

Default is GET

book.war

Page 46: Servlet Introduction

Question?

• What will happen if your form has a post method, and the servlet that the form calls has only doGet() method?

Page 47: Servlet Introduction

Getting multiple parameters…<form method="POST" action="display.do"><p>Select Colors:<br><input type="checkbox" name="color" value="Red">Red<br> <input type="checkbox" name="color" value="Green"> Green<br> <input type="checkbox" name="color" value="Blue">Blue</p><p><input type="submit" value="Submit" name="B1"><input type="reset" value="Reset" name="B2"></p></form>…

Page 48: Servlet Introduction

Servlet to get multiple parampublic class Colors extends javax.servlet.http.HttpServlet{public void doPost(javax.servlet.http.HttpServletRequest req,javax.servlet.http.HttpServletResponse res) throws java.io.IOException,

javax.servlet.ServletException{java.io.PrintWriter out=res.getWriter();out.println("<html>");

Page 49: Servlet Introduction

String colors[]=req.getParameterValues("color");out.println("<body>");for(int i=0;i<colors.length;i++)out.println("<font color='"+ colors[i]+"'>Hello </font><br>" );out.println("</body></html>");}}

greet.war

Page 50: Servlet Introduction

Question?

What happens if you don’t select

any of the checkboxes?

Page 51: Servlet Introduction

Servlet variable initialization• Initialization of servlet variables is generally

done in init() method.• In the normal class, initialization happens in the

constructor. But since the container calls the constructor in this case, having parameterized constructor has no meaning.

• The initialization values are passed to servlet through DD and are available only from init() method onwards.

• Therefore, the initialization is done in init() method.

Generally one never writes a constructor for a servlet!!

Page 52: Servlet Introduction

SingleThreadModel Interface• In the servlet model that we have seen so far, a

single servlet processes multiple requests simultaneously.

• This means that the doGet and doPost methods must be careful to synchronize access to fields and other shared data, since multiple threads may be trying to access the data simultaneously.

• On the other hand, you can have your servlet implement the SingleThreadModel interface, as below.

• public class YourServlet extends HttpServlet implements SingleThreadModel {...}

And say goodbye to Scalability


Recommended