+ All Categories
Home > Documents > Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write...

Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write...

Date post: 04-Aug-2018
Category:
Upload: nguyenphuc
View: 220 times
Download: 0 times
Share this document with a friend
141
Servlet And JSP Mr. Nilesh Vishwasrao Patil, Government Polytechnic, Ahmednagar Mr. Nilesh Vishwasrao Patil
Transcript
Page 1: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Servlet And JSP

Mr. Nilesh Vishwasrao Patil,

Government Polytechnic, Ahmednagar

Mr. Nilesh Vishwasrao Patil

Page 2: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet : Introduction

Specific Objectives:

To write web based applications using servlets,

JSP and Java Beans.

To write servlet for cookies and session tracking.

Page 3: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Web and Web Application

Web consists of billions of clients and server connected through wires and wireless networks.

The web clients make requests to web server. The web server receives the request, finds the resources and return the response to the client.

Page 4: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Web Application

A web application is an application accessible from the web.

A Web application is a web site with dynamic functionality on the server. Google, Facebook, Twitter are examples of web applications.

A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML.

The web components typically execute in Web Server and respond to HTTP request.

Page 5: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HTTP

HTTP is a protocol that clients and servers use on the web to communicate.

It is similar to other internet protocols such as SMTP(Simple Mail Transfer Protocol) and FTP(File Transfer Protocol) but there is one fundamental difference.

HTTP is a stateless protocol.

The client sends an HTTP request and the server answers with an HTML page to the client, using HTTP.

Page 6: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HTTP

Page 7: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HTTP methods Method Name Description

OPTIONS Request for communication options that are available on the request/response chain.

GET Request to retrieve information from server using a given URI.

HEAD Identical to GET except that it does not return a message-body, only the headers and status line.

POST Request for server to accept the entity enclosed in the body of HTTP method.

DELETE Request for the Server to delete the resource.

CONNECT Reserved for use with a proxy that can switch to being a tunnel.

PUT This is same as POST, but POST is used to create, PUT can be used to create as well as update. It replaces all current representations of the target resource with the uploaded content.

Page 8: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HTTP methods

GET Request POST Request

Data is sent in header to the server Data is sent in the request body

Get request can send only limited amount of data

Large amount of data can be sent.

Get request is not secured because data is exposed in URL

Post request is secured because data is not exposed in URL.

Get request can be bookmarked and is more efficient.

Post request cannot be bookmarked.

Page 9: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Anatomy of HTTP GET Request

Get request contains path to server and the parameters added to it.

Page 10: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Anatomy of HTTP POST Request

Post requests are used to make more complex requests on the server. For instance, if a user has filled a form with multiple fields and the application wants to save all the form data to the database. Then the form data will be sent to the server in POST request body, which is also known as Message body.

Page 11: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet : Introduction

Servlet technology is used to create web application (resides at server side and generates dynamic web page).

Servlet is Java program which run on web server and responding to request of clients (Web browser).

Servlet technology is robust and scalable because of java language.

Page 12: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet

Web applications are helper applications that resides at web server and build dynamic web pages. A dynamic page could be anything like a page that randomly chooses picture to display or even a page that displays the current time.

Page 13: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet : Defined in many ways

Servlet is a technology i.e. used to create web application.

Servlet is an API that provides many interfaces and classes including documentations.

Servlet is an interface that must be implemented for creating any servlet.

Servlet is a class that extend the capabilities of the servers and respond to the incoming request. It can respond to any type of requests.

Servlet is a web component that is deployed on the server to create dynamic web page.

Page 14: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet : Defined

Page 15: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

CGI(Common Gateway Interface)

CGI(Common Gateway Interface) programming was used to create web applications.

Here's how a CGI program works :

User clicks a link that has URL to a dynamic page instead of a static page.

The URL decides which CGI program to execute.

Web Servers run the CGI program in seperate OS shell. The shell includes OS enviroment and the process to execute code of the CGI program.

The CGI response is sent back to the Web Server, which wraps the response in an HTTP response and send it back to the web browser.

Page 16: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

CGI(Common Gateway Interface)

Page 17: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

CGI(Common Gateway Interface)

For each request, it starts a new process.

Disadvantages:

If number of clients increases, it takes more time for sending response.

For each request, it starts a process and Web server is limited to start processes.

It uses platform dependent language e.g. C, C++, perl.

High response time because CGI programs execute in their own OS shell.

CGI is not scalable.

CGI programs are not always secure or object-oriented.

It is Platform dependent.

Page 18: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Contrast of process vs. thread

Process

Takes more time to create

More secure

More fault tolerant

Thread Takes less time to

create

Offers multiple threads of execution

Share information with other threads

Less secure

More vulnerable to crashes

Page 19: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet: Advantages over CGI

Page 20: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet: Advantages over CGI

Less response time because each request runs in a separate thread.

Servlets are scalable.

Servlets are robust and object oriented.

Servlets are platform independent.

Page 21: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Terminologies

HTTP: Http is the protocol that allows web servers and browsers to

exchange data over the web.

It is a request response protocol.

Http uses reliable TCP connections by default on TCP port 80.

It is stateless means each request is considered as the new request. In other words, server doesn't recognize the user by default.

Page 22: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet

A Java Servlet is a Java object that responds to HTTP requests. It runs inside a Servlet container.

Page 23: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet A Servlet is part of a Java web application.

A Servlet container may run multiple web applications at the same time, each having multiple servlets running inside.

Page 24: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet

A Java web application can contain other components than servlets.

It can also contain Java Server Pages (JSP), images, text files, documents, Web Services etc.

Page 25: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HTTP Request and Response The browser sends an HTTP request to the Java web

server.

The web server checks if the request is for a servlet. If it is, the servlet container is passed the request.

The servlet container will then find out which servlet the request is for, and activate that servlet.

The servlet is activated by calling the Servlet.service()method.

Once the servlet has been activated via the service() method the servlet processes the request, and generates a response. The response is then sent back to the browser.

Page 26: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Containers

Java servlet containers are usually running inside a Java web server.

Example: Tomcat, GlasssFish, Jboss etc.

Container:

It provides runtime environment for JavaEE (j2ee) applications.

It performs many operations that are given below:

Life Cycle Management

Multithreaded support

Security etc.

Page 27: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Server

Server:

It is a running program or software that provides services.

Two types

Web Server: Web server contains only web or servlet container. It can be used for servlet,

jsp, struts, jsf etc. It can't be used for EJB.

Example of Web Servers are: Apache Tomcat and Resin.

Application Server: Application server contains Web and EJB containers. It can be used for

servlet, jsp, struts, jsf, ejb etc.

Ex: Jboss, Glassfish, Weblogic, Websphere

Page 28: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Content Type

Content Type:

Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.

It is a HTTP header that provides the description about what are you sending to the browser.

text/html

text/plain

application/msword

application/vnd.ms-excel

application/jar

application/pdf

application/octet-stream

application/x-zip

images/jpeg

video/quicktime

Page 29: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Types of Servlet

Generic Servlet:

It is in javax.servlet.GenericServlet package

It is protocol independent.

HTTP Servlet

It is in javax.servlet.HTTPServlet package

Built-in HTTP protocol support.

Page 30: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Types of Servlet

Generic Servlet HTTP Servlet

Package: javax.servlet Package: javax.servlet.http

It is protocol independent servlet It is protocol dependent specifically only HTTP protocol request-response handle.

It uses service() method for handling request-response.

It uses methods like doPost(), doGet()

Page 31: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet life cycle

Managed by :____________.

Each servlet instance is loaded once.

Each execution happens in a separate thread

Three methods:

init() : call only once to initialize servlet.

service() : Call for every request.

destroy() : call only once

Method service() is invoked every time a request comes it. It spawns off threads to perform doGet or doPost based on the method invoked.

Page 32: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet life cycle

1. Load Servlet Class.

2. Create Instance of Servlet.

3. Call the servlets init() method.

4. Call the servlets service() method.

5. Call the servlets destroy() method.

Note: Step 1,2,3 executed only once when servlet is initially loaded. By default servlet is not loaded until first request is received for it.

Step 4 executed „N‟-times whenever http request comes

Step 5 executed to destroy servlet means unload servlet class

Page 33: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet life cycle

Page 34: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet life cycle

Page 35: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet API

Servlet API consists of two important packages that encapsulates all the important classes and interface, namely :

javax.servlet

javax.servlet.http

javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet API.

Page 36: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Interface: javax.servlet

Interfaces Description

Servlet Declare life cycle methods for servlet. To implement this interface we have to extends GenericServlet or HttpServlet classes.

ServletConfig Helps servlet to get initialization parameter means startup information, basic information about servlet.

ServletContext Allows servlet to log events and access information about their environment

ServletRequest Used to read data from client

ServletResponse Used to sent data to client

Page 37: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Classes: javax.servlet

Classes Description

GenericServlet Used to create servlet (Protocol independent)

ServletInputStream Provides an input stream for reading requests from client.

ServletOutputStream This class supports an output stream for writing responses to a client

ServletException For handling exception: Error Occurred

UnavailableException For handling exception: generate when servlet not available

Page 38: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Interface: javax.servlet.http

Classes Description

HttpServlet Used to create http servlet (Protocol dependent)

HttpServletRequest It enables servlets to read data from an HTTP request

HttpServletResponse It enables servlets to write data to an HTTP response

HttpSession It allows to read and write session data.

Cookie Cookie class allows state information to be stored on a client machine

Page 39: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Interface: Methods

Page 40: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

GenericServlet class

It implements Servlet, ServletConfig and Serializable interfaces.

It provides the implementation of all the methods of these interfaces except the service method(You have to write code in your servlet class for this method).

GenericServlet class can handle any type of request so it is protocol-independent.

Page 41: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletConfig interface

Object of ServletConfig created by the web container for each servlet.

This object can be used to get configuration information from web.xml file.

Advantage: No need to edit the servlet file if information is modified from the web.xml file.

Page 42: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletConfig interface

public String getInitParameter(String name):Returns the parameter value for the specified parameter name.

public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names.

public String getServletName():Returns the name of the servlet.

public ServletContext getServletContext():Returns an object of ServletContext.

Page 43: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletConfig interface

Page 44: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletContext interface

An object of ServletContext is created by the web container at time of deploying the project (web application).

This object can be used to get configuration information from web.xml file.

There is only one ServletContext object per web application.

Page 45: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletContext interface

If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param> element.

Usage: The object of ServletContext provides an interface between the

container and servlet.

The ServletContext object can be used to get configuration information from the web.xml file.

The ServletContext object can be used to set, get or remove attribute from the web.xml file.

The ServletContext object can be used to provide inter-application communication.

Page 46: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletContext interface

<context-param>

<param-name>dname</param-name>

<param-value> sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</context-param>

Page 47: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletContext interface

Page 48: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

ServletConfig Vs ServletContext

Config Context

One object per servlet Object is global to entire web application

Object is created when servlet class is loaded

Object is created when web application deployed

It destroy when servlet is destroyed or upload the class.

It will destroyed when web application is un-deployed or removed.

Config object is public to particular servlet only.

It can share information between the servlet

Page 49: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpServlet

It extends GenericServlet class and implements Servlet, ServletConfig and Serializable interface.

It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Page 50: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpServlet

Page 51: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implementation

A Java Servlet is just an ordinary Java class which implements the interface

javax.servlet.Servlet;

The easiest way to implement this interface is to extend either the class GenericServlet or HttpServlet.

Page 52: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Example

Page 53: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implementation

When an HTTP request arrives at the web server, targeted for your Servlet, the web server calls your Servlet's service() method.

The service() method then reads the request, and generates a response which is sent back to the client (e.g. a browser).

Page 54: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implementation:HTTP

The javax.servlet.http.HttpServlet class is a slightly more advanced base class than the GenericServlet

The HttpServlet class reads the HTTP request, and determines if the request is an HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding method.

Page 55: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implementation: HTTP

Page 56: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpRequest: Interface

This interface present in javax.servlet.http.HttpRequest

The purpose of the HttpRequest object is to represent the HTTP request a browser sends to your web application.

Page 57: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpRequest: Parameters

Thus, anything the browser may send, is accessible via the HttpRequest.

We can read initialization parameters also using HttpServletRequest object with getInitParameter method.

Page 58: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpRequest: Parameters

Also we can use same (following) code if request parameters is send through body part of the Http request.

If the browser sends an HTTP GET request, the parameters are included in the query string in the URL.

If the browser sends an HTTP POST request, the parameters are included in the body part of the HTTP request.

Page 59: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpRequest: Header

The request headers are name, value pairs sent by the browser along with the HTTP request.

The request headers contain information about e.g. what browser software is being used, what file types the browser is capable of receiving etc. In short, at lot of meta data around the HTTP request.

Above example reads the Content-Length header sent by the browser.

Page 60: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpRequest: InputStream If the browser sends an HTTP POST request, request

parameters and other potential data is sent to the server in the HTTP request body.

If does not have sent data in parameters means may be binary data, that time we will require InputStream for accessing request body come from client.

InputStream requestBodyInput = request.getInputStream();

NOTE: You will have to call this method before calling any getParameter() method.

Page 61: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpRequest: Session

It is possible to obtain the session object from the HttpRequest object too.

The session object can hold information about a given user, between requests.

So, if you set an object into the session object during one request, it will be available for you to read during any subsequent requests within the same session time scope.

Page 62: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpResponse: Interface

This interface is present in java.servlet.http package.

The purpose of the HttpResponse object is to represent the HTTP response of web application sends back to the browser.

Page 63: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpResponse: Writing HTML

To send HTML back to the browser, you have to obtain the a PrintWriter from the HttpResponse object.

Page 64: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpResponse: Headers Headers must be set before any data is written to the response.

Examples:

Syntax: response.setHeader("Header-Name", "Header Value");

Set Content type: response.setHeader("Content-Type", "text/html");

Writing text

response.setHeader("Content-Type", "text/plain");

PrintWriter writer = response.getWriter();

writer.write("This is just plain text");

Content-length response.setHeader("Content-Length", "31642");

Page 65: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpResponse: Writing Binary Data

We can also write binary data back to the browser instead of text.

For instance, we can send an image back, a PDF file or a Flash file or something like that.

First we have to set content type. And need to use following code:

OutputStream outputStream = response.getOutputStream(); outputStream.write(...);

Page 66: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpResponse: Redirecting

We can redirect the browser to a different URL from your servlet.

You cannot send any data back to the browser when redirecting

response.sendRedirect("http://www.google.com");

Or Another servlet file call

response.sendRedirect(“HelloServlet");

Page 67: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpSession

The HttpSession object represents a user session.

A user session contains information about the user across multiple HTTP requests.

When a user enters your site for the first time, the user is given a unique ID to identify his session by.

This ID is typically stored in a cookie or in a request parameter.

Page 68: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpSession

We can store values in the session object, and retrieve them later. Do it in following way:

session.setAttribute("userName", "theUserName");

This code sets an attribute named "userName", with the value "theUserName".

To read the value again:

String userName = (String) session.getAttribute("userName");

Values stored in the session object are stored in the memory of the servlet container.

Page 69: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpSession: In Clusters

If we have an architecture with 2 web servers in a cluster, keep in mind that values stored in the session object of one server, may not be available in the session object on the other server.

The solution to this problem would be one of:

Do not use session attributes.

Use a session database, into which session attributes are written, and from which it is read.

Use sticky session, where a user is always sent to the same server, throughout the whole session.

Page 70: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

HttpSession: Example

Create one HTML file: index.html which send user name and password to the servlet file.

Create two servlet file, one will save user name into session and that session information is send to another servlet. This example will shows the session tracking.

Page 71: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

RequestDispatcher

The RequestDispatcher class enables your servlet to "call" another servlet from inside another servlet.

We can obtain a RequestDispatcher from the HttpServletRequest object.

The above code obtains a RequestDispatcher targeted at whatever Servlet (or JSP) that is mapped to the URL /anotherUrl.simple.

Page 72: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

RequestDispatcher

You can call the RequestDispatcher using either its include() or forward() method.

The forward() method intended for use in forwarding the request, meaning after the response of the calling servlet has been committed. You cannot merge response output using this method.

The include() method merges the response written by the calling servlet, and the activated servlet. This way you can achieve "server side includes" using the include().

Page 73: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet: Load on start up

The <servlet> element has a sub-element called

<load-on-startup> which you can use to control when the servlet container should load the servlet.

If you do not specify a <load-on-startup> element, the servlet container will typically load your servlet when the first request arrives for it.

By setting a <load-on-startup> element, you can tell the servlet container to load the servlet as soon as the servlet container starts.

Remember, the servlets init() method is called when the servlet is loaded.

<load-on-startup>1</load-on-startup>

Page 74: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie

HTTP Cookies are little pieces of data that a web application can store on the client machine of users visiting the web application.

Typically up to 4 kilo bytes(KB) of data can be store.

We can write cookies using HttpServletResponse object:

Example:

Cookie cookie = new Cookie("myCookie", "myCookieValue");

response.addCookie(cookie);

Page 75: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie

By default, each request is considered as a new request.

In cookies technique, we add cookie with response from the servlet.

So cookie is stored in the cache of the browser.

After that if request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Page 76: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Types

Non-persistent cookie:

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie:

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or sign-out or clear cookies/cache memory of browsers.

Page 77: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Pros/Cons

Advantages:

Simplest technique of maintaining the state.

Cookies are maintained at client side.

Disadvantages

It will not work if cookie is disabled from the browser.

Only textual information can be set in Cookie object.

Page 78: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Constructor

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.

Constructor Description

Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Page 79: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Methods

Useful methods:

Method Description

public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Page 80: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Methods

Other methods:

public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object.

public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

Page 81: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: How to create?

Creating cookie object

Cookie ck=new Cookie("user",”Sandip");

Adding cookie in the response

response.addCookie(ck);//

Page 82: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: For delete Cookies

Deleting value of cookie

Cookie ck=new Cookie("user","");

Changing the maximum age to 0 seconds

ck.setMaxAge(0);

Adding cookie in the response

response.addCookie(ck);

Page 83: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: To get Cookies

Cookie ck[]=request.getCookies();

for(int i=0;i<ck.length;i++)

{

out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());

//printing name and value of cookie

}

Page 84: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Example

Page 85: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Cookie: Example

1. Create one Html file which send user name to first servlet.

First servlet file set cookies of that user name and call second servlet file.

Second servlet file retrieve name of user from cookies instead of from session.

Page 86: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Filter

A filter is an object that is invoked at the preprocessing and post processing of a request.

It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.

The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml file, filter will be removed automatically and we don't need to change the servlet.

Page 87: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Filter

Usage of Filter:

recording all incoming requests

logs the IP addresses of the computers from which the requests originate

conversion

data compression

encryption and decryption

input validation etc

Page 88: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Filter

Advantages

Filter is pluggable.

One filter don't have dependency onto another resource.

Less Maintenance.

Page 89: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Servlet Filter

Three interfaces of Filter API: present in javax.servlet package Filter

FilterChain

FilterConfig

Filter tag is used in web.xml file

Page 90: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Applet Servlet Communication

URLConnection class is used.

Page 91: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

Which is of the following are classes and which are interfaces?

1. Servlet

2. ServletConfig

3. ServletRequest

4. ServletResponse

5. HttpServlet

6. GenericServlet

7. Cookies

8. Session

Page 92: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

What is returntype of the getSession() method?

1. Session

2. int

3. HttpSession

4. boolean

5. void

Page 93: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

Javax.servlet packages does not have:

1. HttpServlet

2. ServletConfig

3. ServletContext

4. Servlet

5. HttpServletRequest

6. ServletResponse

7. HttpServletResponse

8. Cookies

Page 94: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

Javax.servlet packages does not have:

1. HttpServlet

2. ServletConfig

3. ServletContext

4. Servlet

5. HttpServletRequest

6. ServletResponse

7. HttpServletResponse

8. Cookies

Page 95: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

Which is correct package for HttpServlet and HttpServletResponse?

1. javax.servlet.*;

2. javax.servlet.http.*;

3. javax.servlet.httpservlet.*;

4. java.lang.*;

Page 96: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

Which of the following method is invoked when Http post request?

1. doPost()

2. doPostCall()

3. doHttpPost()

4. doPut()

5. doTrace()

6. doPostOptions()

Page 97: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

MCQ

Which of the following method is invoked when Http post request?

1. doPost()

2. doPostCall()

3. doHttpPost()

4. doPut()

5. doTrace()

6. doPostOptions()

Page 98: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP (Java Server Pages)

Java Server Pages (JSP) is a server-side programming technology.

It enables the creation of dynamic, platform-independent method for building Web-based applications.

JSP have access to the entire family of Java APIs, including the JDBC API to access enterprise databases.

Page 99: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP (Java Server Pages)

JSP technology is used to create web application just like Servlet technology.

It can be thought of as an extension to servlet because it provides more functionality than servlet.

A JSP page consists of HTML tags and JSP tags.

The jsp pages are easier to maintain than servlet because we can separate designing and development.

It provides some additional features such as Expression Language, Custom Tag etc.

Page 100: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP (Java Server Pages)

JSP is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>

A JSP component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application.

Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically

Page 101: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Advantages of JSP over Servlet

Extension to Servlet:

JSP technology is the extension to servlet technology.

We can use all the features of servlet in JSP.

In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP, that makes JSP development easy.

Page 102: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Advantages of JSP over Servlet

Easy to maintain:

JSP can be easily managed because we can easily separate our business logic with presentation logic.

In servlet technology, we mix our business logic with the presentation logic.

Page 103: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Advantages of JSP over Servlet

Fast Development: No need to recompile and redeploy:

If JSP page is modified, we don't need to recompile and redeploy the project.

The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.

Page 104: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Lifecycle

Translation of JSP Page

Compilation of JSP Page

Class loading (class file is loaded by the class loader)

Instantiation (Object of the Generated Servlet is created).

Initialization ( jspInit() method is invoked by the container).

Reqeust processing ( _jspService() method is invoked by the container).

Destroy ( jspDestroy() method is invoked by the container).

Page 105: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Lifecycle

A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet.

Compilation

Initialization

Execution

Cleanup

Page 106: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Lifecycle

Page 107: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Lifecycle

JSP Compilation: Involves three steps

Parsing the JSP.

Turning the JSP into a servlet.

Compiling the servlet.

JSP Initialization:

public void jspInit(){ // Initialization code... }

JSP Execution:

void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... }

JSP Cleanup:

public void jspDestroy() { // Your cleanup code goes here. }

Page 108: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Working

Page 109: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Working

Page 110: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Scriptlet

1. Java server pages are required to store in …………..(web-apps/root)

2. Does tomcat server required to restart to see updated JSP page…….. (YES/NO)

Page 111: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Scriptlet

A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.

Syntax

<% code fragment %>

Also can be write

<jsp:scriptlet> code fragment </jsp:scriptlet>

Page 112: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Hello World or First JSP Program

Create Dynamic web project in eclipse.

Create one index.jsp file in WebContent folder.

Write code in <% out.print(2*4); %>

Run Project on Tomcat server.

Page 113: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Declarations

A declaration declares one or more variables or methods that you can use in Java code later in the JSP file.

You must declare the variable or method before you use it in the JSP file.

Syntax:

<%! declaration; [ declaration; ]+ ... %>

Or:

<jsp:declaration> code fragment </jsp:declaration>

Ex:

<%! int i = 0; %> <%! int a, b, c; %>

<%! Circle a = new Circle(2.0); %>

Page 114: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Scriptlet and Declaration

Jsp Scriptlet Tag Jsp Declaration Tag

The jsp scriptlet tag can only declare variables not methods.

The jsp declaration tag can declare variables as well as methods.

The declaration of scriptlet tag is placed inside the _jspService() method.

The declaration of jsp declaration tag is placed outside the _jspService() method.

Page 115: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Expressions

The code placed within JSP expression tag is written to the output stream of the response.

So we need not write out.print() to write data. It is mainly used to print the values of variable or method.

Page 116: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Expressions

Syntax:

<%= expression %>

Or:

<jsp:expression> expression </jsp:expression>

Ex:

<p> Today's date: <%= (new java.util.Date()).toLocaleString()%></p>

<%= "welcome to jsp" %>

Current Time: <%= java.util.Calendar.getInstance().getTime() %>

Page 117: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Expressions: Example

<html> <body> <%! int cube(int n){ return n*n*n*; } %> <%= "Cube of 3 is:"+cube(3) %> </body> </html>

Page 118: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Expressions: Example

<html> <html> <body> <%! int data=50; %> <%= "Value of the variable is:"+data %> </body> </html>

Page 119: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects/Pre-defined Variables

There are 9 jsp implicit objects.

These objects are created by the web container that are available to all the jsp pages.

No need to create these objects or declared. It will automatically access in each page of jsp.

Page 120: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable

Page 121: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: out

For writing any data to the buffer, JSP provides an implicit object named out.

In case of servlet you need to write:

PrintWriter out=response.getWriter();

But in JSP, we don't need to write this code.

Ex:

<% out.print(“Hello World”); %>

Page 122: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: request

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the web container.

It can be used to get request information such as parameter, header information, remote address, server name, server port, content type, character encoding etc.

Ex: <% String name=request.getParameter("uname");

out.print("welcome "+name); %>

Page 123: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: response

response is an implicit object of type HttpServletResponse.

The instance of HttpServletResponse is created by the web container for each jsp request.

Ex: <% response.sendRedirect("http://www.google.com"); %>

Page 124: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: config

config is an implicit object of type ServletConfig.

This object can be used to get initialization parameter for a particular JSP page.

The config object is created by the web container for each jsp page.

Generally, it is used to get initialization parameter from the web.xml file

Ex: <% String driver=config.getInitParameter("dname"); %>

Page 125: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: application

application is an implicit object of type ServletContext.

The instance of ServletContext is created only once by the web container when application or project is deployed on the server.

This object can be used to get initialization parameter from configuaration file (web.xml).

Ex: <% String driver=application.getInitParameter("dname"); %>

Page 126: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: session

session is an implicit object of type HttpSession.

The Java developer can use this object to set and get attribute or to get session information.

Ex: Suppose index.html which call welcome.jsp by sending user name.

<html> <body> <form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body> </html>

Page 127: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: session

Wecome.jsp read user name from request parameter, set session and call another jsp.

<html> <body> <% String name=request.getParameter("uname"); out.print("Welcome "+name); session.setAttribute("user",name); <a href="second.jsp">second jsp page</a> %> </body> </html>

Page 128: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

Implicit Objects: session

Second jsp page, will get information from session and identify user.

<html> <body> <% String name=(String)session.getAttribute("user"); out.print("Hello "+name); %> </body> </html>

Page 129: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives

The jsp directives are messages that tells the web container how to translate a JSP page into the corresponding servlet.

There are three types of directives:

page directive

include directive

taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>

Page 130: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: Page

The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP Directive

<%@ page attribute="value" %>

Page 131: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: Page

Attributes of JSP page directive import contentType extends info buffer language isELIgnored isThreadSafe autoFlush session pageEncoding errorPage isErrorPag

Page 132: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: Page import

The import attribute is used to import class, interface or all the members of a package.

It is similar to import keyword in java class or interface

Ex: <html> <body> <%@ page import="java.util.Date" %> Today is: <%= new Date() %> </body> </html

Page 133: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: Page Content type

contentType attribute defines the MIME(Multipurpose Internet Mail Extension) type of the HTTP response.

The default value is "text/html;charset=ISO-8859-1".

Ex: <html> <body> <%@ page contentType=application/msword %> Today is: <%= new java.util.Date() %> </body> </html>

Page 134: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: Page extends

The extends attribute defines the parent class that will be inherited by the generated servlet.

It is rarely used.

Ex: <%@ page extends="mypackage.SampleClass"%>

Page 135: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: Page info

This attribute simply sets the information of the JSP page which is retrieved later by using getServletInfo() method of Servlet interface.

It is rarely used.

Ex: <html> <body> <%@ page info="composed by Sonoo Jaiswal" %> Today is: <%= new java.util.Date() %> </body> </html>

Page 136: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: session

For setting session: true/false

By-default: true

Ex: <%@ page session="true"%> Or <%@ page session="false"%>

Page 137: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: include

The include directive is used to include the contents of any resource it may be jsp file, html file or text file.

The include directive includes the original content of the included resource at page translation time.

Advantage: code reusability.

Syntax:

<%@ include file="resourceName" %>

Ex: <html><body> <%@ include file="header.html" %> Today is: <%= java.util.Calendar.getInstance().getTime() %> </body></html>

Page 138: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP Directives: taglib

JSP taglib directive is used to define a tag library that defines many tags.

We use the TLD (Tag Library Descriptor) file to define the tags.

Syntax:

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Ex: In this example, we are using our tag named currentDate. To use this tag we must specify the taglib directive so the container may get information about the tag.

<html><body> <%@ taglib uri="http://www.msbte.com/tags" prefix="mytag" %> <mytag:currentDate/> </body></html>

Page 139: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JSP API

Two packages:

javax.servlet.jsp

javax.servlet.jsp.tagext

javax.servlet.jsp: It has two interfaces and many classes Interfaces:

JspPage

HttpJspPage

Classes

JspWriter

PageContext

JspFactory

JspEngineInfo

JspException

JspError

Page 140: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JspPage & HttpJspPage Interface

Page 141: Servlet And JSP · Mr. Nilesh Vishwasrao Patil Servlet : Introduction Specific Objectives: To write web based applications using servlets, JSP and Java Beans. To …

Mr. Nilesh Vishwasrao Patil

JspPage & HttpJspPage Interface

JspPage Interface:

According to the JSP specification, all the generated servlet classes must implement the JspPage interface.

It extends the Servlet interface. It provides two life cycle methods.

public void jspInit():

public void jspDestroy()

HttpJspPage Interface:

The HttpJspPage interface provides the one life cycle method of JSP.

It extends the JspPage interface.

public void _jspService()


Recommended