Unit 4
Unit 4
4.1 SERVLET
INTRODUCTION
Java Servlets are programs that run on a Web or Application server and
act as a middle layer between a requests coming from a Web browser or
other HTTP client and databases or applications on the HTTP server.
Using Servlets, you can collect input from users through web page
forms, present records from a database or another source, and create web
pages dynamically.
Applet:
Applets have many restrictions over the areas of security because they
are obtained from remote machines and can harm client-side machines.
Some of them are as follows :
Example:
When you fill-up the shape and submit the shape applying, click the
submit button and it goes, what are the results from this level is CGI.
A common problem in this when a new process is created every time the
web server receives a CGI request so it results in a delay of response time.
Proprietary API:
Example:
Drawback:
Most of these are developed in C/C++ and hence can contain memory
leaks and core dumps that can crash the webserver.
Web server only supports Web application like Servlets, JSP ,HTML and
Application Server support Enterprise Edition like Servlets, JSP , HTML, EJB
(Enterprise Java Bean) , JMS (Java Message Service) and the Application
Server is Superior (Web Server + EJB + JMS). Following is a conceptual figure
which gives more regarding web server and application server. Following are
the advantages of servlet.
Advantages:
• A web developer can create fast and efficient server side program by
using servlets.
• The servlet is safe because, servlet inherits Java with all features like
memory management, exception handling, multi-threading, garbage
collection and emerged as a very powerful web server extension.
• The servlet is Robust because, they are managed by the JVM.So need
not worry about the memory leak, garbage collection.
Talking about the types of servlets, there are primarily two types,
namely:
Generic Servlets
HTTP Servlets
There are three potential ways in which we can employ to create a servlet:
Client:
Web Server
Primary job of a web server is to process the requests and responses
that a user sends over time and maintain how a web user would be able to
access the files that has been hosted over the server. The server we are
talking about here is a software which manages access to a centralized
resource or service in a network.. There are precisely two types of
webservers:
• URL mapping
Web container sits at the server-side managing and handling all the requests
that are coming in either from the servlets or from some JSP pages or
potentially any other file system.
Servlet Request :
init()
service()
destroy()
These methods are used to process the request from the user.
Following are the steps in which a request flows through a servlet which can
be observed in the architecture diagram:
• The request is accepted by the web server and forwarded to the web
container.
• In order to obtain the servlet’s address, the web container traces
web.xml file corresponding to the request URL pattern.
• By the time above process takes place, the servlet should have been
instantiated and initialized. If the servlet has not been instantiated and
initialized, init() method is invoked to serve the purpose.
• When servlet container shuts down, it unloads all the servlets and calls
destroy() method for each initialized servlets.
Advantages:
• Servlets are first converted into byte codes and then executed, which
helps in increasing the processing time.
Disadvantages:
The init method is called only once. It is called only when the servlet is
created, and not called for any user requests afterwards. So, it is used for
one-time initializations, just as with the init method of applets.
Syntax:
// Initialization code...
The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted
response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service. The service() method checks the
HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc. methods as appropriate.
// Servlet code
A POST request results from an HTML form that specifically lists POST
as the METHOD and it should be handled by doPost() method.
Syntax:
// Servlet code }
The destroy() method is called only once at the end of the life cycle of
a servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to disk,
and perform other such cleanup activities. After the destroy() method is
called, the servlet object is marked for garbage collection. The destroy
method definition looks like this.
Syntax:
// Finalization code...}
Architecture Diagram:
• First the HTTP requests coming to the server are delegated to the
servlet container.
• The servlet container loads the servlet before invoking the service()
method.
java.lang.Object
|_extended byjavax.servlet.GenericServlet
Example of GenericServlet:
I am using Eclipse IDE for this example. Create New “Dynamic Web
Project” from the Eclipse file menu.
Project structure (or you can hierarchy) would look like this, once you are
done creating all the following files in IDE.
I am using Eclipse IDE for this example. Create New “Dynamic Web Project”
from the Eclipse file menu.
Project structure (or you can hierarchy) would look like this, once you are
done creating all the following files in IDE.
dex.html
We are creating an html file that would call the servlet once we click on
the link on web page. Create this file in WebContent folder. This path of the
file should look like this: WebContent/index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Generic Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
Generic.java:
Now, we are creating a Generic Servlet by extending GenericServlet
class. When creating a GenericServlet you should always override service()
method. Right click on the src folder and create a new class file, name the
file as ExampleGeneric. The file path should look like this: Java
Resouces/src/default package/ExampleGeneric.java
import java.io.*;
import javax.servlet.*;
public class ExampleGeneric extends GenericServlet{
public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
res.setContentType("text/html");
PrintWriter pwriter=res.getWriter();
pwriter.print("<html>");
pwriter.print("<body>");
pwriter.print("<h2>Generic Servlet Example</h2>");
pwriter.print("<p>Hello BeginnersBook Readers!</p>");
pwriter.print("</body>");
pwriter.print("</html>");
}}
web.xml:
This file can be found at this path WebContent/WEB-INF/web.xml. In
this file we will map the Servlet with the specific URL. Since we are calling
welcome page upon clicking the link on index.html page so we are mapping
the welcome page to the Servlet class we created above.
<web-app>
<display-name>BeginnersBookServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyGenericServlet</servlet-name>
<servlet-class>ExampleGeneric</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyGenericServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
As you can see in the diagram below that client (user’s browser) make
requests. These requests can be of any type, for example – Get Request,
Post Request, Head Request etc. Server dispatches these requests to the
servlet’s service() method, this method dispatches these requests to the
correct handler for example if it receives Get requests it dispatches it to the
doGet() method.
java.lang.Object
|_extended byjavax.servlet.GenericServlet
|_extended byjavax.servlet.http.HttpServlet
I have already discussed in the Generic Servlet article that you should
always use HttpServlet instead of the GenericServlet. HttpServlet is easier to
work with, and has more methods to work with than GenericServlet.
Example:
I am using Eclipse IDE for this example. Create New “Dynamic Web
Project” from the Eclipse file menu.explained all the steps for creating
Servlet in Eclipse IDE, however if you are unfamiliar with Eclipse and don’t
have it installed on your system then refer this guide:How to Install Eclipse,
configure tomcat and run your First Servlet Application using Eclipse.
Project structure (or you can hierarchy) would look like this, once you
are done creating all the following files in IDE.
index.html:
Creating an html file that would call the servlet once we click on the
link on web page. Create this file in WebContent folder. The path of the file
should look like this: WebContent/index.html
index<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Http Servlet Demo</title>
</head>
<body>
<a href="welcome">Click to call Servlet</a>
</body>
</html>
Example HttpServlet.java:
Createng a Http Servlet by extending HttpServlet class. Right click on
the src folder and create a new class file, name the file as
ExampleHttpServlet. The file path should look like this: Java
Resources/src/default package/ExampleHttpServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ExampleHttpServlet extends HttpServlet
{
private String mymsg;
public void init() throws ServletException
{
mymsg = "Http Servlet Demo";
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>" + mymsg + "</h1>");
out.println("<p>" + "Hello Friends!" + "</p>");
}
public void destroy()
{
}
}
web.xml:
This file can be found at this path WebContent/WEB-INF/web.xml. In
this file we will map the Servlet with the specific URL. Since we are calling
welcome page upon clicking the link on index.html page so we are mapping
the welcome page to the Servlet class we created above.
<web-app>
<display-name>BeginnersBookServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>MyHttpServlet</servlet-name>
<servlet-class>ExampleHttpServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyHttpServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Run the project:
You can call servlets by using URLs embedded as links in HTML or JSP
pages. The format of these URLs is as follows:
http://server:port/context_roott/servlet/servlet_name?name=value
http://server:port/OfficeFrontEnd/servlet/ShowSupplies?name=value
You can call this servlet programmatically from another servlet in one
of two ways.Include another servlet's output, use the include() method from
the RequestDispatcher interface. This method calls a servlet by its URI and
waits for
Example:
RequestDispatcher dispatcher =z
getServletContext().getRequestDispatcher("/servlet/ShowSupplies");
dispatcher.include(request, response);
To handle interaction control to another servlet, use
the RequestDispatcher interfaces forward() method with the servlet's URI as
a parameter.
This example shows a servlet using forward():
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("/servlet/ShowSupplies");
dispatcher.forward(request, response);
4.9 RETRIEVING PARAMETERS
It is common in web applications to pass data or parameters from one
to another page. To retrieve the values of various elements in a HTML form
or from another page, we can use the following methods which are available
in HttpServletRequest object:
SSI cant be supported for all web server. so you can read web server
supported documents before using the SSI in your code.
It helpful for when you want to small part of page loading dynamically
instead of whole page loading. Below the Syntex given,
<SERVLET CODE=MyservletClassname CODEPASE=path
initparam1=initparamvalue initparam2=initparam2value>
<PARAM NAME=name1 VALUE=value1>
<PARAM NAME=name2 VALUE=value2>
</SERVLET>
Here the path indicate the MyservletClassname class name path in the
server. you can setup the remote file path also. the remote file path syntex
is,
http://server:port/dir
You can pass the any no of PARAM in that SERVLET. It can be accessed by
using getParameter() method in ServletRequest class.
You can save the SSI contains html file using .shtml extension.
The Example can be showing the current time for here and the time in
London and Newyork.
First to write the the shtml file to call the servlet class.
<HTML>
<HEAD><TITLE>Times!</TITLE></HEAD>
<BODY>
4.11 COOKIES
The cookie is stored in the user browser, the client (user’s browser)
sends this cookie back to the server for all the subsequent requests until the
cookie is valid. The Servlet container checks the request header for
cookies and get the session information from the cookie and use the
associated session from the server memory.
The session remains active for the time specified in tag in web.xml. If
tag in not set in web.xml then the session remains active for 30 minutes.
Types of Cookies:
Unlike Session cookies they have expiration time, they are stored in
the user hard drive and gets destroyed based on the expiry time.
Cookies to the Client:
By using setMaxAge () method we can set the maximum age for the
particular cookie in seconds.
c.setMaxAge(1800);
Place the Cookie in HTTP response header:
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++){
System.out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Welcome Screen:
Use of JSP:
• 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.
Advantages of JSP:
Following table lists out the other advantages of using JSP over other
technologies.
The advantages of JSP are twofold. First, the dynamic part is written in
Java, not Visual Basic or other MS specific language, so it is more powerful
and easier to use. Second, it is portable to other operating systems and non-
Microsoft Web servers.
Pure Servlets:
SSI is really only intended for simple inclusions, not for "real" programs
that use form data, make database connections, and the like.
JavaScript:
JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access
and image processing etc.
Static HTML:
JSP files are usually used for views rather than for logic, so users often
want to change the JSP files while still running the service, so web
applications that use JSP are often deployed as a directory instead of a WAR.
JSP files are located in the root directory of the web context. They can
be packaged as a separate directory or in the 'META-INF/resources/ that is
defined in Servlet 3.0' directory.JSP files can be found in the
'META-INF/resources/' directory if the directory is in the *.jar library files of
the 'WEB-INF/lib/' directory. JSP files in 'WEB-INF/' cannot be executed
because for security reasons web clients cannot access the files in the 'WEB-
INF/' directory.
When multiple web engines execute a service using the same source
file from NAS, a delayed service or errors can occur due to OS file system
access operations that are needed at JSP compilation time. In order to
address this issue, the JSP precompilation and JSP graceful reloading
functions are provided, but a more fundamental resolution of compiling and
executing in memory is also provided.
The JSP engine saves the .java and .class files, the results of JSP
compilation, in memory. Therefore, the engine does not access the file
system except for when reading metadata and content from the .jsp file.
The .java and .class files are actually needed for other reasons. They
are used in the file system by using a background thread that every JSP
engine has, instead of using a request processing thread. Since the thread
handles requests in the order they are received, the chances of bottlenecks
happening in the file system due to file I/O requests are low, but the .smap
files are not used.
Configuring JSP Engines:
3. Configure the basic information on the Jsp Engine screen and click
[OK].
• JSP source code - This is the form the developer actually writes. It
exists in a text file with an extension of.jsp, and consists of a mix of HTML
template code, Java language statements, and JSP directives and actions that
describe how to generate a Web page to service a particular request.
• Java source code - The JSP container translates the JSP source code
into the source code for an equivalent Java servlet as needed. This source
code is typically saved in a work area and is often helpful for debugging.
• Compiled Java class - Like any other Java class, the generated servlet
code is compiled into bytecodes in a .class file, ready to be loaded and
executed.
The JSP container manages each of these forms of the JSP page
automatically, based on the timestamps of each file. In response to an HTTP
request, the container checks to see if the .jsp source file has been modified
since the .java source was last compiled. If so, the container retranslates the
JSP source into Java source and recompiles it.
The above diagram illustrates the process used by the JSP container.
When a request for a JSP page is made, the container first determines the
name of the class corresponding to the .jsp file. If the class doesn’t exist or if
it’s older than the .jsp file (meaning the JSP source has changed since it was
last compiled), then the container creates Java source code for an equivalent
servlet and compiles it.
Example:
converter.jsp
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<%-- Prints a conversion table of miles per gallon to kilometers per liter --
%>
<BODY>
<H3>Fuel Efficiency Conversion Chart</H3>
<TABLE BORDER=1>
<TR>
<TH>Kilometers per Liter</TH>
<TH>Miles per Gallon</TH>
</TR>
<%>
for (double kpl = 5; kpl <= 20; kpl += 1.0) {
double mpg = kpl * 2.352146;
<%>
<TR>
<TD><%=FMT.format(kpl)%></TD>
<TD><%=FMT.format(mpg)%></TD>
</TR>
<%
}
%>
</TABLE>
</body>
</html>
Let's invoke this JSP page from a Web browser, you see the table on a
browser:
converter_jsp.java:
A JSP is a text document which contains two types of text: static data
and dynamic data. The static data can be expressed in any text-based
format (like HTML, XML, SVG and WML), and the dynamic content can be
expressed by JSP elements. Difference between Servlet and JSP:
JSPs are utilised for server-side programming and are also used to create
platform-independent, dynamic web applications.
1. Servlets load only one copy into the Java Virtual Machine. This makes
their memory efficient and faster.
2. The response time is significantly less, as it saves time to respond to
the first request.
3. Servlets are easily accessible, as they use standard API that is used by
a large number of web servers.
4. It is easy for development and is platform-independent.
5. Servlet’s usage doesn’t constrain the web servers.
6. Servlets help developers access a large number of APIs, which are
available for Java.
7. It is very easy to maintain multiple Servlets for a single web
application.
8. Servlet containers provide developers with the facility of support to
several other features like resource management, sessions, security,
persistent, etc.
9. If servlets have multiple requests, the web containers provide threads
to handle more than one request.
The Advantages of using JSP:
Template Data:
Template data refers to the static HTML or XML content of the JSP.
Although it is essential for the JSP presentation, it is relatively uninteresting
from a JSP programming point of view.
Aside from the usual substitutions, such as those based on quoting and
escape sequences, the template data is written verbatim as part of the JSP
response.
JSP Elements:
JSP elements represent the portion of the JSP that gets translated and
compiled into a servlet by the JSP compiler. In syntax, JSP elements are
similar to HTML elements in that they have a begin and an end tag (for
example, <B> bold text </B>).
There are three types of JSP elements defined in the JSP specification:
directive elements, action elements, and scripting elements.
Directive Elements:
Directive elements provide global information for the translation
phase. These directives are general in nature, that is, not related to a
specific request and thus do not directly impact the output to the client.
Directive elements take the following form:
Page directive:
Action Elements:
or
</prefix:tag>
Actions prefixed with “jsp” are standard actions. Some standard actions are
• Include responses sent by other JSPs
Scripting Elements:
Declarations:
<jsp:expression>Some expression</jsp:expression>
Example:
In this tutorial, we will learn about how to create a table in the database, and
how to create records in these tables through JSP.
• Create Table
• Create Records
Create Table:
C:\>Program Files\MySql\bin>
Mysql>
Emp_namevarchar(11),
);
First the records are inserted using INSERT query and then we can
useSELECTquery to check whether the table is created or not.
Create Records:
Select:
The Select operation is used to select the records from the table.
Example:
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
</head>
<body>.
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
</sql:query>
<table>
<tr>
<th>Guru ID</th>
<th>Name</th>
</tr>
<tr>
<td><c:out value="${row.emp_id}"/></td>
<td><c:out value="${row.emp_name}"/></td>
</tr>
</c:forEach> </table>
</body>
</html>
Output:
Here both the records will be fetched from the database
1 guru emp1
2 guru emp2
Insert:
Example:
In this example, we are going to learn about inserting the records in the
table guru_test
pageEncoding="ISO-8859-1"%>
<html>
<head>
</head>
<body>
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
<gurusql:update dataSource="${guru}" var="guruvar">
</gurusql:update>
</body>
</html>
Delete
This is delete operation where we delete the records from the table
guru_test.
Example:
Here we will delete query to delete the record from the table guru_test.
The record which has to be deleted has to be set in variable "guruid", and
the corresponding record is deleted from the database.
6. pageEncoding="ISO-8859-1"%>
8. <html>
9. <head>
13. <body>
16. url="jdbc:mysql://localhost/GuruTest"
22. </gurusql:update>
23. </body>
24. </html>
Output:
When you execute the above code, the record with emp_id as 3 is
deleted.
Update:
Example:
pageEncoding="ISO-8859-1"%>
<head>
</head>
<body>
url="jdbc:mysql://localhost/GuruTest"
user="gururoot" password="guru"/>
</gurusql:update>
</body>
</html>
Output:
When you execute the above code the record withemp_id 2 is changed to 99.
So, now the output will show emp"guru99" instead of emp "guru2".