You are on page 1of 28

WEB TECHNOLOGIES

UNIT III

Syllabus
SERVER SIDE PROGRAMMING
Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions-Session Handling-
Understanding Cookies- Installing and Configuring Apache Tomcat Web Server- DATABASE
CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding Java Server Pages-
JSP Standard Tag Library (JSTL)-Creating HTML forms by embedding JSP code.

Servlets
Why use Servlets
• To develop a web application
• To deliver the application to anyone with a browser
What is a Servlet
▪ Servlet is a java program that runs inside JVM on the web server.
▪ It is used for developing dynamic web applications.
▪ Servlet do not have main() method. They are under the control of TOMCAT.
static and dynamic web page
▪ Static page remains same for all users
▪ A dynamic web page changes based on the request from client
Features of a Servlet
▪ Portable
o Platform independence
▪ Efficient and Scalable
o Simultaneous support for multiple requests using multithreading
▪ Robust
o Garbage collection, Exception handling.
Servlet API
▪ We need to use Servlet API to create servlets.
▪ Two packages will be used
o javax.servlet : Contains the classes to support generic servlet (protocol-
independent servlet)
▪ Must extend javax.servlet.GenericServlet class
o javax.servlet.http : contains classes to support http servlet.
▪ Must extend javax.servlet.http.HttpServlet class

WT – UNIT III – R19 Page 1


Generic Servlet
▪ GenericServlet class has an abstract service() method. Which means the subclass of
GenericServlet should always override the service() method.
public abstract void service(ServletRequest request, ServletResponse response) throws
ServletException, java.io.IOException

HTTP Servlet
▪ HttpServlet class, which is an abstract class. The HTTP Servlet doesn’t override the
service() method.
▪ It must override at least one method from the list below:
doGet() , doPost(),doPut(),doDelete(), init() and destroy() and getServletInfo()

WT – UNIT III – R19 Page 2


Servlet’s life cycle
❖ Servlet life cycle contains five steps:
1) Loading of Servlet
2) Creating instance of Servlet
3) Invoke init() once
4) Invoke service() repeatedly for each client request
5) Invoke destroy()

WT – UNIT III – R19 Page 3


1) Loading of Servlet : When the web server (e.g. Apache Tomcat) starts up, the servlet
container deploy and loads all the servlets.
2) Creating instance of Servlet : Once all the Servlet classes loaded, the servlet
container creates instances of each servlet class. Servlet container creates only once

WT – UNIT III – R19 Page 4


instance per servlet class and all the requests to the servlet are executed on the same
servlet instance.
3) Invoke init() once: Once all the servlet classes are instantiated, the init() method is
invoked for each instantiated servlet. This method initializes the servlet.
4) Invoke service() repeatedly for each client request:
i) Each time the web server receives a request for servlet, it spawns a new thread
that calls service() method.
ii) If the servlet is GenericServlet then the request is served by the service() method
itself,
iii) if the servlet is HttpServlet then service() method receives the request and
dispatches it to the correct handler method based on the type of request.
5) Invoke destroy() :
i. When servlet container shuts down(this usually happens when we stop the web
server), it unloads all the servlets and calls destroy() method for each initialized
servlets.

TOMCAT or Web Container


o Also known as Servlet Container and Servlet Engine.
o It is a part of Web Server that interacts with Servlets. This is the main component of Web
Server that manages the life cycle of Servlets.
o Servlets don’t have a main() method.
o They are under the control of another java application called a Container.

WT – UNIT III – R19 Page 5


Application Server (Weblogic,Jboss,WebSphere,Glassfish)

WT – UNIT III – R19 Page 6


How the Container handles a request?

WT – UNIT III – R19 Page 7


Create and Run a Servlet in Eclipse
1) Create a Dynamic Web project
2) Create an html page to call the servlet class on a webpage (under WebContent folder)
3) Create a Servlet class
4) Edit web.xml (Deployment Descriptor)

FORM GET and POST Actions


GET request : The following form will call doGet() method when the form is submitted.
<form action=”servlet” method=”get”>
</form>
➢ GET is used to request data from a specified resource.

POST request : The following form will call doPost() method when the form is submitted.
<form action=”servlet” method=”post”>
</form>
➢ POST is used to send data to a server to create/update a resource.

WT – UNIT III – R19 Page 8


GET vs POST

GET POST

1) In case of Get request, only limited amount In case of post request, large amount of
of data can be sent because data is sent in data can be sent because data is sent in
header. body.

2) Get request is not secured because data is Post request is secured because data is
exposed in URL bar. not exposed in URL bar.

3) Get request can be bookmarked. Post request cannot be bookmarked.

4) Get request is idempotent . It means second Post request is non-idempotent.


request will be ignored until response of first
request is delivered

Session Tracking / Session Handling


• The HTTP protocol is stateless by design.
• Session tracking is a mechanism to identify user sessions and appropriately tie all of a
user's requests to his or her session.
• This process is typically performed using cookies or URL rewriting.
• In the standard servlet API, each user session is represented by an instance of a class
that implements the javax.servlet.http.HttpSession interface.

HttpSession session=request.getSession();
o The above statement will create a session ID by TOMCAT server and then the session
id will be sent to the client.

WT – UNIT III – R19 Page 9


o In the next request, the client will send the session ID to the server so that server will
identify the user who is requesting.
o The session ID will be exchanged between client and server using COOKIES.

getSession(false) vs getSession(true)
❑ getSession(true) will check whether a session already exists for the user. If yes, it will
return that session object else it will create a new session object and return it.
❑ getSession(false) will check existence of session. If session exists, then it returns the
reference of that session object, if not, this methods will return null.

Configuring session timeout in the DD

session-config>
<session-timeout> 15 </session-timeout>
</session-config>
Setting session timeout for a specific session

session.setMaxInactiveInterval(20*60);

if the client does not make any requests on the session for 20 minutes, kill it.

Cookies

• Cookie is a little piece of data ( a name / value String pair) exchanged between the client
and server.
• Cookies are used to exchange session ID information between client and server.
• The Container does virtually all the cookie work with the below statement.
HttpSession s = request.getSession();

How do client and container exchange Session ID info

WT – UNIT III – R19 Page 10


WT – UNIT III – R19 Page 11
Custom Cookies
1. Creating a cookie
Cookie c = new Cookie (“username”, name);
2. Setting how long a cookie will live on the client
c.setMaxAge(30*60);
3. Sending the cookie to the client
response.addCookie(c);

Installing and Configuring Apache Tomcat Web Server

o To run servlets in Eclipse, we need TOMCAT server installed the on the system and
configured in the Eclipse IDE.
Step 1: Download and Install Eclipse IDE
Install Eclipse on Windows

o Go to this link https://www.eclipse.org/downloads. Under “Get Eclipse Oxygen” →Click


“Download Packages” ->Download “Eclipse IDE for Java Developers”.

o You would see two options on the right side (32 bit and 64 bit), click on 32 bit if you
system is 32 bit else click on 64 bit. This will download a zipped file on your system.

o To install Eclipse, unzip the downloaded file and copy the unzipped folder to the desired
location.

WT – UNIT III – R19 Page 12


Step 2: Download and Install Apache Tomcat Server
o Download and install TOMCAT 9 from the link
http://tomcat.apache.org/download-80.cgi.

Step 3: Configure Apache Tomcat Server in Eclipse


o In Eclipse, go to Window -> Preferences

o Click on Server -> Run Time Environments

o Click on Add

WT – UNIT III – R19 Page 13


o Add Tomcat installation directory

o Then Click Finish

WT – UNIT III – R19 Page 14


JDBC (Java Database Connectivity)
o There are 5 steps to connect any java application with the database using JDBC. These
steps are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

i) Register the driver class

o The forName() method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.
o public static void forName(String className) throws ClassNotFoundException
o Class.forName("oracle.jdbc.driver.OracleDriver");

ii) Create the connection object

o The getConnection() method of DriverManager class is used to establish


connection with the database.
o public static Connection getConnection(String url) throws SQLException
o public static Connection getConnection(String url,String name,String password)
throws SQLException
o Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:15
21:xe","system","password");
iii) Create the Statement object

o The createStatement() method of Connection interface is used to create


statement. The object of statement is responsible to execute queries with the
database.
o public Statement createStatement() throws SQLException
o Statement stmt=con.createStatement();
iv) Execute the query

o The executeQuery() method of Statement interface is used to execute queries


to the database. This method returns the object of ResultSet that can be used to
get all the records of a table.

public ResultSet executeQuery(String sql)throws SQLException

WT – UNIT III – R19 Page 15


ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2));

v) Close the connection object

o By closing connection object statement and ResultSet will be closed


automatically. The close() method of Connection interface is used to close the
connection.
o public void close()throws SQLException
o con.close();
JDBC Program Example

public class ConnectJDBC {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String name;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE",
"webapp","webapp");

Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from user_details");

while(rs.next()) {
name = rs.getString(1);
System.out.println(name);
}
con.close();

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

WT – UNIT III – R19 Page 16


JSP (Java Server Pages)

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

o A JSP page consists of HTML tags and JSP tags.

o JSTL – JSP Standard Tag Library

Advantages of JSP

o Extension to Servlet
o Easy to maintain
o Less code than Servlet

Life cycle of JSP

The JSP pages follow these phases:

1. Translation of JSP Page into Servlet


2. Compilation of JSP Page
3. Classloading (the classloader loads class file)
4. Instantiation (Object of the Generated Servlet is created).
5. Initialization ( the container invokes jspInit() method).
6. Request processing ( the container invokes _jspService() method).
7. Destroy ( the container invokes jspDestroy() method).

WT – UNIT III – R19 Page 17


Implicit objects of JSP :

▪ There are 9 jsp implicit objects. These objects are created by the web container that
are available to all the jsp pages.

Example of JSP

<html>

<body>
WT – UNIT III – R19 Page 18
<% out.print(2*5); %>

</body>

</html>

Creating HTML forms by embedding JSP code

JSP with method “get”

We can write JSP code inside a HTML form. Example is given below:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Welcome.jsp" method=”get”>

<input type="text" name="FName">


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

</form>
</body>

Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Page</title>
</head>
<body>

<%
String fname=(String)request.getParameter("FName");
out.print("Hello "+fname);
%>

</body>
</html>
Output

WT – UNIT III – R19 Page 19


Note: The input is visible in the browser URL as

http://localhost:9999/JSP_Example/Welcome.jsp?FName=SVCK

JSP with method “post”

We can write JSP code inside a HTML form. Example is given below:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="Welcome.jsp" method=”post”>

<input type="text" name="FName">


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

</form>
</body>

Welcome.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
WT – UNIT III – R19 Page 20
<title>JSP Page</title>
</head>
<body>

<%
String fname=(String)request.getParameter("FName");
out.print("Hello "+fname);
%>

</body>
</html>
Output

Note: The input is visible in the browser URL as

http://localhost:9999/JSP_Example/Welcome.jsp

JSP – Scripting Elements

• Java provides various scripting elements that allow you to insert Java code from your
JSP code into the servlet
• Scripting elements in JSP must be written within the <% %> tags.
• The JSP engine will process any code you write within the pair of the <% and %> tags

Five different scripting elements:


1) Comment <%-- Set of comments --%>
2) Directive <%@ directive %>

WT – UNIT III – R19 Page 21


3) Declaration <%! declarations %>
4) Scriptlet <% scriplets %>
5) Expression <%= expression %>

2) Directives
• These tags are used to provide specific instructions to the web container when the page
is translated. It has three subcategories:
• Page: <%@ page ... %>
• Include: <%@ include ... %>
• Taglib: <%@ taglib ... %>
3) Declaration

• As the name suggests, it is used to declare methods and variables you will use in your
Java code within a JSP file.
• According to the rules of JSP, any variable must be declared before it can be used.
• <%! declaration; [ declaration; ]+ ... %>
• <%! int variable_value=62; %>
4) JSP Scriptlet tag
• The scriptlet tag allows writing Java code statements within the JSP page.
• This tag is responsible for implementing the functionality of _jspService() by scripting
the java code.
• <% JAVA CODE %>
• <% int cnt = 2; %>
• <% out.println(cnt); %>

5) JSP Expressions
• Expressions elements are responsible for containing scripting language expression,
which gets evaluated and converted to Strings by the JSP engine and is meant to the
output stream of the response.
• Hence, you are not required to write out.print() for writing your data.
• This is mostly used for printing the values of variables or methods in the form of output.
• <%= "A JSP based string" %>

JSTL
o JSTL stands for JSP Standard Tag Library.
o The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP
development.
o JSTL is the standard tag library that provides tags to control the JSP page behavior.
o JSTL tags can be used for iteration and control statements, internationalization, SQL
etc.
o For creating JSTL based application, we need to download the jstl.jar file.

WT – UNIT III – R19 Page 22


Advantage of JSTL

1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag: It avoids the use of scriptlet tag.

JSTL Tags

There JSTL mainly provides five types of tags:

Tag Name Description


Core tags The JSTL core tag provide variable support, URL management,
flow control, etc. The URL for the core tag
is http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.

Function tags The functions tags provide support for string manipulation and
string length. The URL for the functions tags
is http://java.sun.com/jsp/jstl/functions and prefix is fn.

Formatting tags The Formatting tags provide support for message formatting,
number and date formatting, etc. The URL for the Formatting tags
is http://java.sun.com/jsp/jstl/fmt and prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc. The URL
for the XML tags is http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL
tags is http://java.sun.com/jsp/jstl/sql and prefix is sql.

WT – UNIT III – R19 Page 23


JSTL CORE TAG DESCRIPTION
<c:out> To
Samewrite
assomething in JSP
<jsp:include> page
or include
<c:import> directive
<c:redirect> redirect request
To set the to another
variable value in resource
given
<c:set> scope.
To remove the variable from given
<c:remove> scope
To catch the exception and wrap it
<c:catch> into an object.
<c:if> Simple
Simple conditional
conditional logic
tag that
<c:choose> establishes
Subtag of <c:choose>for
a context mutually
that includes
<c:when> its bodyof
Subtag if its condition evalutes
<c:choose> to
that includes
<c:otherwise> its body if its condition evalutes to
<c:forEach> for
for iteration
iteration over
over a collection
tokens separated by
<c:forTokens> a delimiter.
used with <c:import> to pass
<c:param> parameters
to create a URL with optional query
<c:url> string parameters

JSTL Functions Description


fn:contains() It is used to test if an input string containing the
specified substring in a program.
fn:containsIgnoreCase() It is used to test if an input string contains the specified
substring as a case insensitive way.
fn:endsWith() It is used to test if an input string ends with the
specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as
XML markup.
fn:indexOf() It returns an index within a string of first occurrence of
a specified substring.
fn:trim() It removes the blank spaces from both the ends of a
string.
fn:startsWith() It is used for checking whether the given string is
started with a particular string value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase() It converts all the characters of a string to lower case.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given
fn:substringAfter() start and end
It returns position.
the subset of string after a specific substring.
fn:substringBefore() It returns the subset of string before a specific
fn:length() substring.
It returns the number of characters inside a string, or
fn:replace() the numberall
It replaces ofthe
items in a collection.
occurrence of a string with another
string sequence.

WT – UNIT III – R19 Page 24


Formatting Tags Descriptions
fmt:parseNumber It is used to Parses the string representation of a
currency, percentage or number.
fmt:timeZone It specifies a parsing action nested in its body or
the time zone for any time formatting.

fmt:formatNumber It is used to format the numerical value with


specific format or precision.

fmt:parseDate It parses the string representation of a time and


date.
fmt:bundle It is used for creating the ResourceBundle objects
which will be used by their tag body.
fmt:setTimeZone It stores the time zone inside a time zone
configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a
bundle configuration variable or the named
fmt:message scoped variable.
It display an internationalized message.

fmt:formatDate It formats the time and/or date using the supplied


pattern and styles.
XML Tags Descriptions
x:out Similar to <%= ... > tag, but for XPath
x:parse expressions.
It is used for parse the XML data specified either in
the tag body or an attribute.
x:set It is used to sets a variable to the value of an
XPath expression.
x:choose It is a conditional tag that establish a context for
mutually exclusive conditional operations.
x:when It is a subtag of that will include its body if the
condition evaluated be 'true'.
x:otherwise It is subtag of that follows tags and runs only if all
the prior conditions evaluated be 'false'.
x:if It is used for evaluating the test XPath expression
and if it is true, it will processes its body content.
x:transform It is used in a XML document for providing the
XSL(Extensible Stylesheet Language)
transformation.
x:param It is used along with the transform tag for setting
the parameter in the XSLT style sheet.

WT – UNIT III – R19 Page 25


SQL Tags Descriptions
sql:setDataSource It is used for creating a simple data source
suitable only for prototyping.
sql:query It is used for executing the SQL query
defined in its sql attribute or the body.
sql:update It is used for executing the SQL update
defined in its sql attribute or in the tag body.
sql:param It is used for sets the parameter in an SQL
statement to the specified value.
sql:dateParam It is used for sets the parameter in an SQL
statement to a specified java.util.Date value.
sql:transaction It is used to provide the nested database
action with a common connection.

Example JSTL Core <c:import> Tag

The <c:import> is used to include the content of any resource either within server or outside the
server.

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

<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:import var="data" url="http://www.google.com"/>
<c:out value="${data}"/>
</body>
</html>

MVC architecture (Model – View – Controller)

o View: Responsible for the presentation.


o Controller: Takes user input from the request and figures out what it means to the
model.
o Model: Holds the real business logic and the state. In other words, it knows rules for
getting and updating the state.

WT – UNIT III – R19 Page 26


MVC in JSP & Servlet

Web Application Project Structure


Project Name or
Context Root

Java program
Files

Java .class Files

Library files

Deployment Descriptor

html or jsp files

WT – UNIT III – R19 Page 27


Important Questions
1. Define a Servlet and its types. Explain Servlet Lifecycle with neat diagram.
2. What is a TOMCAT or Web Container or Web Server? Explain how TOMCAT handles
request and response protocol with near diagrams
3. Differentiate between GET and POST methods with a program.
4. Explain how Session Handling will be done in a web application. Explain Cookie
concept.
5. What is JDBC? Explain how to connect to database from Java program with an
example.
6. What is JSP? Explain life cycle and implicit objects of JSP with a program.
7. What is JSTL? Write short notes.
8. Explain how to run a servlet in Eclipse with Eclipse and Tomcat installation and
configuration in Eclipse.
9. Explain the project structure of a web application with neat diagram.
10. Explain MVC architecture in Servlets and JSP.
11. What is a Deployment Descriptor (web.xml) Explain with an example.

WT – UNIT III – R19 Page 28

You might also like