0% found this document useful (0 votes)
19 views57 pages

Unit 4

Java Servlets are server-side programs that act as intermediaries between web clients and databases, offering better performance and security compared to CGI. Applets are client-side Java programs that run in browsers but face security restrictions due to their remote execution. The document also discusses servlet alternatives, strengths, architecture, and lifecycle, emphasizing the importance of servlets in dynamic web applications.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views57 pages

Unit 4

Java Servlets are server-side programs that act as intermediaries between web clients and databases, offering better performance and security compared to CGI. Applets are client-side Java programs that run in browsers but face security restrictions due to their remote execution. The document also discusses servlet alternatives, strengths, architecture, and lifecycle, emphasizing the importance of servlets in dynamic web applications.

Uploaded by

govindanm223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 57

UNIT-IV

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.

Java Servlets often serve the same purpose as programs implemented


using the Common Gateway Interface (CGI). But Servlets offer several
advantages in comparison with the CGI.

• Performance is significantly better.


• Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client
request.
• Servlets are platform-independent because they are written in Java.
• Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet

Applet:

An Applet is a small java program that runs in a Java enabled web


browser. Java Applet is a small piece of java code that is embedded into
HTML page, which gets executed when the HTML page loads into the
browser.Applets provide powerful client-side functionality. As applets are
loaded from remote machines and executed on client-side, there are various
security restrictions on applets. Let us look into various Applets advantages
and Applets Restrictions in brief .
applet Advantages

Applets have many advantages over stand-alone application. Some of


them are :

 As applet is a small java program, so it is platform independent


code which is capable to run on any browser.
 Applets can perform various small tasks on client-side machines.
They can play sounds, show images, get user inputs, get mouse
clicks and even get user keystrokes, etc ...
 Applets creates and edit graphics on client-side which are different
and independent of client-side platform.
 As compared to stand-alone application applets are small in size,
the advantage of transferring it over network makes it more usable.
 Applets run on client browser so they provide functionality to import
resources such as images, audio clips based on Url's.
 Applets are quite secure because of their access to resources.
 Applets are secure and safe to use because they cannot perform
any modifications over local system.
 Various small tasks such as performing login, inventory checking,
task scheduling can be done by applets running over Intranets.
Applets Restrictions:

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 :

 If we are running an applet from a provider who is not trustworthy than


security is important.
 Applet itself cannot run or modify any application on the local system.
 Applets has no access to client-side resources such as files , OS etc.
 Applets can have special privileges. They have to be tagged as trusted
applets and they must be registered to APS (Applet Security Manager).
 Applet has little restriction when it comes to communication. It can
communicate only with the machine from which it was loaded.
 Applet cannot work with native methods.
 Applet can only extract information about client-machine is its name,
java version, OS, version etc ... .
 Applets tend to be slow on execution because all the classes and
resources which it needs have to be transported over the network.

4.2 SERVLET ALTERNATIVES


Servlets are the Java programs that run on the Java-enabled web
server or application server. They are used to handle the request obtained
from the webserver, process the request, produce the response, then send
the response back to the webserver. Below are some alternatives to servlets:

Common Gateway Interface (CGI):

It is the most typical server-side solution. CGI application is an


independent program that receives requests from the online server and
sends it back to the webserver. The use of CGI scripts was to process forms.
it’s the technology that permits web browsers to submit forms and connect
with programs over an internet server. The common gateway interface
provides an even way for data to be passed from the user’s request to the
appliance program and back to the user.

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:

Many proprietary web servers have built-in support for server-side


programming. These also are called non-free software, or closed-source
software, is computer software that the software’s publisher or another
person retains property right usual copyright of the ASCII text file, but
sometimes patent rights. It’s a software library interface “specific to at least
one device or, more likely to a variety of devices within a specific
manufacturer’s product range”. The motivation for employing a proprietary
API is often vendor lock-in or because standard APIs don’t support the
device’s functionality.

Example:

Netscape’s NSAPI, Microsoft’s ISAPI, and O’Reilly’s WSAPI.

Drawback:

Most of these are developed in C/C++ and hence can contain memory
leaks and core dumps that can crash the webserver.

Active Server Pages (ASP):

Microsoft’s ASP is another technology that supports server-side


programming. Only Microsoft’s Internet Information Server (IIS)
supports this technology which isn’t free. They work with simple HTML
pages, the client (a web surfer) requests an internet page from a
server. The server just sends the file to the client, and therefore the
page is shown on the client’s browser. ASP is now obsolete and
replaced with ASP.NET. ASP.NET may be a compiled language and
relies on the .NET Framework, while ASP is strictly an interpreted
language.
Serverside JavaScript:

It is another alternative to servlets. The sole known servers that


support it are Netscape’s Enterprise and FastTrack servers. This ties you to a
specific vendor. Server-side JavaScript can be a JavaScript code that runs
over a server local resources and it is similar to Java or C#, but the syntax is
predicated on JavaScript.
Example:

An ideal of this is often Node.JS. The advantage of server-side scripting


is that the ability to highly customize the response supported the user’s
requirements, access rights, or queries into data stores.

4.3 SERVLET STRENGTHS:


The Servlet is a Java program which can run in Web server or
Application server and act as a mediator from a web browser or client to the
database or Server. For this Servlet, one can take input from the users
through HTMLor Web forms and can also take present records from
databases and create web forms dynamically.Now, there comes a doubt
about what is a Web server and Application server.

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:

• The servlet is a server side component which gives a powerful


mechanism for developing server side application.

• Servlet provides an important role in the exploring internet,


reusability, performance and scalability.

• A web developer can create fast and efficient server side program by
using servlets.

• The servlet is platform independent because servlet is written entirely


on Java. Servlets can run on any web server. For example, if one
develops an application in windows machine running the Resin server,
one can easily run the same application on Apache web server without
modification and compilation of code.

• 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 secure.It is nothing but applying Authentication and


Authorization on the Web Application.

• Authentication means checking the identity of a user.

• Authorization means checking the access permission of the user on


particular resources of the project.

• The servlet is Robust because, they are managed by the JVM.So need
not worry about the memory leak, garbage collection.

• The servlet is Scalable because, Servlet developed based on thread


based server side technologies.

4.4 SERVLET ARCHITECTURE:


lets are grouped under the Advanced Java tree that are used to create
dynamic web applications. Servlets are robust in nature,well scalable and are
primarily used in developing server-side applications. If we go a little back in
time, we would be able to witness that before the introduction of servlets,
CGI (Common Gateway Interface) were used. Amid several indigenous tasks
that a servlet is capable of doing, dynamically performing client requests and
responses are most common. Other tasks that a servlet can do effectively
are:

• Can easily manage/control the application flow.

• Suitable to implement business logic.

• Can effectively balance the load at the server-side.


• Easily generate dynamic web content.

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:

 Implementing Servlet Interface


 Extending Generic Servlet
 Extending HTTP Servlet.
Components of Servlet Architecture:

Below is the high level architecture diagram of servlet. Let’s see in


brief, how does each component add to the working of a servlet.

Client:

The client shown in the architecture above is primarily working as a


medium who is sending out HTTP requests over to the web server and again
processing the response it gets back from the server. As we can see in the
diagram, our client here is the web browser.

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:

 Static web server


 Dynamic web server
Web Container: Web container is another typical component in servlet
architecture which is responsible for communicating with the servlets. Two
prime tasks of a web container are:

• Managing the servlet lifecycle

• 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 :

Every servlet should override the following 3 methods namely:

 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 client sends over a request.

• 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.

• By passing ServletRequest and Response object, publicservice()


method is called by the container.

• In the next step, the ServletRequest and ServletResponseobjects are


type-casted to HttpServletRequest andHttpServletResponse objects by the
public service() method.

• Now protected service() method is called by the public


service()method.

• The protected service() method dispatches the request to the correct


handler method based on the type of request.

• When servlet container shuts down, it unloads all the servlets and calls
destroy() method for each initialized servlets.

Advantages:

• Prime functionality of a servlet is that they are independent of server


configuration and they are pretty much compatible with any of the web
servers

• Servlets are also protocol-independent supporting FTP, HTTP,SMTP,


etc. protocols to the fullest.

• Until destroyed manually, servlets can be retained in the memory


helping process several requests over time. Also, once a database
connection is established, it can facilitate process several requests for a
database in the very same database session.
• Servlets inherit Java’s property of portability and hence are compatible
with nearly any web server.

• Servlets are first converted into byte codes and then executed, which
helps in increasing the processing time.

Disadvantages:

• Designing a servlet can be pretty laborious.

• Exceptions need to be handled while designing a servlet since they are


not thread-safe.

• Developers may need additional skills to program a servlet.

4.5 SERVLET LIFE CYCLE


A servlet life cycle can be defined as the entire process from its
creation till the destruction. The following are the paths followed by a servlet.

• The servlet is initialized by calling the init() method.

• The servlet calls service() method to process a client's request.

• The servlet is terminated by calling the destroy() method.

• Finally, servlet is garbage collected by the garbage collector of the


JVM.

Now let us discuss the life cycle methods in detail.

The init() Method:

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.

The servlet is normally created when a user first invokes a URL


corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started.When a user invokes a servlet, a
single instance of each servlet gets created, with each user request resulting
in a new thread that is handed off to doGet or doPost as appropriate. The
init() method simply creates or loads some data that will be used throughout
the life of the servlet.

Syntax:

public void init() throws ServletException {

// Initialization code...

The service() Method:

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.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

The service () method is called by the container and service method


invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you
have nothing to do with service() method but you override either doGet() or
doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods with in
each service request. Here is the signature of these two methods.

The doGet() Method:

A GET request results from a normal request for a URL or from an


HTML form that has no METHOD specified and it should be handled by
doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

// Servlet code

The doPost() Method:

A POST request results from an HTML form that specifically lists POST
as the METHOD and it should be handled by doPost() method.

Syntax:

public void doPost(HttpServletRequest request, HttpServletResponse


response)

throws ServletException, IOException {

// Servlet code }

The destroy() Method:

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:

public void destroy() {

// Finalization code...}

Architecture Diagram:

The following figure depicts a typical servlet life-cycle scenario.

• 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.

• Then the servlet container handles multiple requests by spawning


multiple threads, each thread executing the service() method of a
single instance of the servlet.

4.6 GENERIC SERVLET


A generic servlet is a protocol independent Servlet that should always
override the service() method to handle the client request. The service()
method accepts two arguments ServletRequest object and ServletResponse
object. The request object tells the servlet about the request made by client
while the response object is used to return a response back to the client.

Hierarchy of Generic Servlet:

java.lang.Object

|_extended byjavax.servlet.GenericServlet

GenericServlet is an abstract class and it has only one abstract method,


which is service(). That’s why when we create Generic Servlet by extending
GenericServlet class, we must override service() method.

Pros of using Generic Servlet:

1. Generic Servlet is easier to write

2. Has simple lifecycle methods

3. To write Generic Servlet you just need to extend javax.servlet.

Cons of using Generic Servlet:


Working with Generic Servlet is not that easy because we don’t have
convenience methods such as doGet(), doPost(), doHead() etc in Generic
Servlet that we can use in Http Servlet.

In Http Servlet we need to override particular convenience method for


particular request, for example if you need to get information then override
doGet(), if you want to send information to server override doPost(). However
in Generic Servlet we only override service() method for each type of request
which is cumbersome.

I would always recommend you to use HttpServlet instead of the


GenericServlet. HttpServlet is easier to work with, and has more methods to
work with than 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>

Methods of GenericServlet class:

Here is the list of all the methods of GenericServlet class.


1. Public void init(): it is a convenient method. This method can be
overridden so that there’s no need to call super.init(config).
2. Public void init(ServletConfig config): Called by the servlet container
to indicate that the servlet is being placed into service, this method is used
for initializing the servlet.
3. Public String getInitParameter(String name): Returns a String
containing the value of the given initialization parameter, or null if the
parameter does not exist.
4. Public Enumeration getInitParameterNames(): Returns the names of
all the parameters defined in the web.xml file or null if web.xml does’t have
any parameter.
5. Public abstract void service(ServletRequest request,
ServletResponse response): Called by the Servlet container to allow
servlet to respond to the requests made by client.
6. Public void destroy(): It is called by servlet container once at the end of
servlet life cycle to indicate that servlet is being destroyed.
7. Public ServletConfig getServletConfig(): Return the ServletConfig
object that initialized this servlet
8. Public String getServletInfo(): Returns information about servlet.
9. Public ServletContext getServletContext(): Return ServletContext
object, passed to this servlet by the init method
10. Public String getServletName(): Returns the name of the servlet
instance.
11. Public void log(String msg): Writes the given message in the servlet
log file.
12. Public void log(String msg,Throwable t): Writes the explanatory
message in the servlet log file including a String that describes the error or
exception

4.7 HTTP SERVLET


Unlike Generic Servlet, the HTTP Servlet doesn’t override the service()
method. Instead it overrides the doGet() method or doPost() method or both.
The doGet() method is used for getting the information from server while the
doPost() method is used for sending information to the server.

In Http Servlet there is no need to override the service() method


because this method dispatches the Http Requests to the correct method
handler, for example if it receives HTTP GET Request it dispatches the
request to the doGet() method.

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.

Hierarchy of Http Servlet:

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:

Right click on the index.html, run on server.


Methods of HttpServlet class:

1. protected void doGet(HttpServletRequest req,


HttpServletResponse resp): This method is called by servlet service
method to handle the HTTP GET request from client. When overriding this
method, read the request data, write the response headers, get the
response’s writer or output stream object, and finally, write the response
data.
2. protected long getLastModified(HttpServletRequest req): Returns
a long integer specifying the time the HttpServletRequest object was last
modified, in milliseconds since midnight, January 1, 1970 GMT, or -1 if the
time is not known
3. protected void doHead(HttpServletRequest req,
HttpServletResponse resp): This method is called by servlet service
method to handle the HTTP HEAD request from client. The client sends a
HEAD request when it wants to see only the headers of a response, such as
Content-Type or Content-Length
4. protected void doPost(HttpServletRequest req,
HttpServletResponse resp): This method is called by servlet service
method to handle the POST request from client. The HTTP POST method
allows the client to send data of unlimited length to the Web server a single
time and is useful when posting information to the server. Unlike, doGet
where we get information from the sever this method is used when we are
transferring information from client to the server.
5. protected void doPut(HttpServletRequest req,
HttpServletResponse resp): This method is called by servlet service
method to handle the PUT request from client. This method is similar to
doPost method but unlike doPost method where we send information to the
server, this method sends file to the server, this is similar to the FTP
operation from client to server.
6. protected void doDelete(HttpServletRequest req,
HttpServletResponse resp): Called by servlet service() method to handle
the DELETE request from client that allows a client to delete a document,
webpage or information from the server.
7. protected void doOptions(HttpServletRequest req,
HttpServletResponse resp): Called by the service method to allow a
servlet to handle a OPTIONS request. The OPTIONS request determines which
HTTP methods the server supports and returns an appropriate header.
8. protected void doTrace(HttpServletRequest req,
HttpServletResponse resp): This method is called by service() method for
handling TRACE request. Used for debugging purposes.
9. protected void service(HttpServletRequest req,
HttpServletResponse resp): There is no need to override this method, this
method receives the HTTP request from client and forwards them to the
corresponding doXXX methods such as doGet(), doPost(), doHEAD() etc.
10. public void service(ServletRequest req, ServletResponse res):
Forwards client request to the protected service method. There’s no need to
override this method as well.
4.8 INVOKING SERVLETS
Invoke a servlet by directly addressing it from a Web page with a URL
or by calling it programmatically from an already running servlet.

• Calling a Servlet With a URL

• Calling a Servlet Programmatically

Calling a Servlet With a URL:

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

Calling a Servlet Programmatically:


Identify which servlet to call by specifying a URI. This URI is normally a
path relative to the current application. For example, if your servlet is part of
an application with a context root named OfficeFrontEnd, the URL to a servlet
called ShowSupplies from a browser is as follows:

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

it to return before continuing to process the interaction.


The include() method can be called multiple times within a given servlet.

The following table describes each URL section


URL Element Description

server:port The IP address or host name and


optional port number.
To access the default web application
for a virtual server, specify only this
URL section. You do not need to
specify
the context_root orservlet_name u
nless you also wish to specify name-
value parameters.

context_root The context path without the leading


“/” at which the web application is
installed.

Servlet Only needed if no servlet-mapping is


defined in the web.xml file.

servlet_name The servlet-name (or servlet-mapping if


defined) as configured in
the web.xml file.

?name=value... Optional servlet name-value


parameters.

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:

String getParameter(String name)


Enumeration getParameterNames()
String[] getParamterValues(String name)
Following example demonstrates retrieving data from a login page to a
servlet:
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">
<title>Login</title>
</head>
<body>
<form action="auth.html" method="get">
. Username: <input type="text" name="txtuser" /><br />
.Password: <input type="password" name="txtpass" /><br />
.<input type="submit" value="Submit" />
.<input type="reset" value="Clear" />
.</form>
.</body>
</html>
web.xml

<?xml version="1.0" encoding="UTF-8"?>


<web-app>
<servlet>
<servlet-name>Authenticate</servlet-name>
<servlet-class>Authenticate</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Authenticate</servlet-name>
<url-pattern>/auth.html</url-pattern>
</servlet-mapping>
</web-app>

4.10 SERVER SIDE INCLUDES


Server Side Includes are commands and directives placed in the web
page that can be evaluated by the web server when the web page being
served. The servlet code embedded inside theHTML code called as SSI.

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.

Program for SSI :

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>

The current time here is:

<!-- here the ssi servlet class has been called-->


<SERVLET CODE=CurrentTime>
</SERVLET>
<P>
The current time in London is:
<!-- here the ssi servlet class has been called and send the parameter-->
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=GMT>
</SERVLET>
<P>
And the current time in New York is:
<!-- here the ssi servlet class has been called and send the parameter-->
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=EST>
</SERVLET>
<P>
</BODY>
</HTML>
After that the web server receive the SERVLET tag and process the SSI.
First it search the server container has the SSI servlet class i.e .shtml file has
the CODE attribute value as treated as SSI servlet class.
Then the file found it process the SSI servlet. The SSI servlet use either
doget() or service() method in request process.

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:

We can classify the cookie based on their expiry time:


1. Session
2. Persistent
SessionCookies:

Session cookies do not have expiration time. It lives in the browser


memory. As soon as the web browser is closed this cookie gets destroyed.
Persistent 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:

Here are steps for sending cookie to the client:


o Create a Cookie object.
o Set the maximum Age.
o Place the Cookie in HTTP response header.
Create a Cookie object:

Cookie c = new Cookie("userName","Chaitanya");


Set the maximum Age:

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:

We can send the cookie to the client browser through


response.addCookie() method.
response.addCookie(c);
Read cookies:

Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++){
System.out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());

Example of Cookies in java servlet:

index.html
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>

<input type="submit" value="submit"/>


</form>
MyServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
String name = request.getParameter("userName");
String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
Cookie c1=new Cookie("userName",name);
Cookie c2=new Cookie("userPassword",password);
response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<br><a href='welcome'>View Details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}}}
MyServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
Cookie c[]=request.getCookies();
pwriter.print("Name: "+c[1].getValue());
pwriter.print("Password: "+c[2].getValue());
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}}
}
web.xml
<web-app>

<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:

Methods of Cookie class:

public void setComment(String purpose): This method is used for


setting up comments in the cookie. This is basically used for describing the
purpose of the cookie.

public String getComment(): Returns the comment describing the


purpose of this cookie, or null if the cookie has no comment.
Public void setMaxAge(int expiry): Sets the maximum age of the cookie
in seconds.
public int getMaxAge(): Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until
browser shutdown.
public String getName(): Returns the name of the cookie. The name
cannot be changed after creation.
public void setValue(String newValue): Assigns a new value to this
Cookie.
public String getValue(): Gets the current value of this Cookie.

4.12 JAVASERVER PAGES (JSP)


JavaServer Pages (JSP) is a technology for developing Webpages that
supports dynamic content. This helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and
end with %>.

A JavaServer Pages component is a type of Java servlet that is


designed to fulfill the role of a user interface for a Java web application. Web
developers write JSPs as text files that combine HTML or XHTML code, XML
elements, and embedded JSP actions and commands.

JSP tags can be used for a variety of purposes, such as retrieving


information from a database or registering user preferences, accessing
JavaBeans components, passing control between pages, and sharing
information between requests, pages etc.

Use of JSP:

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.

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.

Advantages of JSP:

Following table lists out the other advantages of using JSP over other
technologies.

Active Server Pages (ASP):

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:

It is more convenient to write (and to modify!) regular HTML than to


have plenty of println statements that generate the HTML.
Server-Side Includes (SSI):

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:

Regular HTML, of course, cannot contain dynamic information.

4.13 JSP ENGINE:


JSP engine is embedded in web engines. It exists in each web context.
This section does not explain JSP standards. Refer to the JSP standards for
more information about creating a JSP engine.When web clients request JSP
pages, the JSP engine finds the pages and converts them to servlets. During
the servlets conversion process, the engine creates Java files and SMAP files,
and compiles the Java files to create class files that will be used for the
services.
If JSP pre-compilation is not used, JSP files are compiled the first time
the request is received, so when the first request happens, the response
might take more time because the access to the OS file system occurs
frequently.In an environment where network-attached storage (NAS) is used,
if there are many files that require compilation because of tags and JSP
include relations, many requests will be sent to the NAS, which delays the
response.
JSP Engine Functions:

The JSP engine provides reloading, pre-compilation functions, graceful


reloading, as well as JSP compiling and running at the memory.

Reloading JSP Files:

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.

• When deployed as a directory,If a JSP file is changed in the directory


where the application is deployed as a directory, the JSP engine compares
the last modified date of the existing compiled class files with the modified
date of the original files, and then compiles the files.When this happens, if
the configuration <check-included-jspfile> is 'true', even if the requested JSP
file has not changed, the JSP files or tag files (.tld) that are included in the JSP
file will be checked to recompile the JSP file.

• When deployed as a WAR If applications are deployed in WAR, all of


the files will be repackaged to be redeployed, so the risk is high in the
perspective of service operation.If a large amount of files are changed,
consider graceful redeployment, which is provided Starting from JEUS 7..

JSP in Web Context:

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.

Precompiling JSP Files:

JSP precompilation compiles JSP pages of a web context in advance.


This can be done using the appcompiler script or the precompile-jsp (jspc)
command in jeusadmin.
The appcompiler can precompile JSP files even in an offline state and
precompile-jsp can precompile the modules that are deployed on JEUS.
Precompilation can help improves performance when the JSP is called for the
first time.
JSP Compilation and Execution in Memory:

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:

The JSP engine can be configured in WebAdmin or in each application's


jeus-web-dd.xml file.
The JSP engine of a web engine can be configured in WebAdmin.
1. Click [Servers] from the left menu to go to the list of servers. Click a
server from the list to go to the server configuration screen. From the screen,
go to the [Engine] > [Web Engine] > [Jsp Engine] tab.
Configuring a JSP Engine - Menu
2. Click [Lock & Edit] to change to configuration mode.

3. Configure the basic information on the Jsp Engine screen and click
[OK].

4.14 WORKING WITH JSP :


A JSP page exists in three forms:

• 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.

Container process JSP page:

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:

To illustrate how JSP works, let’s look at the example converting


kilometers per liter to miles per gallon JSP example.

converter.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<%@ page session="false"%>

<%@ page import="java.io.*,java.text.*,java.util.*"%>

<!DOCTYPE html>

<html>

<head>

<meta charset="ISO-8859-1">

<title>>Fuel Efficiency Conversion Chart</title>

<%!private static final DecimalFormat FMT = new DecimalFormat("#0.00");


%>

</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:

To make the JSP-to-servlet relationship clearer, look at the .java source


code generated by the JSP container. This code will differ greatly, depending
on which container is used and the implementation approach it takes
4.15 Servlet and JSP:
Servlet:

A servlet is a Java class which is used to extend the capabilities of


servers that host applications accessed by means of a request-response
model. Servlets are mainly used to extend the applications hosted by webs
servers, however, they can respond to other types of requests too. For such
applications, HTTP-specific servlet classes are defined by Java Servlet
technology.

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:

Servlets are a method to develop web applications by implementing


them in a platform-independent and component-based approach. It does not
abide by the performance-based restrictions of CGI programs (Common
Gateway Interface). Servlets can access all the Java APIs and the JDBC API to
access enterprise databases.

JSPs are utilised for server-side programming and are also used to create
platform-independent, dynamic web applications.

The Advantages of using Servlets:

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:

1. JSP can be used to write Servlets.


2. JSP is very easy to modify, and therefore, it makes it very convenient.
3. Developers can easily show and process information in JSP.
4. JSP can use the multithreading feature of Java.
5. JSP can be easily connected to the MYSQL databases.
6. JSP can use the exceptional handling feature of Java.
7. JSP has better performance and scalability, as developers can embed
dynamic elements into the HTML code.
8. JSP is based in Java and is platform-independent.
Disadvantages of using Servlet:

1. Servlets create threads and not a process when a request arrives.


2. It is harder to code and perform exception handling, as Servlet codes
are not thread-safe by default.
3. Java Runtime Environment is necessary to run Servlets on the server.
4. Developing Servlets requires experience and a lot of knowledge of Java
Servlets for development.
5. Only one Servlet is loaded into the JVM.
6. HTML code and Java code are interdependent and can cause errors if
changes are not taken into consideration.
Disadvantages of using JSP:
1. It is very difficult for developers to perform database connectivity in
JSP.
2. As the JSP is compiled on the server, it is not memory and time-
efficient.
3. It is hard to track errors in JSP files because they are an extension to
Servlets. The JSP codes are processed into Servlet codes for
compilation.
4. As JSP is an HTML file, it doesn’t provide many features.

4.16 ANATOMY OF JSP:


A JSP consists of two basic items: template data and JSP elements.
Template data provides the static aspects, and JSP elements are used for the
dynamic aspects of a 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:

<% @directive-name directive-attribute="attribute-value" other-

attribute-value-pairs ... %>

An example of a directive element follows:

<% include file="Header. sp" %>

Page directive:

A page directive and its attributes provide a convenient mechanism for


instructing the environment on the configuration of various things, such as
libraries to be imported, content type of the page, buffer size, and so on.
With the exception of the import attribute, other page attributes can only be
defined once in the JSP.

Action Elements:

Elements via certain variables. Unlike directive elements, action


elements come into play during the request-processing phase. JSP actions
elements are written using an XML syntax in one of the following two
formats:

<prefix:tag attribute=value attribute-value-list.../

or

<prefix: tag attribute=value attribute-value-list> body

</prefix:tag>

The idea is to establish an association between tags and have a “tag


handler” defined for each tag, which gets invoked to handle the tag when
the tag is encountered. Tag handlers are essentially pieces of code, for
example:

<jsp:forward page="/errorPage" />

Actions prefixed with “jsp” are standard actions. Some standard actions are
• Include responses sent by other JSPs

• Forward requests to others

• Query and update properties of a JavaBean residing on the server

Actions may create objects that are made available to scripting

Scripting Elements:

Scripting elements bring everything together in a JSP. These elements


can be declarations used for defining variables and methods, blocks of code
called scriptlets, and expressions for evaluation during request processing.

Declarations:

Declarations define variables and methods. The syntax for declarations


is <%! Declaration %> where declaration can be a variable or a function, for
example:

<%! private static MyLoginCount=0;

Expressions: Expressions are evaluated during the request-processing


phase of the JSP, and the results are converted to a string and intermixed
with the template data. The result is placed in the same place where the
expression was located in the JSP page.

The syntax of expressions is <% = Some expression %>.

In the XML syntax, the same is expressed as:

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

Example:

Login Count: <%= results %>

4.17 DATABASE CONNECTIVITY USING JSP:


The database is used for storing various types of data which are huge
and has storing capacity in gigabytes. JSP can connect with such databases
to create and manage the records.

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

• JSP Operations: Insert, Update, Delete, Select

Create Table:

In MYSQL database, we can create a table in the database with any


MYSQL client.

Here we are using PHPMyadminclient, and there we have an option "new" to


create a new table using below screenshot.

In this, we have to provide table name as guru_test, and we will create


two fields'emp_id and emp_name.

Emp_idis havingdatatype as int

Emp_nameis havingdatatype as varchar

Another option is by using command prompt and changes to MYSQL


directory:
C:\>

C:\>cd Program Files\MY SQL\bin

C:\>Program Files\MySql\bin>

We can login to database as follows:

C:\Program Files\MYSQL\bin>mysql –u gururoot –p

Enter Password: *******

Mysql>

Create table guru_testin the database named as GuruTestas the following on


MYSQL prompt:

Mysql> use GuruTest;

MySql> create table guru_test(

Emp_idint NOT NULL,

Emp_namevarchar(11),

);

Once you execute this you get the following:

Query OK, 0 rows affected(0.10 sec)

MySQl> select * from guru_test;

Query OK, 0 rows affected(0.10 sec)

First the records are inserted using INSERT query and then we can
useSELECTquery to check whether the table is created or not.

Create Records:

After creating a table we need to create records into the guru_test


table using insert query, which is shown below:

The records entered here are:

• 1 and guru emp1

• 2 and guru emp2


MySql>INSERT INTO `couch_tomato_db`.`guru_test` (`emp_id`,
`emp_name`) VALUES ('1', 'guru emp1');

Query OK, 1 row affected (0.05 sec)

MySQL>INSERT INTO `couch_tomato_db`.`guru_test` (`emp_id`,


`emp_name`) VALUES ('2', 'guru emp2');

Query OK, 1 row affected (0.05 sec)

JSP Operations: Insert, Update, Delete, Select:

Using JSP, we can do multiple operations into the database. We can


insert the records, and also, we can delete the records which are not
required. If any record needs to be edited, then we can do using an update.
The Selectoperation will help to fetch the records which are required.

Select:

The Select operation is used to select the records from the table.

Example:

In this example, we are going to learn about the select operation of


fetching records from guru_test table which was created in the above
section.

<%@ page import="java.io.*,java.util.*,java.sql.*"%>

<%@ page import="javax.servlet.http.*,javax.servlet.*" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-
1">

<title>Guru Database JSP1</title>

</head>

<body>.

<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"

url="jdbc:mysql://localhost/GuruTest"

user="gururoot" password="guru"/>

<sql:query dataSource="${snapshot}" var="result">

SELECT * from guru_test;

</sql:query>

<table>

<tr>

<th>Guru ID</th>

<th>Name</th>

</tr>

<c:forEach var="row" items="${result.rows}">

<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:

Insert operator is used to insert the records into the database.

Example:

In this example, we are going to learn about inserting the records in the
table guru_test

<%@ page import="java.io.*,java.util.*,java.sql.*"%>

<%@ page import="javax.servlet.http.*,javax.servlet.*" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-


1">

<title>Guru Database JSP1</title>

</head>

<body>

<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"

url="jdbc:mysql://localhost/GuruTest"

user="gururoot" password="guru"/>
<gurusql:update dataSource="${guru}" var="guruvar">

INSERT INTO guru_test VALUES (3, 'emp emp3');

</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.

1. <%@ page import="java.io.*,java.util.*,java.sql.*"%>

2. <%@ page import="javax.servlet.http.*,javax.servlet.*" %>

3. <%@ taglib uri="http://java.sun.com/jsp/jstl/core"


prefix="gurucore"%>

4. <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>

5. <%@ page language="java" contentType="text/html; charset=ISO-


8859-1"

6. pageEncoding="ISO-8859-1"%>

7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">

8. <html>

9. <head>

10. <meta http-equiv="Content-Type" content="text/html; charset=ISO-


8859-1">

11. <title>Guru Database JSP1</title>


12. </head>

13. <body>

15. <gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"

16. url="jdbc:mysql://localhost/GuruTest"

17. user="gururoot" password="guru"/>

18. <gurucore:set var="guruid" value="3"/>

19. <gurusql:update dataSource="${guru}" var="guruvar">

20. DELETE FROM guru_test WHERE emp_id = ?

21. <gurusql:param value="${guruid}" />

22. </gurusql:update>

23. </body>

24. </html>

Output:

When you execute the above code, the record with emp_id as 3 is
deleted.

Update:

The update is used to edit the records in the table.

Example:

<%@ page import="java.io.*,java.util.*,java.sql.*"%>

<%@ page import="javax.servlet.http.*,javax.servlet.*" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="gurucore"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="gurusql"%>

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"


"http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-


1">

<title>Guru Database JSP1</title>

</head>

<body>

<gurusql:setDataSource var="guru" driver="com.mysql.jdbc.Driver"

url="jdbc:mysql://localhost/GuruTest"

user="gururoot" password="guru"/>

<gurucore:set var="guruid" value="2"/>

<gurusql:update dataSource="${guru}" var="guruvar">

UPDATE guru_test SET emp_name='emp guru99'

<gurusql:param value="${guruid}" />

</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".

You might also like