Jeppiaar Institute of Technology: Department OF Computer Science and Engineering
Jeppiaar Institute of Technology: Department OF Computer Science and Engineering
DEPARTMENT
OF
LECTURE NOTES
CS8651-INTERNET PROGRAMMING
(Regulation 2017)
2020 – 2021
Prepared by
Dr. K. Tamilarasi
UNIT III
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.
Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in
comparison with the CGI.
Performance is significantly better.
Servlets execute within the address space of a Web server. It is not
necessary to create a separate process to handle each client request.
Servlets are platform-independent because they are written in Java.
Java security manager on the server enforces a set of restrictions to
protect the resources on a server machine. So servlets are trusted.
The full functionality of the Java class libraries is available to a servlet. It
can communicate with applets, databases, or other software via the
sockets and RMI mechanisms that you have seen already.
Read the explicit data sent by the clients (browsers). This includes an HTML form
on a Web page or it could also come from an applet or a custom HTTP client
program.
Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so
forth.
Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing
the response directly.
Send the explicit data (i.e., the document) to the clients (browsers). This document
can be sent in a variety of formats, including text (HTML or XML), binary (GIF
images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.
Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
Servlets can be created using the javax.servlet and javax.servlet.http packages,
which are a standard part of the Java's enterprise edition, an expanded version of
the Java class library that supports large-scale development projects.
These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
Java servlets have been created and compiled just like any other Java class. After
you install the servlet packages and add them to your computer's Classpath, you
can compile servlets with the JDK's Java compiler or any other current compiler.
// For taking the servlet out of service, this method is called only once
}
}
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 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 −
The service () method is called by the container and service method invokes doGet,
doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type of
request you receive from the client.
The doGet() and doPost() are most frequently used methods with in each service request.
Here is the signature of these two methods.
// Servlet code
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method.
// Servlet code
The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
The destroy method definition looks like this −
// Finalization code...
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? (question mark) symbol as
follows −
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 used 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.
Servlets 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.
Here is a simple URL which will pass two values to HelloForm program using GET
method.
Given below is the 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 −
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
String docType =
out.println(docType +
"<html>\n" +
"<ul>\n" +
+ request.getParameter("first_name") + "\n" +
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>" +
"</html>"
);
$ javac HelloForm.java
If everything goes fine, above compilation would produce HelloForm.class file. Next you
would have to copy this class file in <Tomcat installationdirectory>/webapps/ROOT/WEB-
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class>HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>
Output
Here is a simple example which passes two values using HTML FORM and submit button.
We are going to use same Servlet HelloForm to handle this input.
<html>
<body>
<br />
</form>
</body>
</html>
Let us do little modification in the above servlet, so that it can handle GET as well as
POST methods. Below is HelloForm.java servlet program to handle input given by web
browser using GET or POST methods.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
String docType =
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<ul>\n" +
+ request.getParameter("first_name") + "\n" +
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>"
"</html>"
);
doGet(request, response);
Now compile and deploy the above Servlet and test it using Hello.htm with the POST method as
follows −
<html>
<body>
<br />
</form>
</body>
</html>
sent in body.
2 Get request is not secured because data is exposed in Post request is secured because data
URL bar. is not exposed 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 is Post request is non-idempotent.
delivered
5 Post request is less efficient and used
Get request is more efficient and used more than Post.
less than get.
Two common methods for the request-response between a server and client are:
The query string (name/value pairs) is sent inside the URL of a GET request:
GET/RegisterDao.jsp?name1=value1&name2=value2
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 information is sent to the server.
The query string (name/value pairs) is sent in HTTP message body for a POST
request:
POST/RegisterDao.jsp HTTP/1.1
name1=value1&name2=value2
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the
client opens a separate connection to the Web server and the server automatically does
not keep any record of previous client request.
Still there are following three ways to maintain session between web client and web server
3.4.1 Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the recieved cookie.
This may not be an effective way because many time browser does not support a cookie,
so I would not recommend to use this procedure to maintain the sessions.
A web server can send a hidden HTML form field along with a unique session ID as
follows −
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends
request back, then session_id value can be used to keep the track of different web
browsers.
This could be an effective way of keeping track of the session but clicking on a regular (<A
HREF...>) hypertext link does not result in a form submission, so hidden form fields also
cannot support general session tracking.
You can append some extra data on the end of each URL that identifies the session, and
the server can associate that session identifier with data it has stored about that session.
For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session identifier
is attached as sessionid = 12345 which can be accessed at the web server to identify the
client.
URL rewriting is a better way to maintain sessions and it works even when browsers don't
support cookies.
The drawback of URL re-writing is that you would have to generate every URL dynamically
to assign a session ID, even in case of a simple static HTML page.
Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request or visit to a Web site
and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and
an HTTP server. The session persists for a specified time period, across more than one
connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below −
This example describes how to use the HttpSession object to find out the creation time
and the last-accessed time for a session. We would associate a new session with the
request if one does not already exist.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
if (session.isNew()) {
session.setAttribute(userIDKey, userID);
} else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html");
String docType =
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
</tr>\n" +
"<tr>\n" +
" <td>id</td>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"<tr>\n" +
</tr>\n" +
"</table>\n" +
"</body>
</html>"
);
When you are done with a user's session data, you have several options
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30
minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that
session in seconds. So if your session is configured in web.xml for 15 minutes,
getMaxInactiveInterval( ) returns 900.
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users –
Server script sends a set of cookies to the browser. For example name, age, or
identification number etc.
Browser stores this information on local machine for future use.
When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify the
user.
ii. Keep in mind, neither the name nor the value should contain white space or any of
the following characters −
[]()=,"/?@:;
iii. Setting the maximum age − You use setMaxAge to specify how long (in seconds)
the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24);
iv. Sending the Cookie into the HTTP response headers − You use
response.addCookie to add cookies in the HTTP response header as follows −
response.addCookie(cookie);
Example
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
response.addCookie( firstName );
response.addCookie( lastName );
response.setContentType("text/html");
String docType =
"<html>\n" +
"<head>
</head>\n" +
"<ul>\n" +
+ request.getParameter("first_name") + "\n" +
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>
</html>"); }}
To delete cookies is very simple. If you want to delete a cookie then you simply need to
follow up following three steps –
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie
Add this cookie back into response header.
This step involves downloading an implementation of the Java Software Development Kit
(SDK) and setting up PATH environment variable appropriately.
You can download SDK from Oracle's Java site − Java SE Downloads.
Once you download your Java implementation, follow the given instructions to install and
configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and java_install_dir
respectively.
If you are running Windows and installed the SDK in C:\jdk1.8.0_65, you would put the
following line in your C:\autoexec.bat file.
A number of Web Servers that support servlets are available in the market. Some web
servers are freely downloadable and Tomcat is one of them.
Apache Tomcat is an open source software implementation of the Java Servlet and Java
Server Pages technologies and can act as a standalone server for testing servlets and can
be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your
machine –
Download latest version of Tomcat from https://tomcat.apache.org/.
Once you downloaded the installation, unpack the binary distribution into a convenient
location. For example in C:\apache-tomcat-8.0.28 on windows, or /usr/local/apache-
tomcat-8.0.289 on Linux/Unix and create CATALINA_HOME environment variable pointing
to these locations.
Tomcat can be started by executing the following commands on windows machine −
%CATALINA_HOME%\bin\startup.bat
or
C:\apache-tomcat-8.0.28\bin\startup.bat
Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)
machine −
$CATALINA_HOME/bin/startup.sh
or
/usr/local/apache-tomcat-8.0.28/bin/startup.sh
After startup, the default web applications included with Tomcat will be available by
visiting http://localhost:8080/. If everything is fine then it should display following result −
Further information about configuring and running Tomcat can be found in the
documentation included here, as well as on the Tomcat web site −
http://tomcat.apache.org
Tomcat can be stopped by executing the following commands on windows machine −
C:\apache-tomcat-8.0.28\bin\shutdown
Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux,
etc.) machine −
/usr/local/apache-tomcat-8.0.28/bin/shutdown.sh
Since servlets are not part of the Java Platform, Standard Edition, you must identify the
servlet classes to the compiler.
If you are running Windows, you need to put the following lines in your C:\autoexec.bat
file.
o Create connection
o Create statement
o Execute queries
o Close connection
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
Statement stmt=con.createStatement();
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.
con.close();
To connect java application with the oracle database, we need to follow 5 following steps.
In this example, we are using Oracle 10g as the database. So we need to know following
information for the oracle database:
Driver class: The driver class for the oracle database is oracle.jdbc.driver.OracleDriver.
Connection URL: The connection URL for the oracle10G database is
jdbc:oracle:thin:@localhost:1521:xe where jdbc is the API, oracle is the database, thin is
the driver, localhost is the server name on which oracle is running, we may also use IP
address, 1521 is the port number and XE is the Oracle service name. You may get all
these information from the tnsnames.ora file.
Username: The default username for the oracle database is system.
Password: It is the password given by the user at the time of installing the oracle
database.
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the
SQL query to create a table.
In this example, we are connecting to an Oracle database and getting data from emp
table. Here, system and oracle are the username and password of the Oracle database.
import java.sql.*;
class OracleCon{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
Statement stmt=con.createStatement();
while(rs.next())
con.close();
2. set classpath
Firstly, search the ojdbc14.jar file then go to JRE/lib/ext folder and paste the jar file here.
2) set classpath:
o temporary
o permanent
Firstly, search the ojdbc14.jar file then open command prompt and write:
1. C:>set classpath=c:\folder\ojdbc14.jar;.;
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to ojdbc14.jar by appending ojdbc14.jar;.; as
C:\oraclexe\app\oracle\product\10.2.0\server\jdbc\lib\ojdbc14.jar;.;
To connect Java application with the MySQL database, we need to follow 5 following
steps.In this example we are using MySql as the database. So we need to know following
informations for the mysql database:
1. Driver class: The driver class for the mysql database is com.mysql.jdbc.Driver.
4. Password: It is the password given by the user at the time of installing the mysql
database. In this example, we are going to use root as the password.
Let's first create a table in the mysql database, but before creating table, we need to create
database first.
2. use sonoo;
In this example, soon is the database name, root is the username and password both.
1. import java.sql.*;
2. class MysqlCon{
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://localhost:3306/sonoo","root","root");
9. Statement stmt=con.createStatement();
11. while(rs.next())
13. con.close();
15. }
16. }
The above example will fetch all the records of emp table.
To connect java application with the mysql database, mysqlconnector.jar file is required to be
loaded.
2. Set classpath
Download the mysqlconnector.jar file. Go to jre/lib/ext folder and paste the jar file here.
2) Set classpath:
o temporary
o permanent
1. C:>set classpath=c:\folder\mysql-connector-java-5.0.8-bin.jar;.;
Go to environment variable then click on new tab. In variable name write classpath and in
variable value paste the path to the mysqlconnector.jar file by appending mysqlconnector.jar;.; as
C:\folder\mysql-connector-java-5.0.8-bin.jar;.;
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 have access to the entire family of Java APIs, including the JDBC API to access
enterprise databases.
JavaServer Pages often serve the same purpose as programs implemented using
the Common Gateway Interface (CGI). But JSP offers several advantages in comparison with
the CGI.
JSP are always compiled before they are processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has
access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP, etc.
JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.
Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the most
complex and demanding.
The advantages of JSP are twofold. First, the dynamic part is written in Java, not
Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is
portable to other operating systems and non-Microsoft Web servers.
It is more convenient to write (and to modify!) regular HTML than to have plenty of
println statements that generate the HTML.
SSI is really only intended for simple inclusions, not for "real" programs that use
form data, make database connections, and the like.
JavaScript can generate HTML dynamically on the client but can hardly interact
with the web server to perform complex tasks like database access and image processing etc.
To begin working with JSP tages you need to first install the JSTL library. If you are using
the Apache Tomcat container, then follow these two steps −
Step 1 − Download the binary distribution from Apache Standard Taglib and unpack the
compressed file.
Step 2 − To use the Standard Taglib from its Jakarta Taglibs distribution, simply copy the
JAR files in the distribution's 'lib' directory to your application's webapps\ROOT\WEB-
INF\lib directory.
To use any of the libraries, you must include a <taglib> directive at the top of each JSP
that uses the library.
The JSTL tags can be classified, according to their functions, into the following JSTL tag
library groups that can be used when creating a JSP page −
Core Tags
Formatting tags
SQL tags
XML tags
JSTL Functions
Core Tags
The core group of tags are the most commonly used JSTL tags. Following is the syntax to
include the JSTL Core library in your JSP −
13 <c:redirect >
Redirects to a new URL.
14 <c:url>
Creates a URL with optional query parameters
Formatting Tags
The JSTL formatting tags are used to format and display text, the date, the time, and
numbers for internationalized Websites. Following is the syntax to include Formatting library in
your JSP −
8 <fmt:timeZone>
Specifies the time zone for any time formatting or parsing actions nested in its body.
9 <fmt:setTimeZone>
Stores the given time zone in the time zone configuration variable
10 <fmt:message>
Displays an internationalized message.
11 <fmt:requestEncoding>
Sets the request character encoding
SQL Tags
The JSTL SQL tag library provides tags for interacting with relational databases
(RDBMSs) such as Oracle, mySQL, or Microsoft SQL Server.
XML tags
The JSTL XML tags provide a JSP-centric way of creating and manipulating the XML
documents. Following is the syntax to include the JSTL XML library in your JSP.
The JSTL XML tag library has custom tags for interacting with the XML data. This includes
parsing the XML, transforming the XML data, and the flow control based on the XPath
expressions.
Before you proceed with the examples, you will need to copy the following two XML and
XPath related libraries into your <Tomcat Installation Directory>\lib −
Evaluates a test XPath expression and if it is true, it processes its body. If the test
condition is false, the body is ignored.
5 <x:forEach>
To loop over nodes in an XML document.
6 <x:choose>
Simple conditional tag that establishes a context for mutually exclusive conditional
operations, marked by <when> and <otherwise> tags.
7 <x:when >
Subtag of <choose> that includes its body if its expression evalutes to 'true'.
8 <x:otherwise >
Subtag of <choose> that follows the <when> tags and runs only if all of the prior
conditions evaluates to 'false'.
9 <x:transform >
Applies an XSL transformation on a XML document
10 <x:param >
Used 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 −
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.
The following URL will pass two values to HelloForm program using the GET method.
http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Below is the main.jsp JSP program to handle input given by web browser. We are going
to use the getParameter() method which makes it very easy to access the passed information −
<html>
<head>
</head>
<body>
<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 an example that passes two values using the HTML FORM and the submit
button. We are going to use the same JSP main.jsp to handle this input.
<html>
<body>
<br />
</form>
</body>
</html>
<html>
<head>
</head>
<body>
<center>
<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>
<br />
</form>
</body>
</html>
Checkboxes are used when more than one option is required to be selected.
Following is an example HTML code, CheckBox.htm, for a form with two checkboxes.
<html>
<body>
</form>
</body>
</html>
Following is main.jsp JSP program to handle the input given by the web browser for the checkbox
button.
<html>
<head>
</head>
<body>
<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>
<html>
<head>
</head>
<body>
<center>
<th>Param Name</th>
<th>Param Value(s)</th>
</tr>
<%
while(paramNames.hasMoreElements()) {
%>
</table>
</center>
</body>
</html>
<html>
<body>
</form>
</body>
</html>