[go: up one dir, main page]

0% found this document useful (0 votes)
11 views95 pages

Unit 3 Notes

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

Unit 3 Notes

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

22UAD502 FULL STACK DEVELOPMENT UNIT III

UNIT III-SERVER SIDE PROGRAMMING

Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions- Session
Handling- Understanding Cookies-DATABASE CONNECTIVITY: JDBC

SERVLETS

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

Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common
Gateway Interface) scripting language was popular as a server-side programming language. But
there were many disadvantages of this technology.

Servlet can be described in many ways, depending on the context.

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


• Servlets are small Java programs that run inside servers.
• Servlet is an API that provides many interfaces and classes including documentations.
• Servlet is an interface that must be implemented for creating any servlet.
• Servlet is a class that extends the capabilities of the servers and responds to the incoming request.
It can respond to any type of requests.

1
22UAD502 FULL STACK DEVELOPMENT UNIT III

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

CGI (Common Gateway Interface)

CGI(Common Gateway Interface) programming was used to create web applications. Here's how a
CGI program works :

• User clicks a link that has URL to a dynamic page instead of a static page.
• The URL decides which CGI program to execute.
• Web Servers run the CGI program in separate OS shell. The shell includes OS environment and
the process to execute code of the CGI program.
• The CGI response is sent back to the Web Server, which wraps the response in an HTTP response
and send it back to the web browser.

Drawbacks of CGI programs

• High response time because CGI programs execute in their own OS shell.
• CGI is not scalable.
• CGI programs are not always secure or object-oriented.
• It is Platform dependent.

Because of these disadvantages, developers started looking for better CGI solutions. And then Sun
Microsystems developed Servlet as a solution over traditional CGI technology.

Advantages of using Servlets

2
22UAD502 FULL STACK DEVELOPMENT UNIT III

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


• Servlets are scalable.
• Servlets are robust and object oriented.
• Servlets are platform independent.

HTTP (Hyper Text Transfer Protocol)

1. Http is the protocol that allows web servers and browsers to exchange data over the web.
2. It is a request response protocol.
3. Http uses reliable TCP connections bydefault on TCP port 80.
4. It is stateless means each request is considered as the new request. In other words, server doesn't
recognize the user bydefault.

Http Request Methods

Every request has a header that tells the status of the client. There are many request methods. Get
and Post requests are mostly used.

The http request methods are:

HTTP
Description
Request

GET Asks to get the resource at the requested URL.

3
22UAD502 FULL STACK DEVELOPMENT UNIT III

Asks the server to accept the body info attached. It is like GET request with extra
POST
info sent with the request.

Asks for only the header part of whatever a GET would return. Just like GET but
HEAD
with no body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

Asks for a list of the HTTP methods to which the thing at the request URL can
OPTIONS
respond

Container

It provides runtime environment for JavaEE (j2ee) applications.

Operations of Container:

• Life Cycle Management

• Communication Support

• Multithreaded support

• Security etc.
1. Life cycle management: Servlet and JSP are dynamic resources of java based web application.
The Servlet or JSP will run on a server and at server side. A container will take care about life
and death of a Servlet or JSP. A container will
instantiate, Initialize, Service and destroy of a Servlet or JSP. It means life cycle will be managed
by a container.

4
22UAD502 FULL STACK DEVELOPMENT UNIT III

2. Communication Support: If Servlet or JSP wants to communicate with server than its need
some communication logic like socket programming. Designing communication logic is increase
the burden on programmers, but container act as a mediator between a server and a Servlet or JSP
and provides communication between them.
3. Multithreading: A container creates a thread for each request, maintains the thread and finally
destroys it whenever its work is finished.
4. Security: A programmer is not required to write security code in a Servlet/JSP. A container will
automatically provide security for a Servlet/JSP.

Server

It is a running program or software that provides services.

There are two types of servers:

1. Web Server
2. Application Server

Web Server

Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It
can't be used for EJB.

Example of Web Servers are: Apache Tomcat and Resin.

Application Server

Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb
etc.

Example of Application Servers are:

1. JBoss Open-source server from JBoss community.


2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic provided by Oracle. It more secured.

5
22UAD502 FULL STACK DEVELOPMENT UNIT III

4. Websphere provided by IBM.

Content Type

Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP
header that provides the description about what are you sending to the browser.

There are many content types:

• text/html • application/pdf
• text/plain • application/octet-stream
• application/msword • application/x-zip
• application/vnd.ms-excel • images/jpeg
• application/jar • video/quicktime etc.

How a Servlet Application works

Web container is responsible for managing execution of servlets and JSP pages for Java EE
application.

When a request comes in for a servlet, the server hands the request to the Web Container.

Web Container is responsible for instantiating the servlet or creating a new thread to handle the
request. Its the job of Web Container to get the request and response to the servlet. The container
creates multiple threads to process multiple requests to a single servlet.

Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance.

1. User sends request for a servlet by clicking a link that has URL to a servlet.

6
22UAD502 FULL STACK DEVELOPMENT UNIT III

2. The container finds the servlet using deployment descriptor and creates two objects :
a. HttpServletRequest
b. HttpServletResponse

3. Then the container creates or allocates a thread for that request and calls the Servlet's service()
method and passes the request, response objects as arguments.

4. The service() method, then decides which servlet method, doGet() or doPost() to call, based on
HTTP Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP GET
request, so the service() will call Servlet's doGet() method.

7
22UAD502 FULL STACK DEVELOPMENT UNIT III

5. Then the Servlet uses response object to write the response back to the client.

6. After the service() method is completed the thread dies. And the request and response objects
are ready for garbage collection.

Difference between Applet and Servlet

Applets

• Applets are applications designed to be transmitted over the network and executed by Java
compatible web browsers.
• An Applet is a client side java program that runs within a Web browser on the client
machine.
• An applet can use the user interface classes like AWT or Swing.

8
22UAD502 FULL STACK DEVELOPMENT UNIT III

• Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy()

Servlets

• Servlets are Java based analog to CGI programs, implemented by means of servlet container
associated with an HTTP server.
• Servlet is a server side component which runs on the web server.
• The servlet does not have a user interface.
• Servlet Methods: doGet(), doPost()

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

The init() method :


The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. 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.

The init method definition looks like this:

9
22UAD502 FULL STACK DEVELOPMENT UNIT III

publicvoidinit()throwsServletException{// 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:

publicvoid service(ServletRequest request,ServletResponse response)

throwsServletException,IOException{

The service () method is called by the container and service method invokes doGe, 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.

publicvoiddoGet(HttpServletRequest request,

HttpServletResponse response)

throwsServletException,IOException{

// Servlet code}

10
22UAD502 FULL STACK DEVELOPMENT UNIT III

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.

publicvoiddoPost(HttpServletRequest request,

HttpServletResponse response)

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

publicvoid destroy(){

// Finalization code...

SERVLET ARCHITECTURE
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.

11
22UAD502 FULL STACK DEVELOPMENT UNIT III

• Then the servlet container handles multiple requests by spawning multiple threads, each thread
executing the service() method of a single instance of the servlet.

A servlet is a Java class that can be loaded dynamically into and run by a special web server. This
servlet-aware web server is called servlet container, which is also called a servlet engine in the early
days of the servlet technology.

Servlets interact with clients via request-response model based on HTTP. Because servlet technology
works on top of HTTP, a servlet container must support HTTP as the protocol for client requests and
server responses. However, a servlet container also supports similar protocols such as HTTPS for
secure transaction.

STEPS TO CREATE SERVLET APPLICATION USING TOMCAT SERVER


To create a Servlet application you need to follow the below mentioned steps. These steps are common
for all the Web server. In our example we are using Apache Tomcat server. Apache Tomcat

12
22UAD502 FULL STACK DEVELOPMENT UNIT III

is an open source web server for testing servlets and JSP technology. Download latest version
of Tomcat Server and install it on your machine.

After installing Tomcat Server on your machine follow the below mentioned steps :

1. Create directory structure for your application.


2. Create a Servlet
3. Compile the Servlet
4. Create Deployement Descriptor for your application
5. Start the server and deploy the application

All these 5 steps are explained in details below, lets create our first Servlet Application.
1. Creating the Directory Structure

Sun Microsystem defines a unique directory structure that must be followed to create a servlet
application.

Create the above directory structure inside Apache-Tomcat\webapps directory. All HTML, static
files(images, cssetc) are kept directly under Web application folder. While all the Servlet classes
are kept inside classes folder.

The web.xml (deployement descriptor) file is kept under WEB-INF folder.

Creating a Servlet

There are three different ways to create a servlet.


13
22UAD502 FULL STACK DEVELOPMENT UNIT III

• By implementing Servlet interface


• By extending GenericServlet class
• By extending HttpServlet class

But mostly a servlet is created by extending HttpServlet abstract class. As discussed


earlier HttpServlet gives the definition of service() method of the Servlet interface. The servlet
class that we will create should not override method. Our servlet class will override
service()
only doGet() or doPost() method.

When a request comes in for the servlet, the Web Container calls the servlet's service() method and
depending on the type of request the service() method calls either
the doGet() or doPost() method.

NOTE: By default a request is Get request.


importjavax.servlet.*;

importjavax.servlet.http.*;

import java.io.*;

publicMyServletextendsHttpServlet

public void doGet(HttpServletRequestrequest,HttpServletResposne response)

throwsServletException

response.setContentType("text/html");

PrintWriterout = response.getWriter();

out.println("<html><body>");

out.println("<h1>Hello Readers</h1>");

out.println("</body></html>"); }}

Write above code in a notepad file and save it as MyServlet.java anywhere on your PC. Compile
it(explained in next step) from there and paste the class file into WEB-INF/classes/ directory that
you have to create inside Tomcat/webapps directory.

14
22UAD502 FULL STACK DEVELOPMENT UNIT III

Compiling a Servlet

To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache
Tomcat server servlet-api.jar file is required to compile a servlet class.

Steps to compile a Servlet

• Set the Class Path.

• Download servlet-api.jar file.


• Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.

• Compile the Servlet class.

15
22UAD502 FULL STACK DEVELOPMENT UNIT III

NOTE: After compiling your Servlet class you will have to paste the class file into WEB-
INF/classes/ directory.

Create Deployment Descriptor

Deployment Descriptor(DD) is an XML document that is used by Web Container to run Servlets
and JSP pages. DD is used for several important purposes such as:

• Mapping URL to Servlet class.


• Initializing parameters.
• Defining Error page.
• Security roles.
• Declaring tag libraries.

We will discuss about all these in details later. Now we will see how to create a simple web.xml file
for our web application.

16
22UAD502 FULL STACK DEVELOPMENT UNIT III

Start the Server

Double click on the startup.bat file to start your Apache Tomcat Server.

Or, execute the following command on your windows machine using RUN prompt.
C:\apache-tomcat-7.0.14\bin\startup.bat
Starting Tomcat Server for the first time

If you are starting Tomcat Server for the first time you need to set JAVA_HOME in the Enviroment
variable. The following steps will show you how to set it.

• Right Click on My Computer, go to Properites.

17
22UAD502 FULL STACK DEVELOPMENT UNIT III

• Go to Advanced Tab and Click on Environment Variables... button.

• Click on New button, and enter JAVA_HOME inside Variable name text field and path of JDK
inside Variable value text field. Click OK to save.

18
22UAD502 FULL STACK DEVELOPMENT UNIT III

Run Servlet Application

Open Browser and type http:localhost:8080/First/hello

Hurray! Our first Servlet Application ran successfully.

SERVLET API
There are two packages used to implement the Servlet. These packages are:

o javax.servlet
o javax.servlet.http

19
22UAD502 FULL STACK DEVELOPMENT UNIT III

The javax.servlet package

• To implement the servlet


• Out of many other interfaces and classes defined in this package the most important
interface is Servlet.
• Contains many interfaces and classes that are used by the servlet or web container. These
are not specific to any protocol.
• All the servlet must implement this interface.

Interfaces in javax.servlet package

Interface Description
Servlet This interface defines all the lifecycle methods
ServletConfig This interface obtains the initialization parameters
ServletContext Using this interface the events can be logged
ServletRequest This interface is useful in reading the data from the client
request.
ServletResponse This interface is useful in writing the data to the client request.

Servlets Interface

Servlet interface provides common behavior to all the servlets.Servlet interface needs to be
implemented for creating any servlet (either directly or indirectly). It provides 3 life cycle methods

20
22UAD502 FULL STACK DEVELOPMENT UNIT III

that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life
cycle methods.

Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of
servlet. These are invoked by the web container.

Method Description

public void init(ServletConfigconfig) initializes the servlet. It is the life


cycle method of servlet and
invoked by the web container only

public void provides response for the incoming


service(ServletRequestrequest,ServletResponse request. It is invoked at each
public void destroy() is invoked only once and indicates
that servlet is being destroyed.
public ServletConfiggetServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet


such as writer, copyright, version

The ServletConfig Interface

An object of ServletConfig is created by the web container for each servlet using its initialization
phase. This object can be used to get configuration information from web.xml file.

Method Description
Enumeration getInitParameterNames() Returns an enumeration of all the initialization
parameter names.
String getServletName() Returns the name of the Servlet
String getInitParameter(String name) Returns the parameter value for the
specified parameter name.

21
22UAD502 FULL STACK DEVELOPMENT UNIT III

ServletContextgetServletContext() Returns an object of ServletContext.

The ServletContext Interface

ServletContext is one of pre-defined interface available in javax.servlet.*; Object of ServletContext


interface is available one per web application. An object of ServletContext is automatically created by
the container when the web application is deployed.

Method Description
Object getAttribute(String attribute_name) The value of the attribute attribute_name in the
current session is returned.
void setAttribute(String attribute_name, The attribute_name is passed to the object
object value) value.
String getServerInfo( ) This method returns the information about the
server
String log(String str) Writes the str to the servlet log.
String getMimeType(String file) It returns the MIME type of the file.

The ServletRequest Interface


Method Description
Object getAttribute(String attribute_name) The value of the attribute attribute_name in the
current session is returned.
initgetContentlength( ) Returns the content size of the request
String getContentType( ) Returns the type of the request
getInputStream( ) Read the binary data from the request
getProtocol( ) Read the name of the protocol used
getReader( ) Reading the text from the request
getServerName( ) Returns the name of the server on which the
servlet is running
initgetServerPort( ) Returns the port number of the servlet

22
22UAD502 FULL STACK DEVELOPMENT UNIT III

The ServletResponse Interface

Method Description
String getCharacterEncoding( ) Returns the character encoding
ServletOutputStreamgetOutputStream( ) Returns the output stream which is used to
write the data for responding
PrintWritergetWriter( ) Write the character data to the response
void setContentLength(int size) Sets the length of the content equal to the size.
void setContentLength(String Type) Sets the type of the content

Classes in javax.servlet package

There are many classes in javax.servlet package. They are as follows:

Class Description

GenericServlet Implements the Servlet and ServletConfig interfaces

ServletInputStream Provides the input stream for reading the client’s request

ServletOutputStream Provides the output stream for reading the client’s request

ServletException Raise the exception when an error occurs

The javax.servlet.http

The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.

Interface Description
HttpSession Session data can be read or written using this interface
HttpServletRequest Servlet can read the information from the HTTP request using
this information

23
22UAD502 FULL STACK DEVELOPMENT UNIT III

HttpServletResponse Servlet can write the information to HTTP response using this
interface
HttpSessionBindingListener Tells the object about its binding with the particular session

HttpSession
Method Description
String getId() Returns the session ID
ObjectgetAttribute(String attribute_name) The value of the attribute attribute_name in
the current session is returned
Enumeration getAttributeNames() Returns the attribute names

Http Servlet Request

Method Description
String getMethod( ) Returns the HTTP method for the client
request
String getPathInfo( ) Returns the path information about the servlet
path
HttpSessiongetSession() Returns the current session
String getHeader(string fields) Returns the value of header field
Cookie[ ] getCookies() Returns the information in the cookies in the
request made
String getAuth Type() Returns the type of authentication

Http Servlet Response


Method Description
Void addCookie(Cookie cookie) This method is used to add cookie in the
response
String encodeURL(String url) This method is used to encode the specified
URL
Boolean containsHeader(String f) This method returns TRUE if the response
header contains the field f.
Void sendError(int code) This method sends error code to the client.

24
22UAD502 FULL STACK DEVELOPMENT UNIT III

HttpSessionbindinglistener

Method Description
Object getValue() This function returns the value of
bounded or unbounded attribute.
String getName() This function returns the name being bound or
unbound.
HttpSessiongetSession() This function returns the session to which the
listener can be bound or unbound.

Classes

Class Description
Cookie This class is used to write the cookies.
Http Servlet It is used when developing servlet that
receive and process the HTTP request.
HttpSessionEvent This class is used to handle the session
event.
HttpSessionBindingEvent When a listener is bound to a value.

1. The Cookie class

Class Description
String getValue() This function returns a value of the cookie.
Void setValue(String s) This function sets the value to the cookie.
String getName() This function returns the name.

2. TheHttpServlet class

Class Description
Void doGet(HttpServletRequestreq, This method performs HTTP get request.
HttpServletResponse res )
Void doPost(HttpServletRequestreq, This method performs HTTP post request.
HttpServletResponse res )
Void doPut(HttpServletRequestreq, This method performs HTTP put request.
HttpServletResponse res )
Void service(HttpServletRequestreq, This method is invoked for processing
HttpServletResponse res ) HTTP request and response.

3. TheHttpSessionEvent:

This method encapsulates the session event.

25
22UAD502 FULL STACK DEVELOPMENT UNIT III

4. HttpSessionBindingEvent:

The HttpSessionBindingEvent class extends HttpSessionEvent.It is generated when a


listener is bound to a value. The getSession() method obtains the session to which the listener
is being bound or unbound.

Servlet Example by implementing Servlet interface

Let's see the simple example of servlet by implementing the servlet interface.

File: First.java

import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

26
22UAD502 FULL STACK DEVELOPMENT UNIT III

FORM GET AND POSTACTIONS

The browser uses two methods to pass this information to web server. These methods are GET
Method and POST Method.

GET method:
The GET method sends the encoded user information appended to the page request. The page and
the encoded information are separated by the ?character as follows:

http://www.test.com/hello?key1=value1&key2=value2

The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box. Never use the GET method if
you have password or other sensitive information to pass to the server. The GET method has size
limitation: only 1024 characters can be in a request string.

This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using doGet()
method.

Anatomy of Get Request

As we know that data is sent in request header in case of get request. It is the default request type.
Let's see what informations are sent to the server.

POST method:
A generally more reliable method of passing information to a backend program is the POST method.
This packages the information in exactly the same way as GET methods, but instead of
27
22UAD502 FULL STACK DEVELOPMENT UNIT III

sending it as a text string after a ?in the URL it sends it as a separate message. This message comes
to the backend program in the form of the standard input which you can parse and use for your
processing. Servlet handles this type of requests using doPost()method.

Reading Form Data using Servlet:


Servlets handles form data parsing automatically using the following methods depending on the
situation:

• getParameter(): You call request.getParameter() method to get the value of a form


parameter.

• getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.

• getParameterNames(): Call this method if you want a complete list of all parameters in the
current request.

Anatomy of Post Request

As we know, in case of post request original data is sent in message body. Let's see how informations
are passed to the server in case of post request.

GET Method Example Using URL:

28
22UAD502 FULL STACK DEVELOPMENT UNIT III

Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI
Below is HelloForm.java servlet program to handle input given by web browser. We are going to
use getParameter() method which makes it very easy to access passed information:

importjava.io.IOException;

importjava.io.PrintWriter;

importjavax.servlet.ServletException;

importjavax.servlet.http.HttpServlet;

importjavax.servlet.http.HttpServletRequest;

importjavax.servlet.http.HttpServletResponse;

public class HelloFormData extends HttpServlet {

private static final long serialVersionUID = 1L;

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String title = "Servlet: Read Form Data";

out.println("<html>" + "<head><title>" + title

+ "</title></head><body>"

+ "<h1>" + title + "</h1>"

+ "<p>Hi "

+ request.getParameter("name")

+ "</p>"

Web.xml

This web.xml defines the Servlet mapping for the form data servlet.

<web-app xmlns=http://java.sun.com/xml/ns/j2ee

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

29
22UAD502 FULL STACK DEVELOPMENT UNIT III

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-
app_2_4.xsd"

version="2.4">

<display-name>Servlet Form Data Handling</display-name>

<servlet>

<servlet-name>HelloFormData</servlet-name>

<servlet-class>HelloFormData</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>HelloFormData</servlet-name>

<url-pattern>/hello</url-pattern>

</servlet-mapping>

</web-app>

index.html

<!DOCTYPE html>

<html>

<head>

<title>Servlet Read Form Data</title>

</head>

<body>

30
22UAD502 FULL STACK DEVELOPMENT UNIT III

<form action="./hello" method="GET">

Enter your Name: <input type="text" name="name">

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

</form>

</body>

</html>

Read using POST method

In the above HTML page in form tag instead of GET use as POST. Then in the servlet to read the
form data add a doPost method as below,

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throwsServletException, IOException {

doGet(request, response); }

What is the difference between Get and Post?

31
22UAD502 FULL STACK DEVELOPMENT UNIT III

There are many differences between the Get and Post request. Let's see these differences:

GET POST
1) In case of Get request, only limited amount of In case of post request, large amount of data can be
data can be sent because data is sent in header. sent because data is sent in body.
2) Get request is not secured because data is Post request is secured because data is not exposed
exposed in URL bar. in URL bar.
3) Get request can be bookmarked Post request cannot be bookmarked
4) Get request is idempotent. It means second
request will be ignored until response of first request Post request is non-idempotent
is delivered.
5) Get request is more efficient and used more than
Post request is less efficient and used less than get.
Post

SESSION HANDLING

Session simply means a particular interval of time.

Session Tracking is a mechanism used by Webcontainer to maintain state (data) of a user. It is also
known as session management in servlet.

HTTP protocol is a stateless so we need to maintain state using session tracking techniques. Each time
user requests to the server, server treats the request as the new request. So we need to maintain the
state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure
given below:

Why use Session Tracking?

32
22UAD502 FULL STACK DEVELOPMENT UNIT III

✓ Http protocol is stateless, to make stateful between client and server we need Session
Tracking.

✓ Session Tracking is useful for online shopping, mailing application, E-Commerce


application to track the conversion.

✓ To recognize the user it is used to recognize the particular user.

How Session Works

The basic concept behind session is, whenever a user starts using our application, we can save a unique
identification information about him, in an object which is available throughout the application, until
its destroyed. So wherever the user goes, we will always have his information and we can always
manage which user is doing what. Whenever a user wants to exit from your application, destroy the
object with his information.

Session Tracking Techniques

33
22UAD502 FULL STACK DEVELOPMENT UNIT III

There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

1. COOKIES

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie

34
22UAD502 FULL STACK DEVELOPMENT UNIT III

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

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

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

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


2. Only textual information can be set in Cookie object.

Cookie class

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


useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.

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

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

35
22UAD502 FULL STACK DEVELOPMENT UNIT III

Method Description

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

public String getName() Returns the name of the cookie. The name cannot
be changed after creation.

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

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

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

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return
all the cookies from the browser.

How to create Cookie?

Let's see the simple code to create cookie.

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


response.addCookie(ck);//adding cookie in the response

How to delete Cookie?

Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie


ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?

Let's see the simple code to get all the cookies.

36
22UAD502 FULL STACK DEVELOPMENT UNIT III

Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name an
d value of cookie
}

37
22UAD502 FULL STACK DEVELOPMENT UNIT III

Output

38
22UAD502 FULL STACK DEVELOPMENT UNIT III

2. Hidden Form Field


Hidden form field can also be used to store session information for a particular client. In case of hidden
form field a hidden field is used to store client state. In this case user information is stored in hidden
field value and retrieved from another servlet.

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an
user.

In such case, we store the information in the hidden field and get it from another servlet. This approach
is better if we have to submit form in all the pages and we don't want to depend on the browser.

Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

1. It is maintained at server side.


2. Extra form submission is required on each pages.

39
22UAD502 FULL STACK DEVELOPMENT UNIT III

3. Only textual information can be used.

Example of using Hidden Form Field

In this example, we are storing the name of the user in a hidden textfield and getting that value from
another servlet.

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

40
22UAD502 FULL STACK DEVELOPMENT UNIT III

out.close();

}catch(Exception e){System.out.println(e);}
}

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

//Getting the value from the hidden field


String n=request.getParameter("uname");
out.print("Hello "+n);

out.close();
}catch(Exception e){System.out.println(e);}
}
}

web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

41
22UAD502 FULL STACK DEVELOPMENT UNIT III

</web-app>

3. URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next
resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated
from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to
obtain a parameter value.

Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send only textual information.

Example of using URL Rewriting

In this example, we are maintaining the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query string in
another page.

42
22UAD502 FULL STACK DEVELOPMENT UNIT III

index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

//appending the username in the query string


out.print("<a href='servlet2?uname="+n+"'>visit</a>");

out.close();

}catch(Exception e){System.out.println(e);}
}

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

//getting value from the query string


String n=request.getParameter("uname");

43
22UAD502 FULL STACK DEVELOPMENT UNIT III

out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
}

web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>

</web-app>

4. HttpSession

HttpSession object is used to store entire session with a specific client. We can store, retrieve and
remove attribute from HttpSession object. Any servlet can have access to HttpSession object
throughout the getSession() method of the HttpServletRequest object.

44
22UAD502 FULL STACK DEVELOPMENT UNIT III

How HttpSession works

1. On client's first request, the Web Container generates a unique session ID and gives it back to
the client with response. This is a temporary session created by web container.
2. The client sends back the session ID with each request. Making it easier for the web container to
identify where the request is coming from.
3. The Web Container uses this ID, finds the matching session with the ID and associates the
session with the request.

How to get the HttpSessionobject ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. publicHttpSessiongetSession():Returns the current session associated with this request, or if


the request does not have a session, creates one.
2. publicHttpSessiongetSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.

45
22UAD502 FULL STACK DEVELOPMENT UNIT III

3. public long getLastAccessedTime():Returns the last time the client sent a request associated
with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession

In this example, we are setting the attribute in the session scope in one servlet and getting that value
from the session scope in another servlet. To set the attribute in the session scope, we have used the
setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute
method.

index.html

<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

out.print("<a href='servlet2'>visit</a>");

out.close();

}catch(Exception e){System.out.println(e);}
}

46
22UAD502 FULL STACK DEVELOPMENT UNIT III

SecondServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);

out.close();

}catch(Exception e){System.out.println(e);}
}

web.xml

<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>

47
22UAD502 FULL STACK DEVELOPMENT UNIT III

</servlet-mapping>

</web-app>

INSTALLING AND CONFIGURING APACHE TOMCAT WEB SERVER

This section will show the process to install and configure Tomcat 6 on your computer system.

Step 1:

Installation of JDK:

Before beginning the process of installing Tomcat on your system, ensure first the availability of JDK
on your system program directory. Install it on your system if not already installed (because any
version of tomcat requires the Java 1.6 or higher versions) and then set the class path (environment
variable) of JDK. To set the JAVA_HOME Variable: you need to specify the location of the java
run time environment to support the Tomcat else Tomcat server cannot run.

This variable contains the path of JDK installation directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6

Note: it should not contain the path up to bin folder. Here, we have taken the URL path according to
our installation convention.
For Windows OS, go through the following steps:

Start menu->Control Panel->System->Advanced tab->Environment Variables->New->set the


Variable name = JAVA_HOME and variable value = C:\Program Files\Java\jdk1.6

Now click on all the subsequent ok buttons one by one. It will set the JDK path.

Step 2:

For setting the class path variable for JDK, do like this:

Start menu->Control Panel->System->Advanced tab->Environment Variables->New->


Set PATH="C:\Program Files\Java\jdk1.6\bin"; %PATH%
OR

48
22UAD502 FULL STACK DEVELOPMENT UNIT III

First, right click on the

My Computer->properties->advance->Environment Variables->path.
Now, set bin directory path of JDK in the path variable

Step 3:

The process of installing Tomcat 6.0 begins here from now. It takes various steps for installing and
configuring the Tomcat 6.0.

For Windows OS, Tomcat comes in two forms: .zip file and .exe file (the Windows installer file).
Here we are exploring the installation process by using the .exe file. First unpack the zipped file and
simply execute the '.exe' file.

A Welcome screen shot appears that shows the beginning of installation process. Just click on the
'Next' button to precede the installation process.

Steps 4:

A screen of 'License Agreement' displays.

49
22UAD502 FULL STACK DEVELOPMENT UNIT III

Click on the 'I Agree' button.

Step 5:

A screen shot appears asking for the 'installing location'

Choose the default components and click on the 'Next' button.

Step 6:

A screen shot of 'Configuration Options' displays on the screen. Choose the location for the Tomcat
files as per your convenience. You can also select the default Location

50
22UAD502 FULL STACK DEVELOPMENT UNIT III

The port number will be your choice on which you want to run the tomcat server. The port number
8080 is the default port value for tomcat server to proceed the HTTP requests. The user can also
change the 'port number' after completing the process of installation; for this, users have to follow the
following tips.

Go to the specified location as " Tomcat 6.0 \conf \server.xml ". Within the server.xml file choose
"Connector" tag and change the port number.

Now, click on the 'Next' button to further proceed the installation process.

Step 7:

A Window of Java Virtual Machine displays on the screen

51
22UAD502 FULL STACK DEVELOPMENT UNIT III

This window asks for the location of the installed Java Virtual Machine. Browse the location of the
JRE folder and click on the Install button. This will install the Apache tomcat at the specified location.

Step 8:

A processing window of installing displays on the screen.

To get the information about installer click on the "Show details" button

Step 9:

A screen shot of 'Tomcat Completion' displays on the screen.

Click on the 'Finish' button.

52
22UAD502 FULL STACK DEVELOPMENT UNIT III

Step 10:

A window of Apache Service Manager appears with displaying the running process.

Let the running process goes on.

Step 11:

After completing the installation process, the Apache Tomcat Manager appears on the toolbar panel
like shown in the below picture.

Configuring Tomcat Manager

To Configure the Tomcat Manager, there are two ways; either user can configure Tomcat directly
from the toolbar panel or can configure it from Control Panel Section.

i) Configuring from toolbar Panel

To Configure Apache Tomcat web server from the toolbar panel, you have to press 'double click' on
the appeared icon.

53
22UAD502 FULL STACK DEVELOPMENT UNIT III

A configured window appears on the desktop. Now, just click on the Startup button. The installation
process will be completed.

ii) Configuration from the Control Panel

To configure the Apache Tomcat Manager, Users will have to follow the follwing steps:

Click on the Startup button -- select Control Panel -- Administrator Tool -- Services -- select Apache
Tomcat.

The following screen displays on the monitor.

Double click on the Apache Tomcat. The window of Apache Tomcat Properties appears on the
screen.

54
22UAD502 FULL STACK DEVELOPMENT UNIT III

Now, Click on the start up button. The Apache Tomcat is now ready to function.

To operate it, follow the below steps of processing.

Start the Tomcat Server:

1. Start the tomcat server from the bin folder of Tomcat 6.0 directory by double clicking the
"tomcat6.exe" file.
OR create a shortcut of this .exe file at your desktop.
2. Now Open web browser and type URL http://localhost:8080 in the address bar to test the server
3. To Stop the Tomcat Server: Stop the server by pressing the "Ctrl + c" keys.

The screen of Apache Tomcat software looks like this:

55
22UAD502 FULL STACK DEVELOPMENT UNIT III

DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example

JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to
connect with the database.

Why use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with the database.
But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and
unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written
in Java language).

56
22UAD502 FULL STACK DEVELOPMENT UNIT III

What is API?

API (Application programming interface) is a document that contains description of all the features
of a product or software. It represents classes and interfaces that software programs can follow to
communicate with each other. An API can be created for applications, libraries, operating systems,
etc

JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −

• JDBC API: This provides the application-to-JDBC Manager connection.

• JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.

The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.

Following is the architectural diagram, which shows the location of the driver manager with respect
to the JDBC drivers and the Java application −

57
22UAD502 FULL STACK DEVELOPMENT UNIT III

Common JDBC Components


The JDBC API provides the following interfaces and classes −

• DriverManager: This class manages a list of database drivers. Matches connection requests
from the java application with the proper database driver using communication sub protocol.
The first driver that recognizes a certain subprotocol under JDBC will be used to establish a
database Connection.

• Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use DriverManager objects, which
manage objects of this type. It also abstracts the details associated with working with Driver
objects.

• Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through
connection object only.

• Statement: You use objects created from this interface to submit the SQL statements to the
database. Some derived interfaces accept parameters in addition to executing stored
procedures.

• ResultSet: These objects hold data retrieved from a database after you execute an SQL query
using Statement objects. It acts as an iterator to allow you to move through its data.

• SQLException: This class handles any errors that occur in a database application.

JDBC Driver is a software component that enables java application to interact with the
database.There are 4 types of JDBC drivers:
1. JDBC-ODBC bridge driver
2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC
bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged
because of thin driver.

58
22UAD502 FULL STACK DEVELOPMENT UNIT III

Advantages:

• easy to use.
• can be easily connected to any database.

Disadvantages:

• Performance degraded because JDBC method call is converted into the ODBC function calls.
• The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Advantage:

59
22UAD502 FULL STACK DEVELOPMENT UNIT III

• performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

• The Native driver needs to be installed on the each client machine.


• The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls directly
or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
• No client side library is required because of application server that can perform many tasks
like auditing, load balancing, logging etc.

Disadvantages:

• Network support is required on client machine.


• Requires database-specific coding to be done in the middle tier.
• Maintenance of Network Protocol driver becomes costly because it requires database-specific
coding to be done in the middle tier.

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.

60
22UAD502 FULL STACK DEVELOPMENT UNIT III

Advantage:

• Better performance than all other drivers.


• No software is required at client side or server side.

Disadvantage:

• Drivers depends on the Database.

EXAMPLE PROGRAM ON SERVLET WITH DATABASE CONNECTIVITY

▪ Download Jar and save to lib folder of Apache (ojdbc14-1.0.jar Required):


▪ Update Classpath to following (Path in Bold are new): C:\Program Files\Apache Software
Foundation\Tomcat 7.0\lib\servlet-api.jar;C:\Program Files\Apache Software
Foundation\Tomcat 7.0\lib\jsp-api.jar;C:\Program Files\Apache Software Foundation\Tomcat
7.0\lib\ojdbc14-1.0.jar;C:\Program Files\Apache Software Foundation\Tomcat
7.0\lib\ com.mysql.jdbc_5.1.5.jar;.
▪ Download and Install MySQL.
First Create Your Database and Tables
Table Name: student

FieldName Type

Sid number(10) Primary Key

61
22UAD502 FULL STACK DEVELOPMENT UNIT III

Sname varchar2(20)

Hello JDBC MySQL using Servlet Example

FilePath : C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\example03\WEB-


INF\classes
ex03.java
importjava.io.IOException;
importjava.io.PrintWriter;
importjava.sql.Connection;
importjava.sql.DriverManager;
importjava.sql.ResultSet;
importjava.sql.Statement;
importjavax.servlet.ServletException;
importjavax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

public class ex03 extends HttpServlet


{
protected void doGet(HttpServletRequestreq,HttpServletResponse
res)throws ServletException,IOException
{
PrintWriter pw=res.getWriter();
res.setContentType("text/html");
String tb="student";
pw.println("Initializing Connection ... ");

try
{

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","adars
h","patel");
Statement st=con.createStatement();
pw.println("connection established successfully...!!");
ResultSetrs=st.executeQuery("Select * from "+tb);
pw.println("<table border=1>");

while(rs.next())
{

pw.println("<tr><td>"+rs.getInt(1)+"</td><td>"+rs.getString(2)+"</td>"+"<
/tr>");
}
pw.println("</table>");
pw.close();

62
22UAD502 FULL STACK DEVELOPMENT UNIT III

}
catch (Exception e)
{
pw.println("The error is:" + e.getMessage());
} }}

Hello JDBC using Servlet Example Explanation:

Line :Class.forName(“com.mysql.jdbc.Driver “);


Explanation : This Line if to load Driver for MySQL Database Connectivity with Java Servlet.

Line: Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,”root”,””);


Explanation : This Line is most important as it contains userid and password of MySQL. Here I
have used userid :adarsh and password : patel. Only 2 Fields you need to change is userid and
password. (Default userid for MySQL is root and password is blank);
FilePath : C:\Program Files\ApacheSoftwareFoundation\Tomcat
7.0\webapps\example03\WEB-INF\

web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>


<web-app>
<display-name>Example 02 </display-name>
<description> JDBC Using Servlet </description>
<servlet>
<servlet-name>ex03</servlet-name>
<servlet-class>ex03</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ex03</servlet-name>
<url-pattern>/ex03</url-pattern>
</servlet-mapping></web-app>

63
22UAD502 FULL STACK DEVELOPMENT UNIT III
UNIT III
SERVER SIDE PROGRAMMING

JSP: Understanding Java Server Pages-JSP Standard Tag Library(JSTL)-Creating HTML forms by
embedding JSP code.

JSP DEFINITION:
• Java Server Pages (JSP) is a server-side programming technology that enables the creation
of dynamic, platform-independent method for building Web-based applications.
• JSP technology is used to create web application just like Servlet technology. It can be
thought of as an extension to servlet because it provides more functionality than servlet such
as expression language, JSTL, etc.
• A JSP page consists of HTML tags and JSP tags. The jsp pages are easier to maintain than
servlet because we can separate designing and development. It provides some additional
features such as Expression Language, Custom Tag etc.

Advantage of JSP over Servlet

There are many advantages of JSP over servlet. They are as follows:

1) Extension to Servlet
JSP technology is the extension to servlet technology. We can use all the features of servlet in
JSP. In addition to, we can use implicit objects, predefined tags, expression language and
Custom tags in JSP which makes JSP development easy.

2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with presentation
logic. In servlet technology, we mix our business logic with the presentation logic.

3) Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code
needs to be updated and recompiled if we have to change the look and feel of the application.

4) Less code than Servlet


In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code.
Moreover, we can use EL, implicit objects etc.

Why Use JSP?


• JavaServer Pages often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.
• Performance is significantly better because JSP allows embedding Dynamic Elements in
HTML Pages itself instead of having a separate CGI files.
• JSP are always compiled before it's 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.
22UAD502 FULL STACK DEVELOPMENT UNIT III
• JSP pages can be used in combination with servlets that handle the business logic, the model
supported by Java servlet template engines.
JSP ARCHITECTURE
The web server needs a JSP engine ie. container to process JSP pages. The JSP container is
responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has
built-in JSP container to support JSP pages development.

A JSP container works with the Web server to provide the runtime environment and other services
a JSP needs. It knows how to understand the special elements that are part of JSPs.

Following diagram shows the position of JSP container and JSP files in a Web Application.

PROCESSING OF JSP
The following steps explain how the web server creates the web page using JSP:

• As with a normal page, your browser sends an HTTP request to the web server.

• The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP
engine. This is done by using the URL or JSP page which ends with .jspinstead of .html.

• The JSP engine loads the JSP page from disk and converts it into a servlet content. This
conversion is very simple in which all template text is converted to println( ) statements and
all JSP elements are converted to Java code that implements the corresponding dynamic
behavior of the page.

• The JSP engine compiles the servlet into an executable class and forwards the original request
to a servlet engine.

• A part of the web server called the servlet engine loads the Servlet class and executes it.
During execution, the servlet produces an output in HTML format, which the servlet engine
passes to the web server inside an HTTP response.

• The web server forwards the HTTP response to your browser in terms of static HTML
content.
22UAD502 FULL STACK DEVELOPMENT UNIT III
• Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.

All the above mentioned steps can be shown below in the following diagram:

• Typically, the JSP engine checks to see whether a servlet for a JSP file already exists and
whether the modification date on the JSP is older than the servlet.

• If the JSP is older than its generated servlet, the JSP container assumes that the JSP hasn't
changed and that the generated servlet still matches the JSP's contents.

• This makes the process more efficient than with other scripting languages (such as PHP)
and therefore faster.

• So in a way, a JSP page is really just another way to write a servlet without having to be a
Java programming wiz.

• Except for the translation phase, a JSP page is handled exactly like a regular servlet.

LIFECYCLE OF JSP

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

The following are the paths followed by a JSP

• Compilation

• Initialization

• Execution

• Cleanup

The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows:
22UAD502 FULL STACK DEVELOPMENT UNIT III

JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last compiled,
the JSP engine compiles the page.

The compilation process involves three steps:

• Parsing the JSP.

• Turning the JSP into a servlet.

• Compiling the servlet.

JSP Initialization:
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you
need to perform JSP-specific initialization, override the jspInit() method:

publicvoid jspInit(){
// Initialization code...
}
22UAD502 FULL STACK DEVELOPMENT UNIT III
Typically initialization is performed only once and as with the servlet init method, you generally
initialize database connections, open files, and create lookup tables in the jspInit method.

JSP Execution:
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.

Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.

The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its


parameters as follows:

void _jspService(HttpServletRequest request,


HttpServletResponse response)
{
// Service handling code...
}

The _jspService() method of a JSP is invoked once per a request and is responsible for generating
the response for that request and this method is also responsible for generating responses to all seven
of the HTTP methods ie. GET, POST, DELETE etc.

JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.

The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or closing
open files.

The jspDestroy() method has the following form:

publicvoid jspDestroy()
{
// Your cleanup code goes here.
}
22UAD502 FULL STACK DEVELOPMENT UNIT III
CONTROL-FLOW STATEMENTS:
• JSP provides full power of Java to be embedded in your web application.
• You can use all the APIs and building blocks of Java in your JSP programming including decision making
statements, loops etc.
Decision-Making Statements:
• The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text
included between Scriptlet tags.
<%!int day =3; %>
<html>
<head><title>IF...ELSE Example</title></head>
<body>
<%if(day ==1| day ==7){ %>
<p> Today is weekend</p>
<%}else{ %>
<p> Today is not weekend</p>
<%} %>
</body>
</html>
This would produce following result:
Today is not weekend

Switch Case:
Now look at the following switch...case block which has been written a bit differentlty
usingout.println() and inside Scriptletas:

<%!int day =3; %>


<html>
<head><title>SWITCH...CASE Example</title></head>
<body>
<%
switch(day){
case0:
out.println("It\'s Sunday.");
break;
case1:
out.println("It\'s Monday.");
break;
case2:
out.println("It\'s Tuesday.");
break;
case3:
out.println("It\'s Wednesday.");
break;
case4:
out.println("It\'s Thursday.");
break;
case5:
out.println("It\'s Friday.");
break;
22UAD502 FULL STACK DEVELOPMENT UNIT III
default:
out.println("It's Saturday.");
}
%>
</body>
</html>
This would produce following result:
It's Wednesday.

Loop Statements:
• You can also use three basic types of looping blocks in Java: for, while,and
do…whileblocks in your JSP programming.

Let us look at the following for loop example:

<%!int fontSize; %>


<html>
<head><title>FOR LOOP Example</title></head>
<body>
<%for( fontSize =1; fontSize <=3; fontSize++){ %>
<font color="green" size="<%= fontSize %>">
JSP Tutorial
</font><br/>
<%}%>
</body>
</html>
This would produce following result:

JSP Tutorial

JSP Tutorial

JSP Tutorial

Above example can be written using while loop as follows:

<%!int fontSize; %>


<html>
<head><title>WHILE LOOP Example</title></head>
<body>
<%while( fontSize <=3){ %>
<font color="green" size="<%= fontSize %>">
JSP Tutorial
22UAD502 FULL STACK DEVELOPMENT UNIT III
</font><br/>
<%fontSize++;%>
<%}%>
</body>
</html>
This would also produce following result:

JSP Tutorial

JSP Tutorial

JSP Tutorial

JSP Operators:

• JSP supports all the logical and arithmetic operators supported by Java.
• Following table give a list of all the operators with the highest precedence appear at the top
of the table, those with the lowest appear at the bottom.
• Within an expression, higher precedence operators will be evaluated first.

Category Operator Associativity

Postfix () [] . (dot operator) Left to right

Unary ++ - - ! ~ Right to left

Multiplicative */% Left to right

Additive +- Left to right

Shift >>>>><< Left to right

Relational >>= <<= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left


22UAD502 FULL STACK DEVELOPMENT UNIT III
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left

Comma , Left to right

JSP Literals:

The JSP expression language defines the following literals:


• Boolean: true and false
• Integer: as in Java
• Floating point: as in Java
• String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped
as \\.
• Null: null
• Null: null

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

Following is the syntax of Scriptlet:

<% code fragment %>

You can write XML equivalent of the above syntax as follows:

<jsp:scriptlet>

code fragment

</jsp:scriptlet>

JSP Scriptlet tag (Scripting elements)


1. Scripting elements
2. JSP scriptlet tag
3. Simple Example of JSP scriptlet tag
4. Example of JSP scriptlet tag that prints the user name

In JSP, java code can be written inside the jsp page using the scriptlet tag.

JSP Scripting elements

The scripting elements provide the ability to insert java code inside the jsp. There are three types of
scripting elements:
o scriptlet tag
o expression tag
22UAD502 FULL STACK DEVELOPMENT UNIT III
o declaration tag

JSP scriptlet tag

• A scriptlet tag is used to execute java source code in JSP.


• Syntax is as follows:
<% java source code %>

Example of JSP scriptlet tag

In this example, we are displaying a welcome message.


<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

Example of JSP scriptlet tag that prints the user name

• In this example, we have created two files index.html and welcome.jsp.


• The index.html file gets the username from the user and the welcome.jsp file prints the
username with the welcome message.

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

File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
JSP expression tag

• The code placed within JSP expression tag is written to the output stream of the response.
22UAD502 FULL STACK DEVELOPMENT UNIT III
• So you need not write out.print() to write data.
• It is mainly used to print the values of variable or method.

Syntax of JSP expression tag


<%= statement %>

Example of JSP expression tag

In this example of jsp expression tag, we are simply displaying a welcome message.
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>

Note: Do not end your statement with semicolon in case of expression tag.

Example of JSP expression tag that prints current time

To display the current time, we have used the getTime() method of Calendar class. The getTime() is
an instance method of Calendar class, so we have called it after getting the instance of Calendar
class by the getInstance() method.

index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

Example of JSP expression tag that prints the user name

In this example, we are printing the username using the expression tag. The index.html file gets the
username and sends the request to the welcome.jsp file, which displays the username.

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

File: welcome.jsp
<html>
22UAD502 FULL STACK DEVELOPMENT UNIT III
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
JSP Declaration Tag

• The JSP declaration tag is used to declare fields and methods.


• The code written inside the jsp declaration tag is placed outside the service() method of auto
generated servlet.
• So it doesn't get memory at each request.

Syntax of JSP declaration tag


<%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag


Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare variables not The jsp declaration tag can
methods. declare variables as well as
methods.
The declaration of scriptlet tag is placed inside the The declaration of jsp declaration
_jspService() method. tag is placed outside the
_jspService() method.

Example of JSP declaration tag that declares field

In this example of JSP declaration tag, we are declaring the field and printing the value of the
declared field using the jsp expression tag.

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

Example of JSP declaration tag that declares method

• In this example of JSP declaration tag, we are defining the method which returns the cube of
given number and calling this method from the jsp expression tag.
• But we can also use jsp scriptlet tag to call the declared method.

index.jsp
<html>
<body>
<%!
22UAD502 FULL STACK DEVELOPMENT UNIT III
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is
useful when you want to hide or "comment out" part of your JSP page.

Following is the syntax of JSP comments:

<%-- This is JSP comment --%>

There are a small number of special constructs you can use in various cases to insert comments or
characters that would otherwise be treated specially. Here's a summary:

Syntax Purpose

<%-- comment --%> A JSP comment. Ignored by the JSP engine.

<!-- comment --> An HTML comment. Ignored by the browser.

<\% Represents static <% literal.

%\> Represents static %> literal.

\' A single quote in an attribute that uses single quotes.

\" A double quote in an attribute that uses double quotes.

JSP DIRECTIVES:

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

There are three types of directives:

• page directive
• include directive
• taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>


22UAD502 FULL STACK DEVELOPMENT UNIT III
Directive Description

<%@ page ... %> Defines page-dependent attributes, such as scripting language,

<%@ include ... %> Includes a file during the translation phase.

<%@ taglib ... %> Declares a tag library, containing custom actions, used in the

1. page directive

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

<%@ page attribute="value" %>


2. include Directive:
• The include directive is used to includes a file during the translation phase.

• This directive tells the container to merge the content of other external files with the
current JSP during the translation phase.

• You may code include directives anywhere in your JSP page.

The general usage form of this directive is as follows:

<%@ include file="relative url">

The filename in the include directive is actually a relative URL. If you just specify a filename with
no associated path, the JSP compiler assumes that the file is in the same directory as your JSP.

3. taglib Directive:
• The JavaServer Pages API allows you to define custom JSP tags that look like HTML or
XML tags and a tag library is a set of user-defined tags that implement custom behavior.

• The taglib directive declares that your JSP page uses a set of custom tags, identifies the
location of the library, and provides a means for identifying the custom tags in your JSP
page.

The taglib directive follows the following syntax:

<%@ taglib uri="uri" prefix="prefixOfTag">

Where the uri attribute value resolves to a location the container understands and the
prefix attribute informs a container what bits of markup are custom actions.

JSP ACTIONS:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can
dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate
HTML for the Java plugin.
22UAD502 FULL STACK DEVELOPMENT UNIT III
There is only one syntax for the Action element, as it conforms to the XML standard:

<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions available:

Syntax Purpose

jsp:include Includes a file at the time the page is requested

jsp:useBean Finds or instantiates a JavaBean

jsp:setProperty Sets the property of a JavaBean

jsp:getProperty Inserts the property of a JavaBean into the output

jsp:forward Forwards the requester to a new page

jsp:plugin Generates browser-specific code that makes an OBJECT or


EMBED tag for the Java plugin

jsp:element Defines XML elements dynamically.

jsp:attribute Defines dynamically defined XML element's attribute.

jsp:body Defines dynamically defined XML element's body.

jsp:text Use to write template text in JSP pages and documents.


22UAD502 FULL STACK DEVELOPMENT UNIT III

JSP IMPLICIT OBJECTS:


JSP supports nine automatically defined variables, which are also called implicit objects. These
variables are:

Objects Description

request This is the HttpServletRequest object associated with the request.

response This is the HttpServletResponse object associated with the response to the
client.

out This is the PrintWriter object used to send output to the client.

session This is the HttpSession object associated with the request.

application This is the ServletContext object associated with application context.

config This is the ServletConfig object associated with the page.

pageContext This encapsulates use of server-specific features like higher

page This is simply a synonym for this, and is used to call the methods defined
by the translated servlet class.

Exception The Exception object allows the exception data to be accessed by


designated JSP.

JSTL (JSP STANDARD TAG LIBRARY)


The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates core functionality common to many JSP applications.

JSTL has support for common, structural tasks such as iteration and conditionals, tags for
manipulating XML documents, internationalization tags, and SQL tags. It also provides a framework
for integrating existing custom tags with JSTL tags.

The JSTL tags can be classified, according to their functions, into following JSTL tag library groups
that can be used when creating a JSP page:

• Core Tags

• Formatting tags

• SQL tags

• XML tags

• JSTL Functions
22UAD502 FULL STACK DEVELOPMENT UNIT III
Core Tags:
The core group of tags are the most frequently used JSTL tags. Following is the syntax to include
JSTL Core library in your JSP:

<%@ taglib prefix="c"


uri="http://java.sun.com/jsp/jstl/core" %>

There are following Core JSTL Tags:

Tag Description

<c:out > Like <%= ... >, but for expressions.

<c:set > Sets the result of an expression evaluation in a 'scope'

<c:remove > Removes a scoped variable (from a particular scope, if


specified).

<c:catch> Catches any Throwable that occurs in its body and optionally
exposes it.

<c:if> Simple conditional tag which evalutes its body if the supplied
condition is true.

<c:choose> Simple conditional tag that establishes a context for mutually


exclusive conditional operations, marked by <when> and
<otherwise>

<c:when> Subtag of <choose> that includes its body if its condition


evalutes to 'true'.

<c:otherwise > Subtag of <choose> that follows <when> tags and runs only if
all of the prior conditions evaluated to 'false'.

<c:import> Retrieves an absolute or relative URL and exposes its contents


to either the page, a String in 'var', or a Reader in 'varReader'.

<c:forEach > The basic iteration tag, accepting many different collection
types and supporting subsetting and other functionality .
22UAD502 FULL STACK DEVELOPMENT UNIT III
<c:forTokens> Iterates over tokens, separated by the supplied delimeters.

<c:param> Adds a parameter to a containing 'import' tag's URL.

<c:redirect > Redirects to a new URL.

<c:url> Creates a URL with optional query parameters

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

<html>

<head>

<title><c:out> Tag Example</title>

</head>

<body>

<c:out value="${'<tag> , &'}"/>


</body>

</html>

This would produce following result:

<tag> , &

<body>

<c:setvar="salary"scope="session"value="${2000*2}"/>
<c:outvalue="${salary}"/>
</body>

This would produce following result:

4000

<body>

<c:setvar="salary"scope="session"value="${2000*2}"/>
<p>Before Remove Value: <c:outvalue="${salary}"/></p>
<c:removevar="salary"/>
<p>After Remove Value: <c:outvalue="${salary}"/></p>
</body>
22UAD502 FULL STACK DEVELOPMENT UNIT III
This would produce following result:

Before Remove Value: 4000


After Remove Value:

<body>

<c:setvar="salary"scope="session"value="${2000*2}"/>
<c:iftest="${salary > 2000}">
<p>My salary is: <c:outvalue="${salary}"/><p>
</c:if>
</body>

This would produce following result:

My salary is: 4000

Formatting tags:

The JSTL formatting tags are used to format and display text, the date, the time, and numbers for
internationalized Web sites. Following is the syntax to include Formatting library in your JSP:

<%@ taglib prefix="fmt"


uri="http://java.sun.com/jsp/jstl/fmt" %>

Following is the list of Formatting JSTL Tags:

Tag Description

<fmt:formatNumber> To render numerical value with specific precision or


format.

<fmt:parseNumber> Parses the string representation of a number,


currency, or percentage.

<fmt:formatDate> Formats a date and/or time using the supplied styles


and pattern

<fmt:parseDate> Parses the string representation of a date and/or time

<fmt:bundle> Loads a resource bundle to be used by its tag body.


22UAD502 FULL STACK DEVELOPMENT UNIT III
<fmt:setLocale> Stores the given locale in the locale configuration
variable.

<fmt:setBundle> Loads a resource bundle and stores it in the named


scoped variable or the bundle configuration variable.

<fmt:timeZone> Specifies the time zone for any time formatting or


parsing actions nested in its body.

<fmt:setTimeZone> Stores the given time zone in the time zone


configuration variable

<fmt:message> To display an internationalized message.

<fmt:requestEncoding> Sets the request character encoding

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

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

<html>

<head>

<title>JSTL fmt:formatNumber Tag</title>

</head>

<body>
<h3>Number Format:</h3>
<c:setvar="balance"value="120000.2309"/>
<p>Formatted Number (1): <fmt:formatNumbervalue="${balance}"
type="currency"/></p>
<p>Formatted Number (2): <fmt:formatNumbertype="number"
maxIntegerDigits="3"value="${balance}"/></p>
</body>
</html>

This would produce following result:

Number Format:

Formatted Number (1): £120,000.23


22UAD502 FULL STACK DEVELOPMENT UNIT III

Formatted Number (2): 000.231

SQL tags:

The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such
as Oracle, mySQL, or Microsoft SQL Server.

Following is the syntax to include JSTL SQL library in your JSP:

<%@ taglib prefix="sql"


uri="http://java.sun.com/jsp/jstl/sql" %>

Following is the list of SQL JSTL Tags:

Tag Description

<sql:setDataSource> Creates a simple DataSource suitable only for


prototyping

<sql:query> Executes the SQL query defined in its body or through


the sql attribute.

<sql:update> Executes the SQL update defined in its body or through


the sql attribute.

<sql:param> Sets a parameter in an SQL statement to the specified


value.

<sql:dateParam> Sets a parameter in an SQL statement to the specified


java.util.Date value.

<sql:transaction > Provides nested database action elements with a shared


Connection, set up to execute all statements as one
transaction.

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

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

<html>

<head>

<title>JSTL sql:setDataSource Tag</title>

</head>

<body>
22UAD502 FULL STACK DEVELOPMENT UNIT III

<sql:setDataSourcevar="snapshot"driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST"
user="user_id"password="mypassword"/>

<sql:querydataSource="${snapshot}"sql="..."var="result"/>

</body>
</html>

XML tags:

The JSTL XML tags provide a JSP-centric way of creating and manipulating XML documents.
Following is the syntax to include JSTL XML library in your JSP.

The JSTL XML tag library has custom tags for interacting with XML data. This includes parsing
XML, transforming XML data, and flow control based on XPath expressions.

<%@ taglib prefix="x"


uri="http://java.sun.com/jsp/jstl/xml" %>

Before you proceed with the examples, you would need to copy following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib:

• XercesImpl.jar: Download it fromhttp://www.apache.org/dist/xerces/j/

• xalan.jar: Download it from http://xml.apache.org/xalan-j/index.html

Following is the list of XML JSTL Tags:

Tag Description

<x:out> Like <%= ... >, but for XPath expressions.

<x:parse> Use to parse XML data specified either via an attribute or in


the tag body.

<x:set > Sets a variable to the value of an XPath expression.

<x:if > Evaluates a test XPath expression and if it is true, it processes


its body. If the test condition is false, the body is ignored.
22UAD502 FULL STACK DEVELOPMENT UNIT III
<x:forEach> To loop over nodes in an XML document.

<x:choose> Simple conditional tag that establishes a context for mutually


exclusive conditional operations, marked by <when> and
<otherwise>

<x:when > Subtag of <choose> that includes its body if its expression
evalutes to 'true'

<x:otherwise > Subtag of <choose> that follows <when> tags and runs only if
all of the prior conditions evaluated to 'false'

<x:transform > Applies an XSL transformation on a XML document

<x:param > Use along with the transform tag to set a parameter in the
XSLT stylesheet

JSTL Functions:

JSTL includes a number of standard functions, most of which are common string manipulation
functions. Following is the syntax to include JSTL Functions library in your JSP:

<%@ taglib prefix="fn"


uri="http://java.sun.com/jsp/jstl/functions" %>

Following is the list of JSTL Functions:

Function Description

fn:contains() Tests if an input string contains the specified


substring.

fn:containsIgnoreCase() Tests if an input string contains the specified


substring in a case insensitive way.

fn:endsWith() Tests if an input string ends with the specified suffix.

fn:escapeXml() Escapes characters that could be interpreted as XML


markup.
22UAD502 FULL STACK DEVELOPMENT UNIT III
fn:indexOf() Returns the index withing a string of the first
occurrence of a specified substring.

fn:join() Joins all elements of an array into a string.

fn:length() Returns the number of items in a collection, or the


number of characters in a string.

fn:replace() Returns a string resulting from replacing in an input


string all occurrences with a given string.

fn:split() Splits a string into an array of substrings.

fn:startsWith() Tests if an input string starts with the specified


prefix.

fn:substring() Returns a subset of a string.

fn:substringAfter() Returns a subset of a string following a specific


substring.

fn:substringBefore() Returns a subset of a string before a specific


substring.

fn:toLowerCase() Converts all of the characters of a string to lower


case.

fn:toUpperCase() Converts all of the characters of a string to upper


case.

fn:trim() Removes white spaces from both ends of a string.

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

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

<html>

<head>

<title>Using JSTL Functions</title>


22UAD502 FULL STACK DEVELOPMENT UNIT III
</head>

<body>

<c:setvar="string1"value="This is first String."/>


<c:setvar="string2"value="This is second String."/>

<p>Length of String (1) : ${fn:length(string1)}</p>


<p>Length of String (2) : ${fn:length(string2)}</p>

</body>
</html>

This would produce following result:

Length of String (1) : 21


Length of String (2) : 22

<body>

<c:setvar="string1"value="This is first String."/>


<c:setvar="string2"value="${fn:substring(string1, 5, 15)}"/>

<p>Final sub string : ${string2}</p>

</body>

This would produce following result:

Final sub string : is first S

<body>

<c:setvar="string1"value="This is first String."/>


<c:setvar="string2"value="${fn:toLowerCase(string1)}"/>

<p>Final string : ${string2}</p>


22UAD502 FULL STACK DEVELOPMENT UNIT III
</body>

This would produce following result:

Final string : this is first string.

<body>

<c:setvar="string1"value="This is first String."/>


<c:setvar="string2"value="${fn:toUpperCase(string1)}"/>
<p>Final string : ${string2}</p>
</body>

This would produce following result:

Final string : THIS IS FIRST STRING.

CREATING HTML FORM BY EMBEDDING JSP CODE:

JSP handles form data parsing automatically using the following methods depending on the
situation:

• getParameter(): You call request.getParameter() method to get the value of a form


parameter.

• getParameterValues(): Call this method if the parameter appears more than once and
returns multiple values, for example checkbox.

• getParameterNames(): Call this method if you want a complete list of all parameters in
the current request.

• getInputStream(): Call this method to read binary data stream coming from the client.

GET Method Example Using Form:


Here is a simple example which passes two values using HTML FORM and submit button. We are
going to use same JSP main.jsp to handle this input.

<html>
<body>
<formaction="main.jsp"method="GET">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
22UAD502 FULL STACK DEVELOPMENT UNIT III
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>

Keep this HTML in a file Hello.html and put it in <Tomcat-installation- directory>/webapps/ROOT


directory. When you would accesshttp://localhost:8080/Hello.html, here is the actual output of the
above form.

First Name:
Last Name:
Try to enter First Name and Last Name and then click submit button to see the result on your local
machine where tomcat is running. Based on the input provided, it will generate similar result as
mentioned in the above example.

GET Method Example Using URL:


Here is a simple URL which will pass two values to HelloForm program using GET method.

http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Below is main.jsp JSP program to handle input given by web browser. We are going to
use getParameter() method which makes it very easy to access passed information:

<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
22UAD502 FULL STACK DEVELOPMENT UNIT III
Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your browser's
Location:box. This would generate following result:

Using GET Method to Read Form Data


• First Name: ZARA

• Last Name: ALI

POST Method Example Using Form:


• There is no change in above JSP because only way of passing parameters is changed and no
binary data is being passed to the JSP program.

<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>

Following is the content of Hello.html file:

<html>
<body>
22UAD502 FULL STACK DEVELOPMENT UNIT III
<formaction="main.jsp"method="POST">
First Name: <inputtype="text"name="first_name">
<br/>
Last Name: <inputtype="text"name="last_name"/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>

Now let us keep main.jsp and hello.htm in <Tomcat-installation-directory>/webapps/ROOT


directory. When you would accesshttp://localhost:8080/Hello.html, below is the actual output of the
above form.

First Name:
Last Name:

Passing Checkbox Data to JSP Program


• Checkboxes are used when more than one option is required to be selected.

Here is example HTML code, CheckBox.htm, for a form with two checkboxes

<html>
<body>
<formaction="main.jsp"method="POST"target="_blank">
<inputtype="checkbox"name="maths"checked="checked"/> Maths
<inputtype="checkbox"name="physics"/> Physics
<inputtype="checkbox"name="chemistry"checked="checked"/> Chemistry
<inputtype="submit"value="Select Subject"/>
</form>
</body>
</html>

The result of this code is the following form

Maths Physics Chemistry

Below is main.jsp JSP program to handle input given by web browser for checkbox button.
22UAD502 FULL STACK DEVELOPMENT UNIT III
<html>
<head>
<title>Reading Checkbox Data</title>
</head>
<body>
<center>
<h1>Reading Checkbox Data</h1>
<ul>
<li><p><b>Maths Flag:</b>
<%= request.getParameter("maths")%>
</p></li>
<li><p><b>Physics Flag:</b>
<%= request.getParameter("physics")%>
</p></li>
<li><p><b>Chemistry Flag:</b>
<%= request.getParameter("chemistry")%>
</p></li>
</ul>
</body>
</html>

For the above example, it would display following result:

Reading Checkbox Data

• Maths Flag : : on

• Physics Flag: : null

• Chemistry Flag: : on

Reading All Form Parameters:


• Following is the generic example which uses getParameterNames() method of
HttpServletRequest to read all the available form parameters.

• This method returns an Enumeration that contains the parameter names in an unspecified
order.
22UAD502 FULL STACK DEVELOPMENT UNIT III
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method to get
each parameter name.

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


<html>
<head>
<title>HTTP Header Request Example</title>
</head>
<body>
<center>
<h2>HTTP Header Request Example</h2>
<tablewidth="100%"border="1"align="center">
<trbgcolor="#949494">
<th>Param Name</th><th>Param Value(s)</th>
</tr>
<%
Enumeration paramNames = request.getParameterNames();

while(paramNames.hasMoreElements()){
String paramName =(String)paramNames.nextElement();
out.print("<tr><td>"+ paramName +"</td>\n");
String paramValue = request.getHeader(paramName);
out.println("<td> "+ paramValue +"</td></tr>\n");
}
%>
</table>
</center>
</body>
</html>

Following is the content of Hello.html:

<html>
22UAD502 FULL STACK DEVELOPMENT UNIT III
<body>
<formaction="main.jsp"method="POST"target="_blank">
<inputtype="checkbox"name="maths"checked="checked"/> Maths
<inputtype="checkbox"name="physics"/> Physics
<inputtype="checkbox"name="chemistry"checked="checked"/> Chem
<inputtype="submit"value="Select Subject"/>
</form>
</body>
</html>

Now try calling JSP using above Hello.htm, this would generate a result something like as below
based on the provided input:

Reading All Form Parameters

Param Name Param Value(s)

maths on

chemistry on

You might also like