Unit 3 Notes
Unit 3 Notes
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.
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) 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.
• 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.
2
22UAD502 FULL STACK DEVELOPMENT UNIT III
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.
Every request has a header that tells the status of the client. There are many request methods. Get
and Post requests are mostly used.
HTTP
Description
Request
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.
Asks for a list of the HTTP methods to which the thing at the request URL can
OPTIONS
respond
Container
Operations of Container:
• 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
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.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf, ejb
etc.
5
22UAD502 FULL STACK DEVELOPMENT UNIT III
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a HTTP
header that provides the description about what are you sending to the browser.
• text/html • application/pdf
• text/plain • application/octet-stream
• application/msword • application/x-zip
• application/vnd.ms-excel • images/jpeg
• application/jar • video/quicktime etc.
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.
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
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()
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.
9
22UAD502 FULL STACK DEVELOPMENT UNIT III
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.
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.
publicvoiddoGet(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code}
10
22UAD502 FULL STACK DEVELOPMENT UNIT III
publicvoiddoPost(HttpServletRequest request,
HttpServletResponse response)
throwsServletException,IOException{
// Servlet code
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.
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 :
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.
Creating a Servlet
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.
importjavax.servlet.http.*;
import java.io.*;
publicMyServletextendsHttpServlet
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.
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.
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:
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
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.
17
22UAD502 FULL STACK DEVELOPMENT UNIT III
• 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
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
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.
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
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
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.
22
22UAD502 FULL STACK DEVELOPMENT UNIT III
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
Class Description
ServletInputStream Provides the input stream for reading the client’s request
ServletOutputStream Provides the output stream for reading the client’s request
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
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
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.
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:
25
22UAD502 FULL STACK DEVELOPMENT UNIT III
4. HttpSessionBindingEvent:
Let's see the simple example of servlet by implementing the servlet interface.
File: First.java
import java.io.*;
import javax.servlet.*;
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
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.
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.
• 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.
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.
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;
response.setContentType("text/html");
+ "</title></head><body>"
+ "<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">
<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>
</head>
<body>
30
22UAD502 FULL STACK DEVELOPMENT UNIT III
</form>
</body>
</html>
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,
HttpServletResponse response)
throwsServletException, IOException {
doGet(request, response); }
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 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:
32
22UAD502 FULL STACK DEVELOPMENT UNIT III
✓ Http protocol is stateless, to make stateful between client and server we need Session
Tracking.
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.
33
22UAD502 FULL STACK DEVELOPMENT UNIT III
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.
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
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
Disadvantage of Cookies
Cookie class
Constructor Description
Cookie(String name, String value) constructs a cookie with a specified name and
value.
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.
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.
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
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
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.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
39
22UAD502 FULL STACK DEVELOPMENT UNIT III
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
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();
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.
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.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
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
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.
The HttpServletRequest interface provides two methods to get the object of HttpSession:
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.
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.*;
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.*;
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>
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.
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:
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:
48
22UAD502 FULL STACK DEVELOPMENT UNIT III
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:
49
22UAD502 FULL STACK DEVELOPMENT UNIT III
Step 5:
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:
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:
To get the information about installer click on the "Show details" button
Step 9:
52
22UAD502 FULL STACK DEVELOPMENT UNIT III
Step 10:
A window of Apache Service Manager appears with displaying the running process.
Step 11:
After completing the installation process, the Apache Tomcat Manager appears on the toolbar panel
like shown in the below picture.
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.
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.
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.
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.
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.
55
22UAD502 FULL STACK DEVELOPMENT UNIT III
JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to
connect with the database.
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 −
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
• 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)
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
Disadvantage:
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:
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:
Disadvantage:
FieldName Type
61
22UAD502 FULL STACK DEVELOPMENT UNIT III
Sname varchar2(20)
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());
} }}
web.xml
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.
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.
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.
• 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.
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 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.
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:
Loop Statements:
• You can also use three basic types of looping blocks in Java: for, while,and
do…whileblocks in your JSP programming.
JSP Tutorial
JSP Tutorial
JSP Tutorial
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.
JSP Literals:
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.
<jsp:scriptlet>
code fragment
</jsp:scriptlet>
In JSP, java code can be written inside the jsp page using the scriptlet tag.
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
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.
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.
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>
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
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>
• 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.
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
JSP DIRECTIVES:
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
• page directive
• include directive
• taglib directive
<%@ 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.
• This directive tells the container to merge the content of other external files with the
current JSP during the translation phase.
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.
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:
Action elements are basically predefined functions and there are following JSP actions available:
Syntax Purpose
Objects Description
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.
page This is simply a synonym for this, and is used to call the methods defined
by the translated servlet class.
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:
Tag Description
<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:otherwise > Subtag of <choose> that follows <when> tags and runs only if
all of the prior conditions evaluated to 'false'.
<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.
<html>
<head>
</head>
<body>
</html>
<tag> , &
<body>
<c:setvar="salary"scope="session"value="${2000*2}"/>
<c:outvalue="${salary}"/>
</body>
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:
<body>
<c:setvar="salary"scope="session"value="${2000*2}"/>
<c:iftest="${salary > 2000}">
<p>My salary is: <c:outvalue="${salary}"/><p>
</c:if>
</body>
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:
Tag Description
<html>
<head>
</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>
Number Format:
SQL tags:
The JSTL SQL tag library provides tags for interacting with relational databases (RDBMSs) such
as Oracle, mySQL, or Microsoft SQL Server.
Tag Description
<html>
<head>
</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.
Before you proceed with the examples, you would need to copy following two XML and XPath
related libraries into your <Tomcat Installation Directory>\lib:
Tag Description
<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: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:
Function Description
<html>
<head>
<body>
</body>
</html>
<body>
</body>
<body>
<body>
JSP handles form data parsing automatically using the following methods depending on the
situation:
• 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.
<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>
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.
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:
<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>
<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>
First Name:
Last Name:
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>
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>
• Maths Flag : : on
• Chemistry Flag: : on
• 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.
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>
<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:
maths on
chemistry on