Unit - 4 JSP AND SERVLET
Unit - 4 JSP AND SERVLET
Unit-4
Introducing Servlets
1 Background
2 The Life Cycle of a Servlet
Servlet Development Options
Using Tomcat
3 A Simple Servlet
3.a Create and Compile the Servlet Source Code
3.b Start Tomcat
3.c Start a Web Browser and Request the Servlet
4 The Servlet API
5 The javax.servlet Package
A The Servlet Interface
B The ServletConfig Interface
C The ServletContext Interface
D The ServletRequest Interface
E The ServletResponse Interface
F The GenericServlet Class
G The ServletInputStream Class
H The ServletOutputStream Class
I The Servlet Exception Classes
6 Reading Servlet Parameters
7 The javax.servlet.http Package
A The HttpServletRequest Interface
B The HttpServletResponse Interface
C The HttpSession Interface
D The Cookie Class
E The HttpServlet Class
8 Handling HTTP Requests and Responses
a Handling HTTP GET Requests
b Handling HTTP POST Requests
9 Using Cookies
10 Session Tracking
11 Introduction to JSP
a Using JSP
b Comparing JSP with Servlet
c Java Web Frameworks
https://ctal-advancejava.blogspot.com/
2
Servlets are small programs that execute on the server side of a Web connection. Just as applets dynamically
extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server.
A servlet is a Java programming language class used to extend the capabilities of servers that host applications
accessed via a request-response programming model. Although servlets can respond to any type of request, they
are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet
technology defines HTTP-specific servlet classes.The javax.servlet and javax.servlet.http packages provide
interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-
cycle methods.
First, when a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP
request for this URL. This request is then sent to the appropriate server.
Second, this HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet
is dynamically retrieved and loaded into the address space of the server.
Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first loaded
into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.
Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP request. It is
possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP
response for the client. The servlet remains in the server’s address space and is available to process any other HTTP
requests received from clients. The service( ) method is called for each HTTP request.
Finally, the server may decide to unload the servlet from its memory. The server calls the destroy( ) method to
relinquish any resources such as file handles that are allocated for the servlet. Important data may be saved to a
persistent store. The memory allocated for the servlet and its objects can then be garbage collected.
Interface Description
Servlet Declares life cycle methods for a
servlet.
ServletConfig Allows servlets to get initialization
parameters.
ServletContext Enables servlets to log events and
access information about their
environment.
ServletRequest Used to read data from a client
request.
ServletResponse Used to write data to a client
response.
The following table summarizes the core classes that are provided in the javax.servlet package.
Class Description
GenericServlet Implements the Servlet and
ServletConfig interfaces.
ServletInputStream Provides an input stream for reading
requests from a client.
ServletOutputStream Provides an output stream for writing
responses to a client.
ServletException Indicates a servlet error occurred.
UnavailableException Indicates a servlet is unavailable.
Here, buffer is the array into which size bytes are placed starting at offset. The
method returns the actual number of bytes read or –1 if an end-of-stream
condition is encountered.
The ServletRequest class includes methods that allow to read the names and values of parameters that are included in
a client request. We will develop a servlet that illustrates their use. The example contains two files. A Web page is
defined in index.jsp and a servlet is defined in PostParametersServlet.java. The HTML source code for index.jsp is
shown in the following listing. It defines a table that contains two labels and two text fields. One of the labels is
Employee and the other is Phone. There is also a submit button. Notice that the action parameter of the form tag
specifies a URL. The URL identifies the servlet to process the HTTP POST request.
//index.jsp
<html>
<body>
<center>
<form name="Form1"
method="post"
action="http://localhost:8080/servlets-examples/
servlet/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>
//PostParametersServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet
extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname = (String)e.nextElement();
pw.print(pname + " = ");
String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
output
e = navin
p = 9841
The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet
developers. You will see that its functionality makes it easy to build servlets that work with HTTP requests and
responses.
The following table summarizes the core interfaces that are provided in this package:
For example, assume that a user visits an online store. A cookie can save the user’s name, address, and other
information. The user does not need to enter this data each time he or she visits the store.
A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse interface.
The data for that cookie is then included in the header of the HTTP response that is sent to the browser.
The names and values of cookies are stored on the user’s machine. Some of the information that is saved for each
Er. Sitalthe
cookie includes Pd.following:
Mandal https://ctal-advancejava.blogspot.com/
11
o The name of the cookie
o The value of the cookie
o The expiration date of the cookie
o The domain and path of the cookie
The expiration date determines when this cookie is deleted from the user’s machine. If an expiration date is not
explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in a
file on the user’s machine.
The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user enters a
URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it is not.
The methods of the Cookie class are summarized in Table below:
The HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet
developer typically overrides one of these methods. These methods are doDelete( ), doGet( ), doHead( ),
doOptions( ), doPost( ), doPut( ), and doTrace( ).
Compile the servlet. Next, copy it to the appropriate directory, and update the web.xml file. Then, perform
these steps to test this example:
1. Start Tomcat, if it is not already running.
2. Display the web page in a browser.
3. Select a color.
4. Submit the web page.
Assume that the user selects the red option and submits the form. The URL sent from the browser to the server
is The characters
Er. Sital Pd.toMandal
the right of the question mark are known as the query string.
https://ctal-advancejava.blogspot.com/
14
AddCookie.html
AddCookieServlet.java
Compile the servlets. Next, copy them to the appropriate directory, and update the web.xml file. Then, perform
these steps to test this example:
Session Tracking
A session can be created via the getSession( ) method of HttpServletRequest. An HttpSession object is
returned. This object can store a set of bindings that associate names with objects.
That object is a Date object that encapsulates the date and time when this page was last accessed. A Date object
encapsulating the current date and time is then created. The setAttribute( ) method is called to bind the name
"date" to this object.
When you first request this servlet, the browser displays one line with the current date and time information. On
subsequent invocations, two lines are displayed. The first line shows the date and time when the servlet was last
accessed. The second line shows the current date and time.
11 Introduction to JSP
• It stands for Java Server Pages.
• It is a server side technology.
• It is used for creating web application.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform independent web
pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the client’s request.
MVC In contrast to MVC we can state On the other hand, JSP plays
servlet as a controller which the role of view to render the
2
receives the request process and response returned by the
send back the response. servlet.
Request type Servlets can accept and process all JSP on the other hand is
3 type of protocol requests. compatible with HTTP request
only.
Features of JSP
• Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
• Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
• Connection to Database is easier :-It is easier to connect website to database and allows to
read or write data easily to the database.
• Make Interactive websites :- In this we can create dynamic web pages which helps user to
interact in real time environment.
• Portable, Powerful, flexible and easy to maintain :- as these are browser and server
independent.
• No Redeployment and No Re-Compilation :- It is dynamic, secure and platform
independent so no need to re-compilation.
• Extension to Servlet :- as it has all features of servlets, implicit objects and custom tags
JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offers several advantages in comparison with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having separate CGI files.
• JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
• JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
• JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class applications. This
means that JSP can play a part in the simplest applications to the most complex and demanding.
2. Java Scriplets :- It allows us to add any number of JAVA code, variables and expressions.
Syntax:-
<% java code %>
Example:-
<% num1 = num1+num2 %>
4. JAVA Comments :- It contains the text that is added for information which has to be ignored.
Syntax:-
<% -- JSP Comments %>
Process of Execution
Steps for Execution of JSP are following:-
• Create html page from where request will be sent to server eg try.html.
• To handle to request of user next is to create .jsp file Eg. new.jsp
• Create project folder structure.
• Create XML file eg my.xml.
• Create WAR file.
• Start Tomcat
• Run Application
HTML>
<BODY>
Hello BeginnersBook Readers!
Current time is: <%= new java.util.Date() %>
</BODY>
</HTML>
The directory structure of JSP page is same as Servlet. We contain the JSP page outside
the WEB-INF folder or in any directory.
2) Model2 Architecture: In this Model, Servlet plays a major role and it is responsible for processing
the client’s(web browser) request.
Java Framework is the body or platform of pre-written codes used by Java developers
to develop Java applications or web applications. In other words, Java Framework is a
collection of predefined classes and functions that is used to process input, manage
hardware devices interacts with system software. It acts like a skeleton that helps the
developer to develop an application by writing their own code.
What is a framework?
Framework are the bodies that contains the pre-written codes (classes and functions) in
which we can add our code to overcome the problem. We can also say that frameworks
use programmer's code because the framework is in control of the programmer. We can
use the framework by calling its methods, inheritance, and supplying "callbacks",
listeners, or Pd.
Er. Sital other implementations
Mandal of the Observer pattern.
https://ctal-advancejava.blogspot.com/
23
Popular Java Frameworks
o Spring
o Hibernate
o Grails
o Play
o JavaServer Faces (JSF)
o Google Web Toolkit (GWT)
o Quarkus
Spring
Advantages
o Loose coupling
o Lightweight
o Fast Development
o Powerful abstraction
o Easy to test
Hibernate
Advantages
Grails
Advantages
Play
It is a unique Java framework because it does not follow JEE standards. It follows MVC
architecture pattern. It is used when we want to develop highly scalable Java
application. Using Play framework, we can develop lightweight and web-friendly Java
application for both mobile and desktop.
Advantages
o No configuration is required.
o It enhances the developer productivity and target the RESTful architectures.
o It offers hot code reload and error message in the browser.
o It also supports popular IDEs.
JavaServer Faces
Advantages
Quarkus
Advantages
Another example of framework is, Swing and AWT classes. Swing is a GUI based
framework used to develop windows-based application. It contains a large number of
interfaces. There is inversion of control because of listeners.
Library Framework
You are in full control when you call a The code never calls into a framework,
method from a library and the control is instead the framework calls you.
then returned.
They are important in program for They provide a standard way to build and
linking and binding process. deploy applications.
Reference:
https://www3.ntu.edu.sg/home/ehchua/programming/java/JSPByExample.html
Er. Sital Pd. Mandal https://ctal-advancejava.blogspot.com/