Servlet And JSP
Mr. Nilesh Vishwasrao Patil,
Government Polytechnic, Ahmednagar
Mr. Nilesh Vishwasrao Patil
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.
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.
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.
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.
Mr. Nilesh Vishwasrao Patil
HTTP
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.
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.
Mr. Nilesh Vishwasrao Patil
Anatomy of HTTP GET Request
Get request contains path to server and the parameters added to it.
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.
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.
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.
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.
Mr. Nilesh Vishwasrao Patil
Servlet : Defined
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.
Mr. Nilesh Vishwasrao Patil
CGI(Common Gateway Interface)
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.
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
Mr. Nilesh Vishwasrao Patil
Servlet: Advantages over CGI
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.
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.
Mr. Nilesh Vishwasrao Patil
Servlet
A Java Servlet is a Java object that responds to HTTP requests. It runs inside a Servlet container.
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.
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.
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.
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.
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
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
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.
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()
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.
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
Mr. Nilesh Vishwasrao Patil
Servlet life cycle
Mr. Nilesh Vishwasrao Patil
Servlet life cycle
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.
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
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
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
Mr. Nilesh Vishwasrao Patil
Servlet Interface: Methods
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.
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.
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.
Mr. Nilesh Vishwasrao Patil
ServletConfig interface
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.
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.
Mr. Nilesh Vishwasrao Patil
ServletContext interface
<context-param>
<param-name>dname</param-name>
<param-value> sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
Mr. Nilesh Vishwasrao Patil
ServletContext interface
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
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.
Mr. Nilesh Vishwasrao Patil
HttpServlet
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.
Mr. Nilesh Vishwasrao Patil
Example
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).
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.
Mr. Nilesh Vishwasrao Patil
Implementation: HTTP
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.
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.
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.
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.
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.
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.
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.
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.
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");
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(...);
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");
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.
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.
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.
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.
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.
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().
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>
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);
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.
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.
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.
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.
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.
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.
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);//
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);
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
}
Mr. Nilesh Vishwasrao Patil
Cookie: Example
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.
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.
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
Mr. Nilesh Vishwasrao Patil
Servlet Filter
Advantages
Filter is pluggable.
One filter don't have dependency onto another resource.
Less Maintenance.
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
Mr. Nilesh Vishwasrao Patil
Applet Servlet Communication
URLConnection class is used.
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
Mr. Nilesh Vishwasrao Patil
MCQ
What is returntype of the getSession() method?
1. Session
2. int
3. HttpSession
4. boolean
5. void
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
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
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.*;
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()
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()
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.
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.
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
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.
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.
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.
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).
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
Mr. Nilesh Vishwasrao Patil
JSP Lifecycle
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. }
Mr. Nilesh Vishwasrao Patil
JSP Working
Mr. Nilesh Vishwasrao Patil
JSP Working
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)
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>
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.
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); %>
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.
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.
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() %>
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>
Mr. Nilesh Vishwasrao Patil
JSP Expressions: Example
<html> <html> <body> <%! int data=50; %> <%= "Value of the variable is:"+data %> </body> </html>
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.
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
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”); %>
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); %>
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"); %>
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"); %>
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"); %>
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>
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>
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>
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" %>
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" %>
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
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
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>
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"%>
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>
Mr. Nilesh Vishwasrao Patil
JSP Directives: session
For setting session: true/false
By-default: true
Ex: <%@ page session="true"%> Or <%@ page session="false"%>
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>
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>
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
Mr. Nilesh Vishwasrao Patil
JspPage & HttpJspPage Interface
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()