KEMBAR78
Server-Side Programming Guide | PDF | Computers
0% found this document useful (0 votes)
104 views74 pages

Server-Side Programming Guide

Uploaded by

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

Server-Side Programming Guide

Uploaded by

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

CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

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.

3.1: An Introduction to Server Side Programming

SERVER-SIDE PROGRAMMING
Server-Side Programming means that writing scripts that are executed on
the server and are then translated into HyperText Markup Language (HTML)
which can be viewed by all web browsers.

Server-Side Programming Language:


A language used to develop programs that run on the server is called
Server-Side Programming Language.

Difference between Server-Side Scripting and Client-Side Scripting:

S. No. Client-Side Scripting Server-Side Scripting


Client-side scripting is used Server-side scripting is used to
when the browser already has create dynamic pages based on
1. all the code & the page is browser request.
altered on the basis of user
input.
Web browser executes the Web server executes the server-
2.
client-side scripting. side scripting.
The browser receives the page Server executes server-side
sent by the server & executes scripts to send out a page but it
3.
the client-side scripts. does not execute client-side
scripts.
Client-side scripting cannot be Server-side scripting is used to
4. used to connect to the connect to the databases on the
databases. web server.

1
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Client-side scripting cannot Server-side scripting can access


5. access file system on the web the file system on the web server.
server.
Responses from client-side Responses from server-side
scripts are faster because the scripts are slower because the
6.
scripts are processed on local scripts are processed on remote
computer. computer.
7. Less Secure More Secure
8. Less Customization High Customization
9. More tasks at the browser More tasks at the server
Examples: JavaScript, Examples: Servlets, JSP, PHP,
10. VBScript, Dart etc., ASP, ASP.net, Ruby, Perl,
Python, ColdFusion.

3.2: Servlets

3.2.1: What are Servlets?

Servlets are Java programs that run on a web server and act as a middle
layer between a requests coming from a web browser or other HTTP client
and databases or applications on the server.

Using servlets,
 We can collect input from users through web page forms, present
records from a databases (or) another source and create web pages
dynamically.
 We can develop sites with secure access, interact with DB, and
maintain unique session info of each client.

Types of web server responses:

1. Static Response: HTML document retrieved from the file system and
returned to the client is called static response.
2. Dynamic Response: HTML document is generated by a program in
response to an HTTP request.

2
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3.2.2: Java Servlet Architecture

 Servlet architecture comes under a java programming language used


to create dynamic web applications.
 Mainly servlets are used to develop server-side applications.
 Servlets are very robust and scalable.
 There are two types of Servlets-
 1.Generic Servlets
 2.HTTPServlets.
 Servlets can be created in three possible ways
1) Implementing Servlet Interface
2) Extending Generic Servlet.
3) Extending HTTPServlet.
 Three life cycle methods available with servlets are init(), service() and
destroy(). Every servlet should override these methods.

Components of Servlet Architecture


Below is the diagram to show how components working on servlet
architecture.

3
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

1. Client
In this architecture, the web browser acts as a Client. Client or user
connected with a web browser. The client is responsible for sending requests
or HttpRequest to web server and processing responses received by the Web
server.

2. Web Server
Web server controls how web user access hosted files and it is responsible
for processing user request and responses. Here server is a software that
understand URLs and HTTP protocol. Whenever browser needs to request
file on the webserver, it process client request using HTTP request, if it finds
requested file sends it back to browser through HTTP Response. There are
two types’ web servers Static and Dynamic webservers.in static web server
sends the file as it is but in dynamic webserver hosted file is updated before
it is sent to the browser.

3. Web Container
Web container is the component in the webserver it interacts with Java
servlets. A web container is responsible for managing the lifecycle of servlets
and it also performs the URL mapping task. Web container handles the
requests of servlets, JSP and other files at the server-side. The important
tasks performed by servlets are loading and unloading servlets, creating and
managing requests and response objects and performs the overall tsk of
servlet management.

Servlet Request Flow


Every servlet should override the following 3 methods namely:
1. init()
2. service()
3. destroy()

Following are the steps how servlet request has been processed consider the
above diagram.
 The client sends a request.
 Web Server accepts the request and forwards it to the web container.
 Web container searches web.xml file for request URL pattern and gets
the address of the servlet.

4
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 If the servlet is not yet instantiated it will be instantiated and


initialized by calling the init() method.
 The container calls public service() by passing ServletRequest and
ServletResponse objects.
 Public service() method typecast ServletRequest and ServletResponse
object to HttpServletRequest and HttpServletResponse objects
respectively.
 Public service() method calls protected service().
 Protected service() method checks the client request & corresponding
do___() method is called.
 Request is handled by sending the result generated by do___() to the
client.

Uses of Servlet Architecture


Let us see some of the uses of servlet that are given below:
1. Servlets are used to form data manipulation like accepting form data
and generating dynamic HTML pages.
2. Servlets helps in developing server load balancing applications. Where
load balancing is among different servers.
3. Servlets are used as the middle tier in enterprise network platforms for
connecting the SQL database.
4. Servlets can be integrated with applets to provide high-level
interactivity and dynamic web content generation.
5. Servlet is used to develop applications where this act as an active
agent in the middle tiers, where they share data with each other.
6. Since the servlet supports various protocols like HTTP, FTF, etc. this
helps in developing applications like file server applications, chat
enabled applications.

Advantages
Below are some important advantages of the servlet as follows:
 Servlets are server independent, as they are compatible with any web
server. Compared to other server-side web technologies like ASP and
JavaScript these are server-specific.
 Servlets are protocol-independent i.e. it supports FTP, SMTP, etc.
Mainly it provides extended support to HTTP protocol functionality.

5
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 Servlets are persistent because it remains in memory until explicitly


destroyed this helps in several request processing and one database
connection can handle several database requests.
 Servlets are portable since the servlets are written in java they are
portable and supports any web server.
 Faster in execution, servlets are compiled into byte code execute more
quickly compared to other scripting languages. Byte code conversion
gives better performance and helps in type checking and error.

Disadvantages
 Designing a servlet can be pretty laborious.
 Exceptions need to be handled while designing a servlet since they are
not thread-safe.
 Developers may need additional skills to program a servlet.

3.2.3: Servlet Life Cycle

A servlet life cycle can be defined as the entire process from its
creation till the destruction.

The following are the paths followed by a servlet:

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


2) The servlet calls service() method to process a client's request.
3) The servlet is terminated by calling the destroy() method.
4) Finally, servlet is garbage collected by the garbage collector of the
JVM.

Life cycle methods of a Servlet:

1) init()
2) service()
3) destroy()

6
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

1) The init() method:

This method is called when the servlet is first created. It is called only once
during its lifecycle and not called again for each user request. So, it is used
for one-time initializations, just as with the init method of applets.

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


corresponding to the servlet, but you can also specify that the servlet be
loaded when the server is first started.

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

The init method definition looks like this:


public void init() throws ServletException {
// Initialization code...
}

7
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

2) The service() method :

The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted
response back to the client.
Each time the server receives a request for a servlet, the server spawns a
new thread and calls service. The service() method checks the HTTP request
type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut,
doDelete, etc. methods as appropriate.

Here is the signature of this method:

public void service(ServletRequest request, ServletResponse response)


throws ServletException, IOException{
}

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

The doGet() and doPost() are most frequently used methods with in each
service request. Here are the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML
form that has no METHOD specified and it should be handled by doGet()
method.

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
// Servlet code
}

8
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

The doPost() Method

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

public void doPost(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
// Servlet code
}

3) The destroy() method :

The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database
connections, halt background threads, write cookie lists or hit counts to
disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this:

public void destroy() {


// Finalization code...
}

Structure of a servlet program

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


import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html"); // content type of the response
PrintWriter out = response.getWriter(); // used to create a response as a
Html doc try {

9
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

out.println("<html>");

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

}catch(Exception e){}
}
}
}

Servlets - Examples

Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface.
Web application developers typically write servlets that extend
javax.servlet.http.HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests.

Sample Code for Hello World:

Following is the sample source code structure of a servlet example to write


Hello World:

// Import required java libraries import java.io.*;


import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class

public class HelloWorld extends HttpServlet { private String message;


public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException

10
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<html><body><b>" + message + “</b></body></html>");
out.close();
}

public void destroy() { }


}

Output:
Finally type http://localhost:8080/HelloWorld in browser's address box. If
everything goes fine, you would get following result:

3.2.4: Parameter data and Query Strings

Servlet has methods to access data contained in HTTP Request (URL) sent to
the server from the browser.
The Query String portion of the HTTP request is so called parameter
data.
For example,

http://www.example.com/servlet/PrintThis?name=Raj&color=Red

where,
the portion after the ? is called a query string.

11
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 Here it is “name=Raj&color=Red”, in which name and color are


parameter names and “Raj” and “Red” are parameter values.
 PrintThis is a servlet filename and
 servlet is a directory.
 Multiple parameters are separated by &.
 All parameter values are strings by default.
 Parameter names and values can be any 8-bit characters.

The following methods are used to process these parameter data in servlets.

The following program explains how to process these parameter names and
values as well as path of the resource using servlet.

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

12
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("Servlet file NewServlet is at: " + request.getContextPath());
Enumeration para1=request.getParameterNames();
while(para1.hasMoreElements())
{
out.println("Parameter name:"+para1.nextElement());
}
String name = request.getParameter("name");
String id = request.getParameter("id");
out.println("Name:" + name);
out.println("Id:" + id);
out.println("</body>");
out.println("</html>");
}catch(Exception e){}
}
}
}

 The method getContextPath() of HttpServeltRequest object is used to get


the location of the resource
 The method getParameter() is used to get the value of the parameter. The
method getParameterNames() is used to return the paranameter names as
well. It returns enumeration.
 The following code in the above program is used to retrieve the parameter
names from the enumeration.
Enumeration para1=request.getParameterNames();
while(para1.hasMoreElements())
{
out.println("Parameter name:"+para1.nextElement());
}

13
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Output:

3.2.5: Form GET and POST Actions

Definition and Usage

The method attribute specifies how to send form-data (the form-data is sent
to the page specified in the action attribute).
The form-data can be sent as URL variables (with method="get") or as HTTP
post transaction (with method="post").

Notes on GET:
 It is used to process the query string which is part of URL
 Appends form-data into the URL in name/value pairs
 The length of a URL is limited (about 3000 characters)
 It is recommended when parameter data is not stored but used only to
request information.
 Never use GET to send sensitive data! (will be visible in the URL)
 Useful for form submissions where a user wants to bookmark the
result
 GET is better for non-secure data, like query strings in Google

Notes on POST:
 It is used to process the query string as well as to store the data on
server.
 Appends form-data inside the body of the HTTP request (data is not
shown in URL)
 Has no size limitations.
 It is recommended if parameter data is intended to cause the server to
update stored data

14
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 Most browsers will warn you if they are about to resubmit POST data
to avoid duplicate updates
 Form submissions with POST cannot be bookmarked
BASIS FOR
GET POST
COMPARISON

Parameters are placed URI Body


inside

Purpose Retrieval of documents Updation of data

Query results Capable of being Cannot be bookmarked.


bookmarked.

Security Vulnerable, as present in Safer than GET method


plaintext

Form data type Only ASCII characters are No constraints, even


constraints permitted. binary data is permitted.

Form data length Should be kept as Could lie in any range.


minimum as possible.

Visibility Can be seen by anyone. Doesn't display


variables in URL.

Variable size Up to 2000 character. Up to 8 Mb

Caching Method data can be Does not cache the data.


cached.

Example:

The following program explains how to send the data to server from a web
page and the same how to receive it from the server.

Html for creating a web page

<html>
<head>
</head>

15
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

<body>
<pre>
<form action="NewServlet" method="post">
First Name: <input type="text" name="t1" />
Last Name: <input type="text" name="t2" />
Age: <input type="text" name="t3" />
E-mail:<input type="text" name="t4" />
<input type="submit" value="Submit" />
<form>
</pre>
</body>
</html>

Servlet for processing the data coming from this web page

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NewServlet extends HttpServlet
{
public void goPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet NewServlet</title>");
out.println("</head>");
out.println("<body>");
String s1 = request.getParameter("t1");
String s2 = request.getParameter("t2");
String s3 = request.getParameter("t3");
String s4 = request.getParameter("t4");
out.println("First Name:" + s1);
out.println("Last Name:" + s2);

16
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

out.println("Age:" + s3);
out.println("E-mail:" + s4);
out.println("</body>");
out.println("</html>");
} catch(Exception e) {}
}
}
Output

GET and POST methods in HTTP with examples.

 Handling GET request:

Login.html
<html>
<body>
<form action="login" method="get">
<table>
<tr>
<td>User</td>
<td><input name="user" /></td>
</tr>
<tr>
<td>password</td>
<td><input name="password" /></td>
</tr>
</table>
<input type="submit" />
</form>
</body>
</html>

17
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

create a Servlet which receives the request in /login , which is the indicated
direction in the action attribute of the tag <form> of login.html

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) && "bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp, String msg)
throws IOException
{
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println(msg);
out.println("</body></html>");
}
}
We compilate this Servlet and we include LoginServlet.class in the folder
/WEB-INF/classes. We modify web.xml to link /login with this Servlet.

web.xml
<web-app>

18
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

<servlet>
<servlet-name>hello</servlet-name>
<servlet-class> hello </servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login-servlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
We restart the server, open the page login.html, write an "x" in user, write
an "x" in password and click on the submit button.

Logging in with Wrong credentials

Logging in with right credentials

19
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 Handling POST request:

<html>
<body>
<form action="login" method="post">
<table>
<tr><td>User</td> <td><input name="user" /></td></tr>
<tr><td>password</td> <td><input name="password" /></td></tr>
</table>
<input type="submit" />
</form>
</body>
</html>

Reusing login.html, we will use the following error.


 What is happening here is that we haven´t implemented the doPost
method (we have only implemented doGet), so our Servlet is not able to
receive POST requests. In the following code we can see the necessary
modifications to make it work.

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

20
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

import javax.servlet.http.*;
public class LoginServlet extends HttpServlet
{
protected void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
String user = req.getParameter("user");
String pass = req.getParameter("password");
if ("balamurugan".equals(user) && "bala1234".equals(pass))
{
response(resp, "login ok");
}
else
{
response(resp, "invalid login");
}
}
private void response(HttpServletResponse resp, String msg)
throws IOException
{
PrintWriter out = resp.getWriter();
out.println("<html><body>");
out.println(msg);
out.println("</body></html>");
}
}

We can see that the parameters of the URL have disappeared.

21
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3.2.6: Session Handling


There are two types of protocols:
1. Stateful Protocol: In this protocol, part of data is exchanged between
client and server and these protocols always keep track of
communication sessions.
2. Stateless protocol: It is a protocol in which neither client nor server
keeps track of the state of communication session.
 A session is simply the limited interval of time in which two systems
communicate with each other.
 Tracking is the recording of the thing under session.
 Session Tracking is remembering and recording of client conversion in span
of time.
 Formal Definition:
Session Tracking is a technique by which we can keep track of previous
sessions (conversations) held between server and the browser by using
the session ID. It is also called as session management.
 Session ID: It is a unique identification number to identify HTTP requests.
For sending all state information to and fro between the browser and server,
session ID is used.

 If web application is capable of remembering and recording of client


conversion in span of time then that web application is called as stateful
web application.

 Why need/use Session Tracking?


 Http protocol is stateless, that means, each time user requests to the
server, server treats the request as the new request. So we use session
tracking technique to keep track of previous conversations held between

22
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

client and server and to maintain the state of a user to recognize a


particular user.
 Session Tracking is useful for online shopping, mailing application, E-
Commerce application to track the conversion.

Session Tracking Techniques

Servlet technology allows four techniques to track conversion, they are;

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

1. Cookies

 A cookie is a name-value pair of information that a web server sends


to a client machine as a part of an HTTP response.
 The browser then returns these cookies unchanged to the server to
indicate the state of the conversation.
 By returning a cookie to a web server, the browser provides the server a
means of connecting the current page view with the previous page view.
Example:

23
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

(i) Browser connects to the server www.mypage.com by making a


request.

(ii) The server then replies in the form of HTTP response, session id is
given in the form of cookie.

(iii) Another request to the same server. By including cookie which


contain sid=xf1234ad server knows that this request is related to the
previous one. Then server-browser can keep track of current session.

Types of Cookie
There are 2 types of cookies in servlets.
1. Non-persistent cookie
2. Persistent cookie
1. Non-persistent cookie
It is valid for single session only. It is removed each time when user closes
the browser.
2. 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 sign out.

24
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Advantage of Cookie
 Simplest technique of maintaining the state.
 Cookie are maintained at client side so they do not give any burden to
server.
 All server side technology and all web server, application servers
support cookies.
 Presistent cookies can remember client data during session and after
session with expiry time.
Limitation of Coockie
 It will not work if cookie is disabled from the browser.
 Cookies are text files, It does not provides security. Anyone can change
this file.
 With cookies need client support that means if client disable the
coockies then it does not store the client location.
 Cookies cannot store java objects as values, they only store text or
string.

2. Hidden Form Fields


 Tracking client conversion using HTML hidden variables in secure
manner is known as hidden form field.
 In this method, when browser makes a request to the server for some
web page, the server responds by inserting hidden form fields in the
HTML page containing the session id and then sends the page to the
browser.

25
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 Each time when web browser sends request back, then session_id value
can be used to keep track of the 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.
Hidden Form Field Advantage
 Basic knowledge of html is enough to work with this technique.
 It will always work whether cookie is disabled or not.
 Hidden boxes resides in web pages of browser window so they do not
provide burden to the server.
 This technique can be used along with all kind of web server or
application server.
Hidden Form Field Dis-Advantage
 More complex than URL Rewriting.
 It is maintained at server side.
 Extra form submission is required on each pages.
 Hidden form field can not store java object as values. They only store
text value
 It Also increase network traffic because hidden boxes data travels over
the network along with request and response.
 Hidden boxes does not provides data security because their data can be
view through view source option.

Example of session tracking by using Hidden Form Field


index.html

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

FirstServlet.java

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

26
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

public class FirstServlet extends HttpServlet {


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

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

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

//creating form that have invisible textfield


out.print("<form action='servlet2'>");
out.print("<input type='hidden' name='uname' value='"+n+"'>");
out.print("<input type='submit' value='continue'>");
out.print("</form>");
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();

27
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

//Getting the value from the hidden field


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

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

web.xml

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

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

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

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

</web-app>

28
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3. URL Rewriting
 In URL rewriting, we append a token or identifier to the URL of the
next Servlet or the next resource. We can send parameter name/value
pairs using the following format:
url?name1=value1&name2=value2&??
 A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can
use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting


1. It will always work whether cookie is disabled or not (browser
independent).
2. Extra form submission is not required on each pages.
Disadvantage of URL Rewriting
1. It will work only with links.
2. It can send only textual information.
Example of using URL Rewriting
In this example, we are maintaining the state of the user using link. For this
purpose, we are appending the name of the user in the query string and
getting the value from the query string in another page.

index.html
1. <form action="servlet1">

29
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

2. Name:<input type="text" name="userName"/><br/>


3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse respon
se){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15.
16. //appending the username in the query string
17. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
18.
19. out.close();
20.
21. }catch(Exception e){System.out.println(e);}
22. }
23.
24. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;

30
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse respon
se)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }

web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>

31
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

4. HTTPSession Interface

An object of HttpSession can be used to perform two tasks:

1) bind objects
2) View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.

A. Creating a Session

 Java Servlet API supports the session concept by associating an


HTTPSession object with each session maintained by the server.
 Each object stores the session ID for its session.
 HTTPSession object is created by the server when a servlet calls the
getSession() method on its HttpServletRequest parameter and the
associated HTTP request does not contain a valid session ID.
 The getSession() method returns the newly created object.
 If the HTTP request contains a valid session ID, then a call to
getSession() returns the previously created HTTPSession object
containing this session ID.

B. Storing and Retrieving Session Attributes:

A session attribute is a name-value pair that is stored in the HttpSession


object.

The methods used to store and retrieve attributes are:

32
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

i) setAttribute(String name, Object obj)


Create or overwrite an attribute having the given name with given
object value.
ii) getAttribute(String name)
Returns the value of the specified attribute (or) null if there is no
attribute in HttpSession object.
iii) removeAttribute(String value)
Removes the specified attribute from HttpSession object.
iv) getAttributeName()
Returns the array of all attribute names associated with the
HttpSession object.

C. Session Termination:

By default, each session expires if a server determines length of time elapses


between a session’s HttpRequest. Then the server destroys the
corresponding session object.

Methods Used:
i) setMaxInactiveInterval(int)
This method takes an integer argument representing a number of
seconds.
After the specified time elapses, the user’s session will expire.
ii) invalidate()
If the timer completes before the next request containing the session
ID is received, the server calls the invalidate() directly at any time in
order to terminate the running session.
Example:

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

@WebServlet(urlPatterns = {"/SessionServlet"})
public class SessionServlet extends HttpServlet {
@Override

33
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

protected void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
String heading;
Integer count=(Integer)session.getAttribute("cnt");
if(count==null)
{
count=new Integer(0);
heading="Welcome!Thisis your first Access";
}
else
{
heading="Welcome once again";
count=new Integer(count.intValue()+1);
}
session.setAttribute("cnt",count);
out.println("<html><body><center>");
out.println("<h1>"+heading+"</h1><br>");
out.println("<h2> No of previous Access = "+count+"</h2>");
session.setMaxInactiveInterval(2*60*60);
out.println("<h3> Time Out Period is "+session.getMaxInactiveInterval());
out.println("</h3></body></html>");
}
}

34
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3.2.7: Understanding Cookies

35
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

36
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

37
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

38
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3.2.8: Database Connectivity

39
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

40
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

41
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

42
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

43
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

44
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

45
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

46
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

47
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3.3.1: Understanding JSP

Java Server Page is a kind of Server-Side Scripting Language that enables


user to embed java code with HTML elements for the creation of
dynamic, platform-independent method for building web apps.
JSP = Java + HTML + servlet
 JavaServer 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
 Java Server Pages (JSP) is a technology for developing web pages that
support dynamic content which helps developers insert java code in HTML
pages by making use of special JSP tags, most of which start with <% and
end with %>.
 A Java Server Pages component is a type of Java servlet that is designed to
fulfill the role of a user interface for a Java web application.
 Web developers write JSPs as text files that combine HTML or XHTML
code, XML elements, and embedded JSP actions and commands.
 Using JSP, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.

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

1.1: JSP – Architecture:


The web server needs a JSP engine ie. container to process JSP pages. The
JSP container is responsible for intercepting requests for JSP pages. 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.

48
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 JSP Processing (Working 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 .jsp instead of .html.
 The JSP engine loads the JSP page from disk and converts it into
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.
 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:

49
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

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.

 Advantages of JSP:

1. Extension to Servlet: JSP technology is the extension to servlet


technology. We can use all the features of servlet in JSP
2. Dynamic contents can be handled using JSP because JSP allows
scripting and element based programming.
3. We can use implicit objects, predefined tags, expression language and
Custom tags in JSP that makes JSP development easy.
4. JSP is useful for server side programming.
5. JSP programming is easy to learn and easy to implement.
6. JSP programming environment provides the separation between
presentation logic and business logic.
7. JSP provides optional mechanism in configuring web application file
(web.xml).
8. JSP allows creating and using our own custom tag libraries. Hence any
application specific Requirements can be satisfied using custom tag
libraries. This helps the developer to develop any kind of application.

50
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

9. Fast Development: No need to recompile and redeploy If JSP page is


modified, we don't need to recompile and redeploy the project.

3.3.2: JSP - Life Cycle:

A JSP life cycle can be defined as the entire process from its creation
till the destruction which is similar to a servlet life cycle with an
additional step which is required to compile a JSP into servlet.
The following are the paths followed by a JSP
 Compilation  Initialization  Execution  Cleanup
The four major phases of JSP life cycle are very similar to Servlet Life
Cycle and they are as follows:
 JSP Compilation:
When a browser asks for a JSP, the JSP engine first checks to see
whether it needs to compile the page. If the page has never been
compiled, or if the JSP has been modified since it was last compiled, the
JSP engine compiles the page.
The compilation process involves three steps:
 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.

51
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 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:
public void jspInit(){
// Initialization code...
}
Typically initialization is performed only once and as with the servlet init
method, you generally initialize database connections, open files, and
create lookup tables in the jspInit method.

 JSP Execution:
This phase of the JSP life cycle represents all interactions with requests
until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:
void _jspService(HttpServletRequest request,
HttpServletResponse response)
{
// Service handling code...
}
The _jspService() method of a JSP is invoked once per a request and is
responsible for generating the response for that request and this method
is also responsible for generating responses to all seven of the HTTP
methods ie. GET, POST, DELETE etc.

 JSP Cleanup:
The destruction phase of the JSP life cycle represents when a JSP is
being removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup,
such as releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
52
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

// Your cleanup code goes here.


}

3.3.3: JSP vs. Servlet

S.No JSP Servlets


JSP is a webpage scripting Servlets are Java programs that
1. language that can generate are already compiled which also
dynamic content. creates dynamic web content.
In MVC, servlet act as a
2. In MVC, JSP act as a view.
controller.
It’s easier to code in JSP than in
3. Its little much code to write here.
Java Servlets.
JSP are generally preferred when Servlets are best for use when
4. there is not much processing of there is more processing and
data required. manipulation involved.
JSP run slower compared to
Servlet as it takes compilation Servlets run faster compared to
5.
time to convert into Java JSP.
Servlets.
The advantage of JSP
programming over servlets is that There is no such custom tag
6.
we can build custom tags which facility in servlets.
can directly call Java beans.
We can achieve functionality of
There are no such methods for
7. JSP at client side by running
servlets.
JavaScript at client side.
JSP is almost a replacement of
Servlets, (by large, the better
Servlets are difficult to code
8. word is extension of Servlets),
where coding decreases more
than half

53
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

In JSP, static code and dynamic


code are separated.
Example: Both static code and dynamic
Hello Mr. // static content as code are put together
9. HTML code Example:
<%= str %> // dynamic content out.println(“Hello Mr.” + str + ”
as JSP code you are great man”);
you are great man // static
content as HTML code.
In JSP, both presentation layer
Both presentation layer and
and business logic layer can be
10. business logic layer put together
separated with the usage of
in Servlets
JavaBeans.
Writing alias name in <url- Writing alias name in <url-
11. pattern> tag of web.xml is pattern> tag of web.xml is
optional in JSP. mandatory in Servlets
JSP needs no compilation by the
In Servlets, the Programmer
Programmer. Programmer
12. compiles manually a Servlet file
deploys directly a JSP source
and deploys a .class file in server.
code file in server.

3.3.4: BASICS OF JSP

[State and explain the information in a JSP document]


JSP page is a simple web page which contains the three types of
information:
1. JSP Markup
2. JSP Expression Language expressions
3 Template data

1. JSP Markup
Three types of markup elements:
1.1 Scripting Elements
 Ex: scriptlet
 Inserts Java code into servlet

54
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

1.2 Directive Elements


 Ex: directive.page
 Instructs JSP translator
1.3 Action Elements
 Standard: provided by JSP itself
 Custom: provided by a tag library such as JSTL

1.1: Scripting elements:


The scripting elements provides the ability to insert java code inside
the jsp. There are three types of scripting elements:
i. Scriptlet tag
ii. Expression tag
iii. Declaration tag
i. JSP scriptlet tag
A scriptlet is a fragment of Java code that is embedded within the
JSP document.
A scriptlet can contain any number of JAVA language statements,
variable or method declarations, or expressions that are valid in the
page scripting language.
Syntax:
<% java source code %>
Example: In this example, we
are displaying a welcome
message.
1. <html>
2. <body>
3. <h1><center>
4. <% out.print("welcome to js
p"); %>
5. </center></h1>
6. </body>
7. </html>
Output:

55
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Example of JSP scriptlet tag that prints the user name


In this example, we have created two files index.html and welcome.jsp.
The index.html file gets the username from the user and the welcome.jsp
file prints the username with the welcome message.
File: index.html 6. %>
1. <html> 7. </form>
2. <body> 8. </body>
3. <form action="welcome.jsp" 9. </html>
> Output:
4. <input type="text" name="u
name">
5. <input type="submit" value
="go"><br/>
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%
4. String name=request.getPar
ameter("uname");
5. out.print("welcome "+name);

ii. Expression tag


A JSP expression element contains a scripting language expression
that is evaluated, converted to a String, and inserted where the
expression appears in the JSP file. So you need not write out.print() to
write data. It is mainly used to print the values of variable or method.
Syntax: <%= statement %>
Example of JSP expression tag:
In this example of jsp expression tag, we are simply displaying a welcome
message.
1. <html>
2. <body>

56
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3. <%= "welcome to jsp" %>


4. </body>
5. </html>
Note: Do not end your statement with semicolon in case of
expression tag.

Example of JSP expression tag that prints current time:


To display the current time, we have used the getTime() method of
Calendar class. The getTime() is an instance method of Calendar class, so
we have called it after getting the instance of Calendar class by the
getInstance() method.
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </html>

Output:

Example of JSP expression tag that prints the user name:


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

57
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname"><br/>
5. <input type="submit" value="go">
6. </form>
7. </body>
8. </html>
File: welcome.jsp
1. <html>
2. <body>
3. <%= "Welcome "+request.getParameter("uname") %>
4. </body>
5. </html>
Output: Refer the previous example in scriptlet tag

iii. Declaration Tag:


The JSP declaration tag is used to declare fields and methods.
The code written inside the jsp declaration tag is placed outside the
service() method of auto generated servlet. So it doesn't get memory at
each request.

Syntax of JSP declaration tag:


<%! field or method declaration %>

Example of JSP declaration tag that declares field:


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

index.jsp 6. </html>
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable i
s:"+data %>
5. </body>

58
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Example of JSP declaration tag that declares method:


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

index.jsp 10. </html>


1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n;
6. }
7. %>
8. <%= "Cube of 3 is:"+cub
e(3) %>
9. </body>

1.2 JSP Directives:


JSP directives provide directions and instructions to the container,
telling it how to handle certain aspects of JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually
has the following form:

Syntax: <%@ directive attribute="value" %>

59
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

There are three types of directive tag:


Directive Description
Defines page-dependent attributes, such as
<%@ page ... %> scripting language, error page, and buffering
requirements.
<%@ include ... %> Includes a file during the translation phase.
Declares a tag library, containing custom actions,
<%@ taglib ... %>
used in the page

The page Directive:


The page directive is used to provide instructions to the container
that pertain to the current JSP page. You may code page directives
anywhere in your JSP page. By convention, page directives are coded at
the top of the JSP page.

Following is the basic syntax of page directive:

<%@ page attribute="value" %>

Attributes of JSP page directive


 import
 contentType
 extends
 info
 buffer
 language
 isThreadSafe
 autoFlush
 session
 pageEncoding
 errorPage
 isErrorPage

60
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

1) import
The import attribute is used to import class, interface or all the
members of a package. It is similar to import keyword in java class or
interface

Example of import attribute


1. <html>
2. <body>
3. <%@ page import="java.util
.Date" %>
4. Today is: <%= new Date() %
>
5. </body>
6. </html>

2)contentType
The contentType attribute defines the MIME(Multipurpose Internet
Mail Extension) type of the HTTP response.The default value is
"text/html;charset=ISO-8859-1".

Example of contentType
attribute
1. <html>
2. <body>
3. <center><h1><b>
4. <%@ page contentType=”ap
plication/msword” %>
5. Today is: <%= new java.util
.Date() %>
6. </b></h1></center>
7. </body>
8. </html>
3) errorPage
The errorPage attribute is used to define the error page, if exception
occurs in the current page, it will be redirected to the error page.

61
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Example of errorPage attribute


//index.jsp
1. <html>
2. <body>
3.
4. <%@ page language=”java” errorPage="myerrorpage.jsp" %>
5.
6. <%= 100/0 %>
7.
8. </body>
9. </html>

The include Directive:


The include directive is used to includes a file during the
translation phase. This directive tells the container to merge the content
of other external files with the current JSP during the translation phase.
You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows:
<%@ include file="url" >
Example of include directive
In this example, we are including the content of the header.html file. To
run this example you must create an header.html file.
1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </html>

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

62
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

We use the TLD (Tag Library Descriptor) file to define the tags.
The taglib directive declares that your JSP page uses a set of custom
tags, identifies the location of the library, and provides a means for
identifying the custom tags in your JSP page.
The taglib directive follows the following syntax:
<%@ taglib uri="uri" prefix="prefixOfTag" >

Where the uri attribute value resolves to a location the container


understands and the prefix attribute informs a container what bits of
markup are custom actions.

Example of JSP Taglib directive


In this example, we are using our tag named currentDate. To use this tag
we must specify the taglib directive so the container may get information
about the tag.
1. <html>
2. <body>
3. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag"
4. %>
5. <mytag:currentDate/>
6. </body>
7. </html>

3.3.5: JSTL ( JSP Standard Tag Library)

The JavaServerPages Standard Tag Library (JSTL) is a collection of


useful JSP tags which encapsulates the core functionality common
to many JSP applications.

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

63
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

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

 Classification of the JSTL Tags


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

Tag Name Description


The JSTL core tags provide variable support, URL management, flow
core tags control etc. The url for the core tag is http://java.sun.com/jsp/jstl/core .
The prefix of core tag is c.
The JSTL sql tags provide SQL support. The url for the sql tags is
sql tags
http://java.sun.com/jsp/jstl/sql and prefix is sql.
The xml sql tags provide flow control, transformation etc. The url for the
xml tags
xml tags is http://java.sun.com/jsp/jstl/xml and prefix is x.
The internationalization tags provide support for message formatting,
Formatting
number and date formatting etc. The url for the internationalization tags is
tags
http://java.sun.com/jsp/jstl/fmt and prefix is fmt.
The functions tags provide support for string manipulation and string
functions
length. The url for the functions tags is
tags
http://java.sun.com/jsp/jstl/functions and prefix is fn.

JSTL Core Tags


 The JSTL core tag provides variable support, URL management, flow
control etc.
 Following is the syntax to include the JSTL Core library in your JSP −
64
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

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

Example:

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


<html>
<head>
<title>Tag Example</title>
</head>
<body>
<c:out value="${'Welcome to javaTpoint'}"/>
</body>
</html>

65
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

JSTL Function Tags


 The JSTL function provides a number of standard functions, most of
these functions are common string manipulation functions.
 Following is the syntax to include the JSTL Functions library in your
JSP −
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

66
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Example:

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


<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:length() example</title>
</head>
<body>
<c:set var="str1" value="This is first string"/>
<c:set var="str2" value="Hello"/>
Length of the String-1 is: ${fn:length(str1)}<br>
Length of the String-2 is: ${fn:length(str2)}
</body>
</html>

JSTL 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.
 The JSTL formatting tags are used for internationalized web sites to
display and format text, the time, the date and numbers.

67
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

 Following is the syntax to include the JSTL Formatting tag library in


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

Example:

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


<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<head> <title>fmt:formatDate</title> </head>
<body>
<h2>Different Formats of the Date</h2>
<c:set var="Date" value="<%=new java.util.Date()%>" />
<p> Formatted Time :
<fmt:formatDate type="time" value="${Date}" />
</p>
<p> Formatted Date :
<fmt:formatDate type="date" value="${Date}" />
</p>
<p> Formatted Date and Time :
<fmt:formatDate type="both" value="${Date}" />
</p>
</body></html>

68
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

JSTL XML tags


 The JSTL XML tags are used for providing a JSP-centric way of
manipulating and creating XML documents.
 Following is the syntax to include the JSTL XML tag library in your
JSP −
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

Example:

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


<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<html>
<body>
<h2>Vegetable Information:</h2>
<c:set var="vegetable">
<vegetables>
<vegetable>
<name>onion</name>
<price>40/kg</price>
</vegetable>
<vegetable>
<name>Potato</name>
<price>30/kg</price>
</vegetable>
<vegetable>
<name>Tomato</name>

69
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

<price>90/kg</price>
</vegetable>
</vegetables>
</c:set>
<x:parse xml="${vegetable}" var="output"/>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[1]/name" /><br>
<b>Price of the Potato is</b>:
<x:out select="$output/vegetables/vegetable[2]/price" />
</body> </html>

JSTL 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.
 Following is the syntax to include the JSTL SQL tag library in your JSP
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

70
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Example:

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


<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<html>
<body>
<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/test"
user="root" password="1234"/>
<sql:query dataSource="${db}" var="rs">
SELECT * from Students;
</sql:query>
<table border="2" width="100%">
<tr>
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.id}"/></td>
<td><c:out value="${table.First_Name}"/></td>
<td><c:out value="${table.Last_Name}"/></td>
<td><c:out value="${table.Age}"/></td>
</tr>
</c:forEach>
</table>
</body></html>

71
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

3.3.6: Creating HTML forms by embedding JSP code

HTML form basically is a Graphic User Interface (GUI) which you present
to get the input data from users. Once users submit the form from the
client side, on the server side, you need to capture those data for further
processing such as business logic validation, saving the data into the
database and so on.

Example: (AuthorsForm.jsp)

<html>
<head>
<title>Echoing HTML Request Parameters</title>
</head>
<body>
<h3>Choose an author:</h3>

<form method="get">
<input type="checkbox" name="author" value="Tan Ah Teck">Tan
<input type="checkbox" name="author" value="Mohd Ali">Ali
<input type="checkbox" name="author" value="Kumar">Kumar
<input type="submit" value="Query">
</form>

72
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

<%
String[] authors = request.getParameterValues("author");
if (authors != null) {
%>
<h3>You have selected author(s):</h3>
<ul>
<%
for (int i = 0; i < authors.length; ++i) {
%>
<li><%= authors[i] %></li>
<%
}
%>
</ul>
<a href="<%= request.getRequestURI() %>">BACK</a>
<%
}
%>
</body>
</html>

73
CS8651 – Internet Programming Unit – 3 III Year / VI Semester CSE

Explanations
1. This HTML page has a form with 3 checkboxes. The "name=value"
pair of the checkboxes is "author=so_and_so". No "action" attribute
is specified, the default "action" is the current page (i.e. the query
will be sent to the same page).
2. The JSP scriptlet checks if the query parameter "author" exists to
decide whether to dynamically generate the enclosed codes. "author"
parameter is absent when the page is first requested. Once the
client fills in the form (by checking the boxes) and submits the form,
"author" will be present in the HTTP request, and submitted to
the same page for processing (with the default <form>’s "action"
attribute).
3. The request.getParameterValues() is used to retrieve all the values
of the query parameter. The values are echoed back using an
unordered list.

74

You might also like