SlideShare a Scribd company logo
1 of 51
Download to read offline
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
1 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
UNIT II SERVER SIDE PROGRAMMING
Servlet - Strengths - Architecture -Life cycle- Generic and HTTP Servlet - Passing
parameters- Server Side Include- Cookies- Filters.
JSP - Engines-Syntax - Components - Scriplets - JSP Objects - Actions -Tag Extensions -
Session Tracking - Database connectivity - Sql statements.
J2EE - Introduction - Beans - EJB.
SERVLET
What are Servlets?
 Java servlets are small, platform-independent Java programs that can be used to
extend the functionality of a Web Server.
 Servlets are not tied to a specific client-server protocol but they are most
commonly used with HTTP and the word "Servlet" is often used in the meaning
of "HTTP Servlet".
 It is available and runs on all major web and application servers. It is based on
Java. Hence it is platform and server independent.
Functions of Servlets
 Dynamically build and return an HTML file based on nature of client request.
 Process user input passed by an HTML form and return an appropriate response.
 Provide user authentication and Security mechanisms.
 Interact with server resources such as databases, other applications and network
files to return useful information to the client.
 Allow the server to communicate with a client applet via a custom protocol and
keep the connection open throughout the conversation.
 Automatically attach web page design elements, such as headers or footers, to all
pages returned by server.
 Forward requests from one server to another for load balancing purpose.
Role of Servlets in Web Application Design
 Servlets can read explicit data sent in by the browser client. This data can come
from an HTML page into which user has entered data or even an applet. Servlets
can also read implicit request data which is sent by browser as part of request
header.
 Servlets can dynamically generate and send content back to client as a response.
This process may involve talking to databases, executing an RMI call, executing
another server-side component and so on.
 The response sent can be in form of pure HTML, plain text, XML, GIF images or
even as compressed data.
 Servlets can also communicate with one another for load balancing purposes.
HTTP is essentially a stateless protocol. However, many applications need to
manage state on top of this stateless protocol.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
2 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2.1 STRENGTHS / ADVANTAGES OF SERVLETS
1.Compilation: Compilation offers the advantages of strong error and type checking.
Since many errors are flushed out during the compilation, servlets are more stable and
easier to develop and debug.
2.Crash Resistance: The JVM does not allow servlets direct access to memory locations,
thereby eliminating crashes that results from invalid memory accesses. In addition,
before execution, the JVM verifies that compiled Java class files are valid and do not
perform illegal operations.
Finally, rather than crashing, the JVM will propagate an exception up the calling
chain it is caught. Thus, a poorly written or malicious servlet cannot crash server.
3.Cross-Platform: Since servlets are written in Java, they enjoy the same cross platform
support as any program. This "write once, run anywhere" capability allows servlets to
be easily distributed throughout the enterprise without rewriting for each platform.
4.Cross-Server: Servlets can be run on virtually every popular web server that is in use
today. More than a dozen software vendors currently provide native support for
servlets within their products. For those servers that do not currently offer native
servlet support, there are many third party add-ons that allow these servers to load and
run servers.
5.Durable: Servlets are durable objects and remain in memory until specifically
instructed to be destroyed. In addition, a servlet can create other durable objects for use
across many requests. For Example: Create a single database connection when servlet is
first loaded. This connection can then be shared across all requests.
6.Dynamically Loadable across the Network: Servlets can be dynamically loaded
either locally or from across the network. Dynamic loading ensures that unused servlets
do not consume precious server resources. They are only loaded when needed.
7.Extensible: Since servlets are written in Java, there is a wealth of third-party support
for writing and extending them. New development tools, Java class libraries and
database drivers are constantly becoming available and they all can be utilized by
servlets.
8.Multithreaded: Servlets allow client requests to be handled by separate threads
within a single process. Thus it requires far less overhead and executes much more
quickly than say a CGI program.
9.Protocol Independent: Servlets are completely protocol independent. Protocol
independence allows a servlet to be specially constructed to support FTP commands,
SMTP or POP3 e-mail functionality, Telnet sessions, NNTP newsgroup or any other
protocols.
The servlet API does an excellent job of providing strong support for common
HTTP functionality without sacrificing the ability to support other protocols.
10.Secure: Servlets are written in Java. Hence invalid memory access calls and strong
typing violations are not possible. Servlets use server's Security Manager for
customization and enforcement of specific security policies.
2.2 ARCHITECTURE
 A servlet, in its most general form, is an instance of a class which implements
javax.servlet.Servlet interface
 Most servlets extend one of the standard implementations of that interface,
namely javax.servlet.GenericServlet or javax.servlet.http.HtttpServlet.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
3 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Figure: Basic Servlet Architecture
2.2.1 Servlet API
 Servlets use classes and interfaces from two packages: javax.servlet and
javax.servlet.http.
 A servlet, in its most general form, is an instance of a class which implements the
javax.servlet.Servlet interface. Most Servlets, however, extend one of the
standard implementations of that interface, namely
javax.servlet.GenericServlet and javax.servlet.http.Httpservlet.
 A protocol-independent servlet should subclass GenericServlet, while an HTTP
servlet should subclass HTTPServlet, which is itself a subclass of GenericServlet.
 Notice that the classes do not belong to the core Java API. They are extensions to
the core API and hence javax.
2.2.2 GenericServlet
 It is protocol independent. It implements javax.servlet.GenericServlet.
 It makes writing servlets easier.
 It provides simple versions of init() and destroy() and of the methods in the
ServletConfig interface.
 It also implements the log method, declared in the ServletContext interface.
 All the lifecycle methods are implemented in GenericServlet class.
 To write a generic servlet, override the abstract service().
request
response
Figure: GenericServlet Class
Servlet
GenericServlet
HTTPServlet
MyServlet
GenericServlet
subclass
Web
Server
service()
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
4 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
i) ServletContext interface
 It defines a set of methods that a servlet uses to communicate with its servlet
container, for example, to get the MIME type of a file, dispatch requests, or write
to a log file.
 There is one context per "web application" per JVM.
 ServletContext attributes can be used to share information among group of
servlets.
 The ServletContext object is contained within the ServletConfig object, which the
Web server provides the servlet when the servlet is initialized.
ii) ServletConfig interface
 This is a servlet configuration object used by a servlet container used to pass
information to a servlet during initialization.
 It is implemented by GenericServlet.
 All of its initialization parameters can only be set in deployment descriptor. The
ServletConfig parameters are specified for a particular servlet and are unknown
to other servlets.
2.2.3 HttpServlet
 javax.servlet.http.HttpServlet
 It has a built-in HTTP protocol support.
 Its subclass must override at least one of the following methods: doGet(),
doPost(), doHead(), doTrace(), doPut(), doDelete().
 One must not override the service() method, since it dispatches a request to the
different doXXX() methods for different HTTP requests.
Figure: HttpServlet Class
 init() and destroy() can be overriden to manage resources that are held for the
life of servlet. Servlet can implement getServletinfo() to provide information
about itself.
 The service() method of HttpServlet dispatches a request to different Java
methods for different HTTP request methods. It recognizes the standard
HTTP/1.1 methods like GET, HEAD, PUT, POST, DELETE, OPTIONS and TRACE.
Other methods are answered with a Bad Request HTTP error.
 Do not override the service() method because it handles setup and dispatching
to all the doXXX() methods. Since service() method dispatches to doXXX()
methods, it passes its request and response objects to these methods.
Web
Server
HTTPServlet subclass
service()
doGet()
doPost()
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
5 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
 An HTTP servlet generally overrides doGet() to handle GET requests and
doPost() to handle POST type of requests.
Example:
import java.io.*;
// Servlets are not part of standard SDK, they are part of J2EE
import javax.servlet.*;
import javax.servlet.http.*;
//Servlets normally extend HttpServlet
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
//Setting the response type
res.setContentType("text/html");
// Getting PrintWriter object to send response to client
PrintWriter out = res.getWriter();
// Output to the client
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World </TITLE></HEAD>");
out.println("BODY");
out.println("<BIG> Hello World </BIG");
out.println("</BODY></HTML>");
}
};
2.3 LIFECYLCE
1. Servlet Interface Life Cycle Methods
init()
It is executed once when the servlet is first loaded.
service()
It is called in a new thread by server for each request.
destroy()
It is called when server deletes servlet instance.
2. Sequence of Life Cycle Methods
The servlet interface defines methods to be called only once during the servlet's
lifecycle. They are known as life-cycle methods and are called in the following sequence:
1. The init() method is guaranteed to be called only once during the servlet's lifecycle.
The servlet performs one-time setup procedures in this method. It stores the
ServletConfig object so that it can be retrieved later by calling the Servlet's
getServletConfig() method (This is handled by GenericServlet). The ServletConfig object
contains Servlet parameters and a reference to the Servlet's ServletContext.
2. service() method gets called every time a new request comes in. The method's called
concurrently( that is, multiple threads may call this method at the same time) so it
should be implemented in a thread-safe manner.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
6 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
3. When servlet needs to be unloaded(for example: since a new version should be
loaded or the server is shutting down), the destroy() method is called. This method is
guaranteed to be called only once during the servlet's lifecycle. All resources which
were allocated in init() should be released in destroy().
3. Steps of Life Cycle Methods
The process by which a server invokes a servlet can be broken down into the
nine steps
1. The server loads the servlet when the client first requests it or, if configured to do so,
at server start-up. The servlet may be loaded from either a local or remote location
using the standard Java class loading facility. This step is equivalent to the following
code:
Class c = Class.forName("edu.skcet.Myservlet");
2. The server creates one or more instances of the servlet class. Depending on the
implementation, the server may create a single instance that services all requests
through multiple threads or create a pool of instances from which one is chosen to
service each new request. This step is equivalent to the following Java code:
Servlet s= (Servlet) c.newinstance();
3. The server constructs a ServletConfig object that provides initialization information
to the servlet.
4. The server calls the servlet's init(ServletConfig cfg) method. The init() method is
guaranteed to finish execution prior to the servlet processing the first request. If the
server created multiple servlets instances (step 2), then the init method is called one
time for each instance.
5. The server constructs a ServletRequest or HttpServletRequest object from the data
included in the client's request. It also constructs ServletResponse or
HttpServletResponse object that provides methods for customizing the server's
response. The type of objects passed in these two parameters depend on whether the
server extends the GenericServlet class or the HttpServlet class, respectively.
6. The server calls the servlet's service() (or other, more specific method like doGet() or
doPost() for HTTP Servlets), passing the objects constructed in step 5 as parameters.
When concurrent requests arrive, multiple service() methods can run in separate
threads.
7. The service() method processes the client request by evaluating the ServletRequest
or HttpServletRequest object and ServletResponse or HttpServletResponse object.
8. If the server receives another request for this servlet, the process begins at step 5.
9. When instructed to unload the servlet, perhaps by server administrator or
programmatically by the server itself, the server calls the servlet's destroy() method.
The servlet is then eligible for garbage collection.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
7 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
4. Thread Pooling
 Thread pooling save the virtual machine from the work of creating brand new
threads for every short-lived task.
 In addition, it minimizes overhead associated with getting a thread started and
cleaning it up after it dies.
 By creating a pool of threads, a single thread from the pool can be recycled over
and over for different tasks.
 With the thread pooling technique, you can reduce response time. This is
because a thread is already constructed and started and is simply waiting for its
next task.
 In the case of an HTTP servlet, an available thread in the pool can deliver each
new file requested.
 Without pooling, a brand new thread would have to be constructed and started
before the request can be serviced.
Figure: Servlet Life Cycle
2.4 GENERIC AND HTTP SERVLET
1. Generic Servlet ( Refer 2.2.2)
2. HttpServlet (Refer 2.2.3)
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
8 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
3. Difference between Generic and HttpServlet
GENERICSERVLET HTTPSERVLET
Can be used with any protocol (means,
can handle any protocol). Protocol
independent.
Should be used with HTTP protocol only (can
handle HTTP specific protocols) . Protocol
dependent.
All methods are concrete except service()
method. service() method is abstract
method.
All methods are concrete (non-abstract).
service() is non-abstract method.
service() should be overridden being
abstract in super interface.
service() method need not be overridden.
It is a must to use service() method as it
is a callback method.
Being service() is non-abstract, it can be
replaced by doGet() or doPost() methods.
Extends Object and implements
interfaces Servlet, ServletConfig and
Serializable.
Extends GenericServlet and implements
interface Serializable
Direct subclass of Servet interface. Direct subclass of GenericServlet.
Defined javax.servlet package. Defined javax.servlet.http package.
All the classes and interfaces belonging
to javax.servlet package are protocol
independent.
All the classes and interfaces present in
javax.servlet.http package are protocol
dependent (specific to HTTP).
Not used now-a-days. Used always.
2.5 PASSING PARAMETERS
1. init() method
 Each registered servlet can have specific initialization (init) parameters
associated with it. These are available to the servlet at any time.
 They are often used in the init() method to set initial or default values for a
servlet or to customize the servlet's behavior in some way.
 Settings of initialization parameters are server specific. This init parameters are
specified in web.xml, using <init-param> tags.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
9 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2. getInitParameter()
The getInitParameter() method returns the value of the named init parameter
or null if it does not exist. The GenericServlet class implements the servlet config
interface and thus provides direct access to the getInitParameter() method.
Example:
web.xml
<servlet>
<servlet-name>ParameterDemo</servlet-name>
<servlet-class>edu.skcet.ParameterDemo</servlet-class>
</servlet>
<context-param>
<param-name>email</param-name>
<param-value>admin@email.com</param-value>
</context-param>
ParameterDemo.java
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException
{
PrintWriter out = response.getWriter();
out.println(getServletContext().getInitParameter("email"));
}
3. Reading Request parameter from Servlet
Login.jsp
<html>
<head><title>Login Page</title></head>
<body>
<form name="LoginForm" action="/login" method="post">
<label>Username</label>
<input type="text" name="username" />
<label>Password</label>
<input type="password" name="password" />
<input type="submit" value="Login" />
</form>
</body>
</html>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
10 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet implements Servlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doLogin(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doLogin(request, response);
}
protected void doLogin(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");
PrintWriter out = response.getWriter();
if (username != null && username.equals("administrator")
&& password != null && password.equals("secret"))
{
out.println("Success!");
}
else
{
out.println("Denied!");
}
out.close();
}
}
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
11 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2.6 SERVER SIDE INCLUDE
 SHTML is a file extension that lets the web server know the file should be
processed as using Server Side Includes (SSI).
 Servlets are not confined to handling entire requests. Some web servers allow
servlets to add small amounts of dynamic content to otherwise static HTML
pages.
 This is similar to the server-side include functionality found in most web servers,
but includes additional servlet-specific functionality.
 For example, let's assume that we want to use a server-side include to add a
randomly selected advertisement to a page.
 A page that uses the advertisement servlet is written just like a normal HTML
page, except that it contains one or more <SERVLET> tags and is saved with
the .shtml extension.
 The <SERVLET> tag is similar to the <APPLET> tag, which loads an applet within
a page. When a client requests a .shtml page, the server finds all of
the <SERVLET> tags in the text and replaces them with the output from the
appropriate servlets.
 When you use a <SERVLET> tag, you must include a CODE parameter that
identifies the servlet to be loaded. This can be a class name or a servlet alias set
up within the server. On some servers, you can specify an
optional CODEBASE parameter that loads the servlet code from a remote
location.
 Any additional parameters are treated as servlet initialization parameters.
Each <SERVLET> tag must be matched by a closing</SERVLET> tag.
 Between the opening and closing tags, you can include as many <PARAM> tags as
necessary, where you specify NAME and VALUE attributes for each one.
 The servlet can then access these parameters with getParameter().
Example:
Time.shtml
<HTML>
<HEAD><TITLE>Times!</TITLE></HEAD>
<BODY>
The current time here is:
<SERVLET CODE=CurrentTime>
</SERVLET>
<P>
The current time in London is:
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=GMT>
</SERVLET>
<P>
And the current time in New York is:
<SERVLET CODE=CurrentTime>
<PARAM NAME=zone VALUE=EST>
</SERVLET>
<P>
</BODY>
</HTML>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
12 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
A server-side include that prints the current time
CurrentTime.java
import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class CurrentTime extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter();
Date date = new Date();
DateFormat df = DateFormat.getInstance();
String zone = req.getParameter("zone");
if (zone != null)
{
TimeZone tz = TimeZone.getTimeZone(zone);
df.setTimeZone(tz);
}
out.println(df.format(date));
}
}
2.7 COOKIES
Cookie is a small text file containing client information sent by a web server to a
browser that can later be read back from the browser.
 When a browser receives a cookie, it saves the cookie and there after sends the
cookie back to the server each time it accesses a page on that server, subject to
certain rules.
 Since cookie's value can uniquely identify a client, cookies are often used for
session tracking.
 The browser is expected to support 20 cookies for each Web server, 300 cookies
total and may limit cookie size to 4kb each.
1. Working with Cookies
Cookie can be created using Cookie class which is in the package
javax.servlet.http.cookie
i) To create cookie use Cookie class constructor
public Cookie(String name, String Value0
ii) Once the cookie is created, send the cookie to the browser using the following
method:
HttpServletResponse.addCookie(Cookie cookie)
iii) Cookies can be retrieved by servlet from a request using the following method:
HttpServletRequest.getCookies()
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
13 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2. Cookie Methods
i) public void setComment(java.lang.String purpose)
It specifies a comment that describes a cookie's purpose.
ii) public java.lang.String getComment()
It returns the comment using describing the purpose of this cookie, or null if the
cookie has no comment.
iii) public void setDomain(java.lang.String pattern)
It specifies the domain name set for this cookie.
iv) public void setMaxAge(int expiry)
It sets the maximum age of the cookie in seconds.
A positive value indicates that the cookie will expire after that many seconds have
passed. Note that the value is the maximum age when the cookie will expire, not the
cookie's current age.
A negative value means that the cookie is not stored persistently and will be deleted
when the Web browsers exits.
A zero value causes the cookie to be deleted.
v) public int getMaxAge()
It returns the maximum age of the cookie, specified in seconds.
If getMaxAge returns a negative value, the cookie was not stored persistently. This
method does not return a zero value, because if a cookie's age was set to zero with
setMaxAge, the cookie was deleted.
vi) public void setPath(java.lang.String uri)
It specifies a path for the cookie, which is the set of URIs to which the client
should return the cookie. The cookie is visible to all the pages in the directory you
specify, and all pages in that directory's subdirectories.
A cookie's path must include the servlet that set the cookie, For Example,
servlet/dir1, which makes the cookie visible to all directories on the server under dir1.
vii) public java.lang.String getPath()
It returns the paths (that is, URIs) on the server to which the browser returns
this cookie. The cookie is visible to all subdirectories within the specified path on the
server.
viii) public void setSecure(boolean flag)
It indicates to the browser whether the cookie should only be sent using a secure
protocol, such as HTTPS or SSL. You should only use this method when the cookie's
originating server used a secure protocol to set the cookie's value. The default value is
false.
ix) public boolean getSecure()
It returns true if the browser is sending cookies only over a secure protocol, or
false if the browser can use a standard protocol.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
14 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Example:
cookieExample.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>COOKIES</title>
</head>
<body>
<form action="CookieSer"method="GET">
First Name: <input type="text"name="first_name"> <br/>
Last Name: <input type="text"name="last_name"/>
<input type="submit"value="Submit"/>
</form>
</body>
</html>
CookieSer.java
package cookieExample;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class CookieSer extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Create cookies for first and last names.
Cookie firstName =new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName =new Cookie("last_name", request.getParameter("last_name"));
// Set expiry date after 24 Hrs for both the cookies.
firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);
// Add both the cookies in the response header.
response.addCookie( firstName );
response.addCookie( lastName );
// Set response content type
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String title ="Setting Cookies Example";
String docType ="<!doctype html public "-//w3c//dtd html 4.0 "+
"transitional//en">n";
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
15 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
out.println(docType + "<html>n"+ "<head><title>"+
title +"</title></head>n"+ "<body bgcolor="#f0f0f0">n"+
"<h1 align="center">"+ title +"</h1>n"+
"<ul>n"+
" <li><b>First Name</b>: " + request.getParameter("first_name")+"n"+
" <li><b>Last Name</b>: " + request.getParameter("last_name")+"n"+
"</ul>n"+
"</body></html>");
}
}
2.8 FILTERS
 Filter is a component which dynamically intercepts requests and responses to
transform or use the information contained in the requests or responses.
 Filters typically do not themselves create responses but provide universal
functions that can be "attached" to any type of servlet or JSP page.
 A filter is a program that runs on the server before the servlet with which it is
associated.
Benefits of Filters
 Filters encapsulates common behaviour in a modular and reusable manner.
 It separates high-level access decisions from presentation code.
 It applies wholesale changes to many different resources.
1. Types / Components of Filter
Filters can perform many different types of functions. Based on their
functionalities following are the filters
i) Authentication: Blocking requests based on user identity.
ii) Logging and auditing: Tracking users of a web application.
iii) Image conversion: Scaling maps and so on.
iv) Localization: Targeting the request and response to particular locale.
v) XSL/T Transformations of XML Content: Targeting web application responses to
more than one type of client.
2. Programming a Filter
Filter API is defined by the Filter, FilterChain and FilterConfig interfaces in the
javax.servlet package.
Creating a filter involves five basic steps:
i) Create a class that implements the Filter interface
The class need three methods: doFilter, init, destroy. The doFilter method
contains the main filtering code (see Step 2), the init method performs setup operations,
and the destroy method does cleanup.
ii) Put the filtering behaviour in the doFilter method
The first argument to the doFilter method is a ServletRequest object. This object
gives filter full access to the incoming information, including form data, cookies and
HTTP request headers.
The second argument is a ServletResponse; it is mostly ignored in simple filters.
The final argument is FilterChain; it is used to invoke the servlet or JSP page as
described in the next page.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
16 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
iii) Call the doFilter method of the FilterChain object
The doFilter method of the Filter interface takes a FilterChain object as one of its
arguments. When the doFilter method of that object is called, the next associated filter is
invoked.
If no other filter is associated with the servlet or JSP page, then the servlet or
page itself invoked.
iv) Register the filter with the appropriate servlets and JSP pages
Use the filter and filter-mapping elements in the deployment descriptor
(web.xml).
v) Disable the invoker servlet: Prevent users from bypassing filter setting by using
default servlet URLs.
3. Filter Configuration
Filter is configured in web.xml and is mapped to servlet or JSP. To map a filter to
a servlet:
 Declare the filter using the <filter> element in the web application deployment
descriptor. This element creates a name for the filter and declares the filter's
implementation class and initialization parameters.
 Map the filter to a servlet by defining a <filter-mapping> element in the
deployment descriptor. This element maps a filter name to a servlet by name or
by URL pattern.
4. Filter Elements in web.xml
The filter element is placed near the top of deployment descriptor(web.xml)
before any element. The filter element contains six possible subelements.
 icon: This is a optional element declaring an image file that an IDE can use.
 filter-name: This is a required element that assigns a name of your choosing to
the filter.
 display-name: This is a optional element that provides a short name for use by
IDEs
 description: This is a optional element that gives information for IDEs. It
provides textual documentation.
 filter-class: This is a required element that specifies the fully qualified name of
the filter implementation class.
 init-param: This is an optional element that defines initialization parameters
that can be read with the getInitParameter() method of Filterconfig. A single
filter element can contain multiple init-param elements.
5. Filter-mapping Element
The filter-mapping element goes in the web.xml after the filter element but
before the servlet element. It contains three possible subelements.
 filer-name: This required element must match the name you gave to the filter
when declared it with the filter element.
 url-pattern: This element declares a pattern starting with a slash (/) that
designates the URLs to which the filter applies. url-pattern or servlet-name in all
filter-mapping elements.
 servlet-name: This element gives a name that must match a name given to a
servlet or JSP page by means of the servlet element.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
17 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
6. Process of Registering Filter with Servlet
 One filter can be associated with more than one servlet.
 More than one filter can be mapped to a servlet.
 A filter can be mapped to all the servlet using an "*"
 The filter, filter-mapping, servlet and servlet-mapping elements must appear in
the web application deployment descriptor in that order.
<filter-mapping>
<filter-name> LogFilter </filter-name>
<servlet-name>LoginTest </servlet-name>
</filter-mapping>
<servlet>
<servlet-name>LoginTest</servlet-name>
<servlet-class> edu.skcet.LoginTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> LoginTest</servlet-name>
<url-pattern> /LoginTest </url-pattern>
</servlet-mapping>
7. Filter Life Cycle
Methods controlling life cycle of a filer are as follows
 init()
 doFilter()
 Destroy()
The cycle is similar to that of a servlet.
Three methods of Filter interface makes up the life cycle of a filter
1. public void init(FilterConfig config) throws ServletException
The init method is executed only once, when the filter is first initialized. It is not
executed each time the filter is invoked.
2. public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException
The doFilter method is executed each time a filter is invoked(ie., once for each request
for a servlet or JSP page with which the filter is associated). It is this method that
contains the bulk of the filtering logic.
3. public void destroy()
This method is called when a server is permanently finished with a given filter
object(Example: when the server is being shut down). Most filter simply provide an
empty body for this method, but it can used for cleanup tasks like closing files or
database connection pools that are used by the filter.
Filter interface
A filter configuration object used by a servlet container to pass information to a
filter during initialization.
FilterChain interface
 A FilterChain is an object provided by the servlet container giving a view into the
invocation chain of a filtered request for a resource.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
18 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
 Filters use the FilterChain to invoke the next filter in the chain, or if the calling
filter is the last filter in the chain, to invoke the resource at the end of the chain.
For example, The below figure shows how Filters F1 and F3 intercept invocations
to Servlet S1.
Example:
SiteHitCounter.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class SiteHitCounter implements Filter
{
private int hitCount;
public void init(FilterConfig config) throws ServletException
{
// Reset hit counter
hitCount =0;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain) throws java.io.IOException, ServletException
{
// increase counter by one
hitCount++;
// Print the counter
System.out.println("Site visits count :"+ hitCount );
// Pass request back down the filter chain
chain.doFilter(request, response);
}
public void destroy()
{
// This is optional step but if you like you
// can write hitCount value in your database.
}
}
F3
F2
F1
S1
S2
S3
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
19 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
web.xml
<filter>
<filter-name>SiteHitCounter</filter-name>
<filter-class>SiteHitCounter</filter-class>
</filter>
<filter-mapping>
<filter-name>SiteHitCounter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Output
Site visits count :1
Site visits count :2
Site visits count :3
Site visits count :4
Site visits count :5
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
20 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
JAVA SERVER PAGES (JSP)
What is JSP?
Java Server Pages (JSP) is a simple, yet powerful technology for creating and
maintaining dynamic-content web pages. Based on the Java programming language, JSP
offers proven portability, open standards, and a mature re-usable component model.
JSP allows developing web applications in a more efficient manner than servlets.
JSP separates "presentation logic" from "business logic".
 Presentation is in the form of HTML or XML/XSLT
 Business logic is implemented in Java beans or custom tags
 Thus it provides for better maintainability and reusability
Salient features of JSP
JSP provides following features over Servlets
1. Portability:
JSP files can run on any web server or web-enabled application server that
provides support for them.
2. Composition:
JSP architecture includes reusable Java components such as Java beans and
Servlets.
3. Processing:
JSP contains HTML tags + JSP scripting tags. The JSP page is parsed and
processed (translated) into a Servlet.
JSP versus Servlet
 JSP technology is built over Servlet. Servlets are Java code with embedded HTML
and JSP is HTML with embedded Java Code.
 In fact, all JSP pages when requested, are first converted into Servlet. Thus they
inherit all benefits of Servlets.
 Although dynamic, interactive pages can be created with Servlets alone, using JSP
technology makes the process even easier.
 JSP allows to clearly separate content from presentation. This is unlike Servlets
where business logic and presentation logic co-exist many times in a single
program.
JSP versus/advantages over Competing technologies
1. JSP versus ASP.Net and ColdFusion
 It is a better language for dynamic part.
 It is not portable to multiple servers and operating systems.
2. JSP versus PHP
 It is a better language for dynamic part.
 It is a better tool support.
3. JSP versus JavaScript
 Dynamic information is based on server environment.
 It can access server-side resources whereas JavaScript cannot.
4. JSP versus Static HTML
 JSP can generate dynamic content whereas HTML cannot.
 JSP can access server-side resources whereas HTML cannot.
5. JSP versus Velocity
 It is a standard whereas Velocity is not.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
21 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
6. JSP versus Server-Side Includes (SSI)
 JSP uses Servlet instead of separate program to generate dynamic part.
 JSP allows for richer processing of form data.
ARCHITECTURE / ACCESS METHODS / ACCESS MODELS
1. JSP Model 1 Architecture
 In this model, the client request comes directly to a Java Server Page.
 Suppose the page accesses reusable JavaBean components that performs
particular well-defined computations like accessing a database.
 Then the result of the Bean's computations called result sets are stored within
the Bean as properties.
 The page uses such beans to generate dynamic content and present it back to the
client.
Figure: JSP Model 1 Architecture
2. JSP Model 2 Architecture
 In this model, the request comes through a Servlet. The Servlet generates the
dynamic content. To handle the response to the client, the Servlet creates a Bean
and stores the dynamic content (sometimes called the result set) in the Bean.
The Servlet then invokes a Java Server Page that will present the content
generated by the Bean.
 In this model, the Servlet acts as a controller responsible for processing
requests and creating any beans needed by the JSP page. The controller is also
responsible for deciding to which JSP page to forward the request. The JSP page
retrieves objects created by the Servlet and extracts dynamic content for
insertion within a template. This model promotes the use of the Model View
Controller (MVC) architectural pattern.
 There are two APIs to support this model of request processing using Java Server
Pages.
 One API facilitates passing context between the invoking Servlet and the
Java Server Page.
 The other API lets the invoking Servlet specify which Java Server Page to
use.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
22 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Figure: JSP Model 2 Architecture
JSP PROCESSING MODEL / LIFE CYCLE
 JSP is stored as text file(.jsp) in the web application. When the client requests for
the page for the first time, the server (web container) translates the JSP into Java
source code (.java) and if there are no translation errors then it is compiled into
a Servlet class file.
 The Servlet class is then loaded by the class loader, and then instantiated. For the
first time request, the jspInit() method (if present) is called to initialize
resources.
 If the request for the JSP page is not the first time request, then the translation to
Initialization steps are skipped and the request is directly processed by
_jspService() method.
 The web container invokes the jspDestroy method(if present), to cleanup
resources, when the server shuts down or if the JSP page is replaced with a
modified one.
 The lifecycle methods of the JSP page is translated into the Servlet have the
following form:
 public void jspInit()
 public void jspDestroy()
 public void _jspService(HttpServlet Request request, HttpServletResponse
response) throws ServletException, IOException
Figure: JSP Life Cycle
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
23 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2.9 ENGINES
 The web server needs a JSP engine i.e. container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial
makes use of Apache which has built-in JSP container to support JSP pages
development.
 A JSP container works with the Web server to provide the runtime environment
and other services a JSP needs. It knows how to understand the special elements
that are part of JSPs.
JSP Processing:
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 a servlet content.
This conversion is very simple in which all template text is converted to
println( ) statements and all JSP elements are converted to Java code that
implements the corresponding dynamic behaviour 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:
Figure: JSP Processing
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
24 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
 Typically, the JSP engine checks to see whether a Servlet for a JSP file already
exists and whether the modification date on the JSP is older than the Servlet.
 If the JSP is older than its generated Servlet, the JSP container assumes that the
JSP hasn't changed and that the generated Servlet still matches the JSP's
contents.
 This makes the process more efficient than with other scripting languages (such
as PHP) and therefore faster.
 So in a way, a JSP page is really just another way to write a Servlet without
having to be a Java programming wiz. Except for the translation phase, a JSP page
is handled exactly like a regular Servlet.
2.10 SYNTAX
JSP pages use several delimiters for scripting functions. The most basic is
<% ... %>, which encloses a JSP scriptlet. A scriptlet is a fragment of Java code that is
run when the user requests the page.
1. JSP Scriptlet
 A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting language.
 A JSP scriptlet is used to insert Java code into the _jspService method.
 Scriptlets are executed when the JSP engine processes the client request. If the
scriplet produces output, then the output is stored in the out object, from which
can display it.
 Note that code inside a scriptlet gets inserted exactly as written. Any static
HTML (template text) before or after a scriptlet gets converted to print
statements.
Syntax
<% Java Code %>
Example
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>
Output
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
25 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2. JSP Declarations
A JSP declaration is used to define methods or fields that are inserted in the
Servlet class outside the _jspService() method.
Syntax
<%! Java Code %>
Example: Count accesses to page since server reboot
<%! private int accessCount=0; %>
<%=++accessCount %>
Declaration can be used to override jspInit() and jspDestroy() methods of Servlet.
3. JSP Expressions
 A JSP expression is used to insert Java values directly into the output.
 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.
Syntax
<%=Java Expression %>
Example
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>
Output
Today's date: 17-Jan-2016 21:24:25
4. JSP Comments
JSP comment marks text or statements that the JSP container should ignore. A
JSP comment is useful when you want to hide or "comment out" part of your JSP page.
Syntax
<%-- This is JSP comment --%>
Example
<h2>A Test of Comments</h2>
<%-- This comment will not be visible in the page source --%>
5. JSP Directives
 Directives are messages to the JSP container.
 Instruction for the JSP engine that are processed when the JSP page is translated
into Servlet.
 A JSP Directive affects the overall structure of the Servlet class.
 It has the form <%@directive {attribute="value"}* %>
There are three types of directives
page: It lets you do things like import classes, customize the Servlet super class.
include: It lets you insert a file into the Servlet class at that time the JSP file is translated
into a Servlet.
taglib: It is intended to let JSP authors define their own tags.
i) Page Directive
 The JSP page directive defines a number of page independent properties and
communicates these to the JSP container.
 JSP page directive applies to the entire JSP file and any of its static include files
called as translation unit.
 It can be used more than once in a translation unit.
 All attributes except "import" can be used only once per translation unit.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
26 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Syntax
<%@page
{language="scriptingLanguage"}
{extends="className"}
{import="importList"}
{session="true|false"}
{buffer="none|sizekb"}
{autoflush="true|false"}
{isThreadSafe="true|false"}
{info="info_text"}
{errorPage="error_url"}
{isErrorPage="true|false"}
{contentType="ctinfo"}
{pageEncoding="peinfo"}
{isELIgnored="true|false"}
{deferredSyntaxAllowedAsLiteral="true|false"}
{trimDirectiveWhitespaces="true|false"}
%>
Example
<%@ page import="java.util.*"%>
ii) Include Directive
 The include directive includes files at the time the JSP page is translated into a
Servlet.
 The included file can be an HTML file, a JSP file, a text file or a java code file.
 The include process is static.
 Change in the included file will not be reflected in the JSP file in which it is
included.
Syntax
<%@include%>
Example
<html>
<head><title> Include Directive </title></head>
<body>
<%@include file="header.html"%>
Page Body
<!-- Part specific to this page -->
<%@include file="footer.html"%>
</body>
</html>
iii) Taglib Directive
 It is intended to let JSP authors define their own tags.
 It provides a set of reusable standard tags.
Syntax
<%@taglib %>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
27 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Example
<%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %>
<html>
<body>
<c:forEach var="i" begin="1" end="10" step="1">
<c:out value="${i}"/> <br/>
</c:forEach>
</body>
</html>
2.11 COMPONENTS
Refer 2.10 Syntax
2.12 SCRIPTLETS
Refer 2.10 (1. JSP Scriptlets)
2.13 JSP OBJECTS
Implicit objects provide programmers with access to many Servlet capabilities in
the context of a Java Server Page. Implicit objects have four scopes: application, page,
request and session.
1. Application Scope
The JSP and Servlet container application owns objects with application scope.
Any Servlet or JSP can manipulate such objects.
i) application
This javax.servlet.ServletContext object represents the container in which the
JSP executes.
2. Page Scope
Objects with page scope exist only in the page that defines them. Each page has
its own instances of the page-scope implicit objects.
i) config
This javax.servlet.ServletConfig object represents the JSP configuration
options. As with servlets, configuration options can be specified in a Web application
descriptor.
ii) exception
This java.lang.Throwable object represents the exception that is passed to the
JSP error page. This object is available only in a JSP error page.
iii) out
This javax.servlet.jsp.JspWriter object writes text as part of the response to a
request. This object is used implicitly with JSP expressions and actions that insert string
content in a response.
iv) page
This java.lang.Object object represents the this reference for the current JSP
instance.
v) pageContext
This javax.servlet.jsp.PageContext object hides the implementation details of
the underlying Servlet and JSP container and provides JSP programmers with access to
the implicit objects discussed in this table.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
28 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
vi) response
This object represents the response to the client. The object normally is an
instance of a class that implements HttpServletResponse(package javax.servlet.http).
If a protocol other than HTTP is used, this object is an instance of a class that
implements javax.servlet.ServletResponse.
3. Request Scope
Objects with request scope exist for the duration of the request. For example, a
JSP can partially process a request, then forward the request to another Servlet or JSP
for further processing. Request-scope objects go out of scope when request processing
completes with a response to the client.
i) request
This object represents the client request. The object normally is an instance of a
class that implements HttpServletRequest (package javax.servlet.http). If a protocol
other than HTTP is used, this object is an instance of a subclass of
javax.servlet.ServletRequest.
4. Session Scope
Objects with session scope exist for the client’s entire browsing session.
i) session
This javax.servlet.http.HttpSession object represents the client session
information if such a session has been created. This object is available only in pages that
participate in a session.
2.14 JSP ACTIONS
JSP actions use constructs in XML syntax to control the behaviour of the Servlet
engine. With JSP actions, you can do either of the following:
 Dynamically insert a file.
 Reuse JavaBeans components.
 Forward the user to another page.
 Generate HTML for the Java plugin.
Available actions include:
jsp:include: It includes a file at the time the page is requested.
jsp:forward: It forwards a client request to an HTML file, JSP file or Servlet for
processing.
jsp:plugin: It generates browser-specific code that makes an OBJECT or EMBED tag for
the Java plugin.
jsp:useBean: It finds or instantiates a JavaBean.
jsp:setProperty: It sets the property of a JavaBean
jsp:getProperty: It inserts the property of a JavaBean into the output.
1. The jsp:include Action
The <jsp:include> element allows to include either a static or dynamic file in a JSP file.
The results of including static and dynamic files are quite different.
 If the file is static, its content is included in the calling JSP file.
 If the file is dynamic, it acts on a request and sends back a result that is included
in the JSP page.
The <jsp:include> action lets insert files into the page being generated.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
29 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Syntax:
<jsp:include page="{relative URL | <%=expression%>}" flush="true"/>
If the included file is dynamic, <jsp:param> clause to pass the name and value of a
parameter to the dynamic file. As an example, you can pass the string username and a
user's name to a login form that is coded in a JSP file.
Syntax:
<jsp:include page="{relative URL | <%=expression%>}" flush="true"/>
<jsp:param name="parameterName" value="{parameterValue |<%=expression%>}"/>+
</jsp:include>
Example:
Banner (banner.html) to include across the top of the XHTML document
<!-- banner to include in another document -->
<div style = "width: 580px">
<p>
Java(TM), C, C++, Visual Basic(R),
Object Technology, and <br /> Internet and
World Wide Web Programming Training&nbsp;<br />
On-Site Seminars Delivered Worldwide
</p>
<p>
<a href = "mailto:deitel@deitel.com">deitel@deitel.com</a><br />
978.579.9911<br />
490B Boston Post Road, Suite 200,
Sudbury, MA 01776
</p>
</div>
Table of contents (toc.html) to include down the left side of the XHTML
<!-- contents to include in another document -->
<p><a href ="http://www.deitel.com/books/index.html"> Publications/BookStore </a></p>
<p><a href ="http://www.deitel.com/whatsnew.html"> What's New </a></p>
<p><a href ="http://www.deitel.com/books/download.html">Downloads/Resources</a></p>
<p><a href ="http://www.deitel.com/faq/index.html"> FAQ (Frequently Asked Questions)
</a></p>
<p><a href = "http://www.deitel.com/intro.html"> Who we are </a></p>
<p><a href = "http://www.deitel.com/index.html"> Home Pagec </a></p>
<p>Send questions or comments about this site to <a href = "mailto:deitel@deitel.com">
deitel@deitel.com </a><br />
Copyright 1995-2002 by Deitel &amp; Associates, Inc.
All Rights Reserved.
</p>
JSP clock2.jsp to include as the main content in the XHTML document
<!-- date and time to include in another document -->
<table><tr> <td style = "background-color: black;">
<p class = "big" style = "color: cyan; font-size: 3em; font-weight: bold;">
<%= new java.util.Date() %>
</p>
</td></tr>
</table>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
30 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
JSPinclude.jsp Includes resources with <jsp:include>
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<title>Using jsp:include</title>
<style type = "text/css">
body {
font-family: tahoma, helvetica, arial, sans-serif;
}
table, tr, td {
font-size: .9em;
border: 3px groove;
padding: 5px;
background-color: #dddddd;
}
</style>
</head>
<body>
<table>
<tr>
<td style = "width: 160px; text-align: center">
<img src = "images/logotiny.png"
width = "140" height = "93"
alt = "Deitel & Associates, Inc. Logo" />
</td>
<td>
<%-- include banner.html in this JSP --%>
<jsp:include page = "banner.html" flush = "true" />
</td>
</tr>
<tr>
<td style = "width: 160px">
<%-- include toc.html in this JSP --%>
<jsp:include page = "toc.html" flush = "true" />
</td>
<td style = "vertical-align: top">
<%-- include clock2.jsp in this JSP --%>
<jsp:include page = "clock2.jsp" flush = "true" />
</td>
</tr>
</table>
</body>
</html>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
31 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Output:
2. The jsp:forward Action
 The <jsp:forward> element forwards the request object containing the client
request information from one JSP file to another file.
 The target file can be an HTML file, another JSP file or a Servlet.
 A jsp:forward effectively terminates the execution of the current page.
 If the page output is buffered, then the buffer is cleared prior to forwarding.
Syntax:
<jsp:forward page="{relativeURL | <%=expression %>}"
{/> | > [jsp:param name="parameterName"
value="{ parameterValue | <%=expression %>}" />]+
</jsp:forward>
Example:
JSP forward1.jsp receives a firstName parameter, adds a date to the request
parameters and forwards the request to forward2.jsp for further processing
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head> <title>Forward request to another JSP</title></head>
<body>
<% // begin scriptlet
String name = request.getParameter( "firstName" );
if ( name != null ) {
%> // end scriptlet
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
32 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
<jsp:forward page = "forward2.jsp">
<jsp:param name = "date" value = "<%= new java.util.Date() %>" />
</jsp:forward>
<% // continue scriptlet
} // end if
else {
%> <%-- end scriptlet to insert fixed template data --%>
<form action = "forward1.jsp" method = "get">
<p>Type your first name and press Submit</p>
<p><input type = "text" name = "firstName" />
<input type = "submit" value = "Submit" />
</p>
</form>
<% // continue scriptlet
} // end else
%> <%-- end scriptlet --%>
</body>
</html>
JSP forward2.jsp receives a request (from forward1.jsp in this example) and uses
the request parameters as part of the response to the client
<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- forward2.jsp -->
<html xmlns = "http://www.w3.org/1999/xhtml"v
<head><title>Processing a forwarded request</title>
<style type = "text/css">
.big {
font-family: tahoma, helvetica, arial, sans-serif;
font-weight: bold;
font-size: 2em;
}
</style>
</head>
<body>
<p class = "big">
Hello <%= request.getParameter( "firstName" ) %>, <br />
Your request was received <br /> and forwarded at</p>
<table style = "border: 6px outset;">
<tr>
<td style = "background-color: black;">
<p class = "big" style = "color: cyan;">
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
33 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
<%= request.getParameter( "date" ) %>
</p>
</td>
</tr>
</table>
</body>
</html>
jsp:forward versus response.sendRedirect
jsp:forward response.sendRedirect
Server-side redirect, hence no network
traffic
Client-side redirect, hence additional
network round trip
The address of the destination page
hidden from user.
The address of the destination page
visible to user in the address bar.
Allows forwarding of the request to
another page in the same context as the
current page.
Allows re-direction of the request to
another page in same or different
context as the current page.
3. The jsp:plugin Action
 The plugin action enables a JSP author to generate HTML that contains the
appropriate client browser dependent constructs (OBJECT or EMBED).
 The plugin action will result in the download of the Java plugin (if required).
 It will execute the Applet or JavaBeans component specified in jsp:plugin action.
Syntax:
<jsp:plugin type="bean | applet"
code= "classFileName"
codebase="classFileDirectoryName"
[name="instanceName"]
[arhive="URIToArchive, ..."]
[height="displayPixels"]
[width="diplayPixels"]
[align="bottom | top | middle | left | right"]
[hspace="leftRightPixels"]
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
34 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
[vspace="topBottomPixels"]
[jreversion="JREVersionNumber | 1.1"]
[nspluginurl="URLToplugin"]
[iepluginurl=" URLToplugin "]
[<jsp:params> [<jsp:param name="parameterName" value="parameterValue" />+
</jsp:params>]
[<jsp:fallback> text message for user </jsp:fallback>]
</jsp:plugin>
Example:
HelloApplet.java
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello",15,12);
}
public void update(Graphics g)
{
paint(g);
}
}
plugin.jsp
<html>
<head><title>Using jsp:plugin to load an applet</title></head>
<body>
<jsp:plugin type="applet"code="HelloApplet.class" jreversion="1.2" width="150"height="100">
<jsp:fallback>
Plugin tag OBJECT or EMBED not supported by browser
</jsp:fallback>
</jsp:plugin>
</body>
</head>
</html>
4.The <jsp:useBean> Action
 A <jsp:useBean> action associates an instance of a Java object defined within a
given scope available with a given id via newly declared scripting variable of the
same id.
 The action tries to find an existing object using id and scope. If it is not found,
then it will attempt to create the object using the other attributes.
Syntax
<jsp:useBean id="beanInstanceName" scope="page|request|session|application"
beanName="{package.class | <%=expression%>}" type="package.class"
</jsp:useBean>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
35 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
5. The <jsp:setProperty> Action
 The jsp:setProperty action sets the value of properties in a bean. The name
attribute denotes an object that must be defined before this action appears.
 Property in a Bean can be set from either of the following:
 one or more parameters in the request object
 a String constant
 a computed request-time expression
Syntax
<jsp:setProperty name="beanInstanceName" property="*" |
property="propertyName" [ param="parameterName"] | property="propertyName"
value="{string| <%=expression%>}" />
Type Conversion for setProperty Action
Property Type Conversion from String
boolean or Boolean java.lang.Boolean.valueOf(String)
byte or Byte java.lang.Byte.valueOf(String)
char or Character java.lang.Character.valueOf(String)
double or Double java.lang.Double.valueOf(String)
int or Integer java.lang.Integer.valueOf(String)
float or Float java.lang.Float.valueOf(String)
Long or Long java.lang.Long.valueOf(String)
6. The <jsp:getProperty> Action
 The jsp:getProperty element retrieves the value of a bean property, converts it to
a string, and inserts it into the output.
 The two required attributes are:
 name: the name of a bean previously referenced via jsp:useBean
 property: the property whose value should be inserted.
Syntax
<jsp:getProperty name="beanInstanceName" property="propertyName"/>
Type Conversion for getProperty Action
Property Type Conversion from String
boolean java.lang.Boolean.toString (boolean)
byte java.lang.Byte. toString (byte)
char java.lang.Character. toString (char)
double java.lang.Double. toString (double)
int java.lang.Integer. toString (int)
float java.lang.Float. toString (float)
long java.lang.Long. toString (long)
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
36 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2.15 TAG EXTENSIONS / CUSTOM TAGS
 A custom tag is a user-defined JSP element.
 Custom tags have a rich set of features. They can
 Be customized via attributes passed from the calling page
 Pass variables back to the calling page
 Access all the objects available to JSP pages
 Be nested within one another
 Custom tags are required to
 Replace the Java code with tags in JSP page.
 Help page authors to easily develop JSP page
1. Types of Tags
i) Tags with Attributes
<example:hello name="Hi"></example:hello>
ii) Tags with Bodies
<example:reverse> This is body content </example:reverse>
iii) Tags with variables
<example:hello name="Sham">Hello<%=name%> </example:hello>
2. Process / Steps of Creating Custom Tags
i) Creation of Tag Handler Class
Tag handler is a java class which handles the tag processing for a particular tag.
To create the custom tag, first we need to create the tag handler for that tag.
ii) Creation of Tag Library Descriptor
Tag Library Descriptor is a file which includes the entries for mapping the tag
and its tag handler. This file is saved with TLD extension.
iii) Modification of web.xml to use tag library
In order to use tags from a specific tag library descriptor in web application, an
entry for TLD should be added in web.xml
iv) Importing TLD
 Once TLD entry is made in web.xml, all jsp files from that web application will
be able to use different tags from that TLD file.
 To use tags from the specific TLD, we need to import TLD file in jsp by using
taglib directive.
v) Use of Custom Tags in JSP
 After TLD tags are made available for the particular JSP page, one can use
different tags from that TLD file in JSP page code at various places.
 Thus these custom tags contribute in processing certain functionality required
by that JSP page.
Properties / Constants of Tag interface
EVAL_BODY_INCLUDE: It evaluates body into existing out stream.
EVAL_PAGE: It continues evaluating the page.
SKIP_BODY: It skips body evaluation.
SKIP_PAGE: It skips the rest of the page.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
37 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Step 1:Creation of Tag Handler Class
HelloTag.java
public class HelloTag extends TagSupport
{
public int doStartTag() throws JspTagException
{
return EVAL_BODY_INCLUDE;
}
public int doEndTag() throws JspTagException
{
pageContext.getOut().write("Helloworld <br/>");
return EVAL_PAGE;
}
}
Step 2: Creation of the Tag Library Descriptor
Demo.tld
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>2.1</jspversion>
<shortname>examples</shortname>
<tag>
<name>hello</name>
<tagclass>lab.wt.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<info>Simple Example</info>
</tag>
</taglib>
Step 3 & 4: Entry in web.xml & JSP Page
Web.xml
<jsp-config>
<taglib>
<taglib-uri>demo.tld</taglib-uri>
<taglib-location>/WEN-INF/demo.tld</taglib-location>
</taglib>
</jsp-config>
Hello.jsp
<%@taglib uri="demo.tld" prefix="examples"%>
<html>
<head><title>First Custom Tag</title></head>
<body>
This is static output<p/>
<i><examples:hello></examples:hello></i>
This is static output again
</body>
</html>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
38 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2.16 SESSION TRACKING
The Session Object
 JSP makes use of Servlet provided 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.
 By default, JSPs have session tracking enabled and a new HttpSession object is
instantiated for each new client automatically. Disabling session tracking
requires explicitly turning it off by setting the page directive session attribute to
false as follows:
<%@ page session="false" %>
Methods and Description
1. public Object getAttributeStringname
This method returns the object bound with the specified name in this session, or
null if no object is bound under the name.
2. public Enumeration getAttributeNames
This method returns an Enumeration of String objects containing the names of
all the objects bound to this session.
3. public long getCreationTime
This method returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
4. public String getId
This method returns a string containing the unique identifier assigned to this
session.
5. public long getLastAccessedTime
This method returns the last time the client sent a request associated with this
session, as the number of milliseconds since midnight January 1, 1970 GMT.
6. public int getMaxInactiveInterval
This method returns the maximum time interval, in seconds, that the servlet
container will keep this session open between client accesses.
7. public void invalidate
This method invalidates this session and unbinds any objects bound to it.
8. public boolean isNew
This method returns true if the client does not yet know about the session or if
the client chooses not to join the session.
9. public void removeAttribute Stringname
This method removes the object bound with the specified name from this
session.
10. public void setAttributeStringname, Objectvalue
This method binds an object to this session, using the name specified.
11. public void setMaxInactiveInterval intinterval
This method specifies the time, in seconds, between client requests before the
Servlet container will invalidate this session.
Example:
<%@ page import="java.io.* ,java.util.* " %>
<%
// Get session creation tim e.
Date createTime = new Date(session.getCreationTime());
// Get last access tim e of this web page.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
39 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new com er on your web page.
if (session.isNew())
{
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
}
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<htm l>
<head><title>Session Tracking</title></head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border="1" align="center">
<tr bgcolor="#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Tim e</td>
<td><% out.print(createTim e); %></td>
</tr>
<tr>
<td>Tim e of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Num ber of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
40 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2.17 DATABASE CONNECTIVITY
 Java Database Connectivity (JDBC) is a standard SQL database access interface,
providing uniform access to a wide range of relational databases.
 JDBC allows us to construct SQL statements and embed them inside Java API
calls.
JDBC Features:
 JDBC supports all the advanced features of latest SQL version.
 JDBC API provides a rich set of methods.
 It provides a clean, simple, uniform vendor independent interface.
Example:
<%@ page language="java" import="java.sql.*" %>
<HTML>
<HEAD> <TITLE> The JDBCQuery JSP </TITLE> </HEAD>
<BODY BGCOLOR="white">
<% String searchCondition = request.getParameter("cond");
if (searchCondition != null) { %>
<H3> Search results for <I> <%= searchCondition %> </I> </H3>
<B> <%= runQuery(searchCondition) %> </B> <HR><BR>
<% } %>
<B>Enter a search condition:</B>
<FORM METHOD="get">
<INPUT TYPE="text" NAME="cond" SIZE=30>
<INPUT TYPE="submit" VALUE="Ask Oracle");
</FORM>
</BODY>
</HTML>
<%-- Declare and define the runQuery() method. --%>
<%! private String runQuery(String cond) throws SQLException
{
Connection conn = null;
Statement stmt = null;
ResultSet rset = null;
try
{
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
conn = DriverManager.getConnection("jdbc:oracle:oci8:@",
"scott", "tiger");
stmt = conn.createStatement();
// dynamic query
rset = stmt.executeQuery ("SELECT ename, sal FROM scott.emp "+
(cond.equals("") ? "" : "WHERE " + cond ));
return (formatResult(rset));
}
catch (SQLException e)
{
return ("<P> SQL error: <PRE> " + e + " </PRE> </P>n");
}
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
41 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
finally
{
if (rset!= null) rset.close();
if (stmt!= null) stmt.close();
if (conn!= null) conn.close();
}
}
private String formatResult(ResultSet rset) throws SQLException
{
StringBuffer sb = new StringBuffer();
if (!rset.next())
sb.append("<P> No matching rows.<P>n");
else { sb.append("<UL>");
do { sb.append("<LI>" + rset.getString(1) +
" earns $ " + rset.getInt(2) + ".</LI>n");
} while (rset.next());
sb.append("</UL>");
}
return sb.toString();
}
%>
OUTPUT:
2.18 SQL STATEMENTS
SQL stands for Structured Query Language. Pronounced as SEQUEL, SQL was
originally developed by IBM based on Dr.E.F. Codd's relational model to define,
manipulate and control data in a database.
Almost all modern Relational Database Management Systems like MS SQL Server,
Microsoft Access, MSDE, Oracle, DB2, Sybase, MySQL, Postgres and Informix use SQL as
standard database language.
1. Rules for SQL statements
 SQL keywords are not case sensitive. However, normally all commands
(SELECT,INSERT, etc) are upper-cased.
 Variable and parameter names are displayed as lower-case.
 New-line characters are ignored in SQL.
 Many DBMS systems terminate SQL statements with a semi-colon character.
 Character strings and date values are enclosed in single quotation marks while
using them in WHERE clause or otherwise.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
42 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
2. Standard SQL statement groups
GROUPS STATEMENTS DESCRIPTION
DQL SELECT
Data Query Language - It is used to get data from the
database.
DML
DELETE
INSERT
UPDATE
MERGE
Data Manipulation Language - It is used to change
database data.
DDL
DROP
TRUNCATE
CREATE
ALTER
Data Definition Language - It is used to manipulate
database structures and definitions
TCL
COMMIT
ROLLBACK
SAVEPOINT
TCL statements are used to manage the transactions.
DCL
REVOKE They are used to remove and provide access rights to
database objects.
i) The SELECT Statement
public List<Employee> getAllDetails() throws EmployeeException
{
Connection con=null;
Statement st=null;
ResultSet rs=null;
List<Employee> l=new ArrayList<Employee>();
try
{
con=new DBConnection().getConnection();
st=con.createStatement();
rs=st.executeQuery("select * from employee_801774");
while(rs.next())
{
Employee e=new Employee();
e.setEcode(rs.getInt(1));
e.setEname(rs.getString(2));
e.setDesignation(rs.getString(3));
e.setAge(rs.getInt(4));
e.setBasic_Pay(rs.getDouble(5));
e.setDept_num(rs.getInt(6));
l.add(e);
}
}
catch (SQLException e1)
{
throw new EmployeeException(e1.getMessage());
}
return l;
}
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
43 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
ii) The INSERT statement
public boolean insertEmployee(Employee e) throws EmployeeException
{
Connection con=null;
PreparedStatement ps=null;
boolean result=false;
try
{
con=new DBConnection().getConnection();
System.out.println(con);
ps=con.prepareStatement("insert into employee_801774 values(?,?,?,?,?)");
ps.setString(1,e.getEname());
ps.setString(2,e.getDesignation());
ps.setInt(3,e.getAge());
ps.setDouble(4,e.getBasic_Pay());
ps.setInt(5,e.getDept_num());
int r=ps.executeUpdate();
if(r>=1)
{
result=true;
}
else
{
result=false;
}
}
catch (SQLException e1)
{
throw new EmployeeException(e1.getMessage());
}
return result;
}
iii) The DELETE STATEMENT
public boolean deleteEmployee(int ecode) throws EmployeeException
{
Connection con=null;
PreparedStatement ps=null;
boolean result=false;
try
{
con=new DBConnection().getConnection();
System.out.println(con);
if(con!=null)
{
ps=con.prepareStatement("delete from employee_801774 where Ecode=?");
ps.setInt(1,ecode);
int r=ps.executeUpdate();
if(r>=1)
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
44 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
{
result=true;
}
else
{
result=false;
}
}
}
catch (SQLException e1)
{
throw new EmployeeException(e1.getMessage());
}
return result;
}
iv) The UPDATE Statement
public boolean updateEmployee(String a,int b) throws EmployeeException
{
Connection con=null;
PreparedStatement ps=null;
boolean result=false;
try
{
con=new DBConnection().getConnection();
System.out.println(con);
if(con!=null)
{
ps=con.prepareStatement("update employee_801774 set Ename=? where
Ecode=?");
ps.setString(1,a);
ps.setInt(2,b);
int r=ps.executeUpdate();
if(r>=1)
{
result=true;
}
else
{
result=false;
}
}
}
catch (SQLException e1)
{
throw new EmployeeException(e1.getMessage());
}
return result;
}
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
45 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
JAVA 2 ENTERPRISE EDITION
2.19 J2EE INTRODUCTION
J2EE ARCHITECTURE
 The J2EE platform uses a distributed multitiered application model for
enterprise applications.
 Application logic is divided into components according to function, and the
various application components that make up a J2EE application are installed on
different machines depending on the tier in the multitiered J2EE environment to
which the application component belongs.
 Figure shows two multitiered J2EE applications divided into the tiers described
in the following list. The J2EE application parts shown in Figure are presented in
J2EE Components.
 Client-tier components run on the client machine.
 Web-tier components run on the J2EE server.
 Business-tier components run on the J2EE server.
 Enterprise information system (EIS)-tier software runs on the EIS server.
 Although a J2EE application can consist of the three or four tiers shown in Figure,
J2EE multitiered applications are generally considered to be three tiered
applications because they are distributed over three locations: client machines,
the J2EE server machine, and the database or legacy machines at the back end.
 Three-tiered applications that run in this way extend the standard two tiered
client and server model by placing a multithreaded application server between
the client application and back-end storage.
Figure: Multitiered Applications
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
46 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
J2EE COMPONENTS & CONTAINERS
1. J2EE COMPONENTS
J2EE applications are made up of components. A J2EE component is a self-
contained functional software unit that is assembled into a J2EE application with its
related classes and files and that communicates with other components. The J2EE
specification defines the following J2EE components:
 Application clients and applets are components that run on the client.
 Java Servlet and Java Server Pages (JSP) technology components are Web
components that run on the server.
 Enterprise JavaBeans (EJB) components (enterprise beans) are business
components that run on the server.
i) Application Clients
 An application client runs on a client machine and provides a way for users to
handle tasks that require a richer user interface than can be provided by a
markup language.
 It typically has a graphical user interface (GUI) created from the Swing or the
Abstract Window Toolkit (AWT) API, but a command-line interface is certainly
possible. Application clients directly access enterprise beans running in the
business tier.
 However, if application requirements warrant it, an application client can open
an HTTP connection to establish communication with a servlet running in the
Web tier.
ii) Web Components
 J2EE Web components are either servlets or pages created using JSP technology
(JSP pages). Servlets are Java programming language classes that dynamically
process requests and construct responses.
 JSP pages are text-based documents that execute as servlets but allow a more
natural approach to creating static content.
 Static HTML pages and applets are bundled with Web components during
application assembly but are not considered Web components by the J2EE
specification.
 Server-side utility classes can also be bundled with Web components and, like
HTML pages, are not considered Web components.
 As shown in Figure, the Web tier, like the client tier, might include a Java- Beans
component to manage the user input and send that input to enterprise beans
running in the business tier for processing.
Figure: Web Tier and J2EE Applications
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
47 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
iii) Business Components
 Business code, which is logic that solves or meets the needs of a particular
business domain such as banking, retail, or finance, is handled by enterprise
beans running in the business tier.
 Figure shows how an enterprise bean receives data from client programs,
processes it (if necessary), and sends it to the enterprise information system tier
for storage.
 An enterprise bean also retrieves data from storage, processes it (if necessary),
and sends it back to the client program.
 There are three kinds of enterprise beans: session beans, entity beans, and
message-driven beans.
 A session bean represents a transient conversation with a client. When the client
finishes executing, the session bean and its data are gone.
 In contrast, an entity bean represents persistent data stored in one row of a
database table. If the client terminates or if the server shuts down, the
underlying services ensure that the entity bean data is saved.
 A message-driven bean combines features of a session bean and a Java Message
Service (JMS) message listener, allowing a business component to receive JMS
messages asynchronously.
Figure: Business and EIS Tiers
2. J2EE CONTAINERS
i) Container Services
ii) Container Types
i) Container Services
 Containers are the interface between a component and the low-level platform
specific functionality that supports the component.
 Before a Web, enterprise bean, or application client component can be executed,
it must be assembled into a J2EE module and deployed into its container.
 The assembly process involves specifying container settings for each component
in the J2EE application and for the J2EE application itself.
 Container settings customize the underlying support provided by the J2EE
server, including services such as security, transaction management, Java
Naming and Directory Interface (JNDI) lookups, and remote connectivity.
 Here are some of the highlights:
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
48 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
 The J2EE security model lets you configure a Web component or enterprise
bean so that system resources are accessed only by authorized users.
 The J2EE transaction model lets you specify relationships among methods that
make up a single transaction so that all methods in one transaction are treated
as a single unit.
 JNDI lookup services provide a unified interface to multiple naming and
directory services in the enterprise so that application components can access
naming and directory services.
 The J2EE remote connectivity model manages low-level communications
between clients and enterprise beans. After an enterprise bean is created, a
client invokes methods on it as if it were in the same virtual machine.
 Because the J2EE architecture provides configurable services, application
components within the same J2EE application can behave differently based on
where they are deployed.
 For example, an enterprise bean can have security settings that allow it a certain
level of access to database data in one production environment and another level
of database access in another production environment.
 The container also manages nonconfigurable services such as enterprise bean
and servlet life cycles, database connection resource pooling, data persistence,
and access to the J2EE platform APIs.
 Although data persistence is a nonconfigurable service, the J2EE architecture lets
you override container-managed persistence by including the appropriate code
in your enterprise bean implementation when you want more control than the
default container-managed persistence provides.
 For example, you might use bean-managed persistence to implement your own
finder (search) methods or to create a customized database cache.
ii) Container Types
The deployment process installs J2EE application components in the J2EE
containers illustrated in Figure.
Figure: J2EE Server and Containers
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
49 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
J2EE server
The runtime portion of a J2EE product. A J2EE server provides EJB and Web containers.
Enterprise JavaBeans (EJB) container
Manages the execution of enterprise beans for J2EE applications. Enterprise beans and
their container run on the J2EE server.
Web container
Manages the execution of JSP page and servlet components for J2EE applications. Web
components and their container run on the J2EE server.
Application client container
Manages the execution of application client components. Application clients and their
container run on the client.
Applet container
Manages the execution of applets. Consists of a Web browser and Java Plugin running on
the client together.
2.20 ENTERPRISE JAVABEANS (EJB)
1. Enterprise JavaBeans
 They are components that can be connected to form a system.
 They can represent data. They can represent behaviour.
 Usually, EJBs fall into only one of these categories.
 They are typically used in the server tier. EJBs can be persisted. EJBs can interact
with other EJBs.
Advantages of EJBs:
 EJBs are reusable components. Can be reused in different parts of the system.
Can be packaged into libraries and sold.
 EJBs Can be combined visually using development IDEs.
 E.g. Visual Age, Visual Cafe
 EJBs provide convenient abstractions so it do not require you to write
 Multi-threaded, multiple access code
 Database access code (e.g. JDBC)
 Network communication code (i.e. it uses RMI) for client/server
communication
 Network communication code for EJB to EJB communication
 Transaction management code
 EJBs from different businesses can interact easily. This is because of their well-
defined interfaces
i) EJB Communication
EJBs use IIOP as the wire protocol. Therefore, EJBs are compatible with RMI (i.e.,
RMI over IIOP) and CORBA libraries. Thus, you could write an EJB client in any language
that supports CORBA.
ii) EJB as Client/Server Middleware
Think of EJBs as just another Client/Server middleware like RMI, CORBA, or Web
Services. The EJB instance itself is the server. EJBs have clients (objects that call its
methods). One complication is that EJB clients can be:
 Java Applets and Applications (using RMI or CORBA)
 Non-Java applications (using CORBA)
 JSPs and Servlets (using RMI or CORBA)
 Other EJBs (using RMI or CORBA)
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
50 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
iii) EJBs & 3-Tiered Architectures
In enterprise systems, EJB clients are usually: Servlets, JSPs, or Other EJBs.
Figure: 3-Tiered Architecture
iv) EJBs & Multi-Tiered Architectures
Figure: Multi-Tiered Architecture
How EJBs Change Things?
EJBs are most suitable for developing business logic and data manipulation. If all
of the business logic operations and data manipulations are done using EJBs, the JSPs
and Servlets will be focused mainly on displaying the results of those operations.
Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2
51 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |
Session EJBs: Used to represent system behavior (i.e. business logic). e.g. Storing
products to purchase in the shopping cart
Entity EJBs: Used to represent & manipulate system data. e.g. Finding products that
match a search term
EJB Types
2. Types of Enterprise Beans
i) Session beans
Also called business process objects. They represent the business logic of the
system. Their lifetime is usually an entire session. When a session is done, the session
bean expires. i.e. Session bean instances exist as long as a specific user is using the
system.
Subtypes of Session Beans:
Stateful:
Used for operations that require multiple requests to be completed. Maintain
data between requests.
Stateless:
Used for operations that can be performed in a single request. Do not maintain
persistent data between subsequent requests from a given client.
ii) Entity beans:
Also called business data objects. They represent persistent data. Often the data
persistence is managed through a database, using JDBC.
Subtypes of Entity Beans:
Bean-managed persistence:
The entity bean handles its own persistence. Often via JDBC (or SQL/J) to a
database. The bean author is required to write persistence management code into the
bean code itself.
Container-managed persistence:
The entity bean’s persistence is automatically maintained by the EJB container.
This is the easiest way, and often EJB containers do a better job because they provide
extra features like connection pooling, load balancing, etc. This method is known to be
extremely reliable, since CMP code is usually well tested. Persistence logic is kept in
“declarative code” in the EJB deployment descriptor.

More Related Content

What's hot

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programmingAmit Soni (CTFL)
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating SystemsRitu Ranjan Shrivastwa
 
Multithreading
MultithreadingMultithreading
MultithreadingA B Shinde
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
Control structures in java
Control structures in javaControl structures in java
Control structures in javaVINOTH R
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)Prakhar Maurya
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in javasharma230399
 
Networking Models
Networking ModelsNetworking Models
Networking ModelsAftab Mirza
 
Error managing and exception handling in java
Error managing and exception handling in javaError managing and exception handling in java
Error managing and exception handling in javaAndhra University
 
Java multi threading
Java multi threadingJava multi threading
Java multi threadingRaja Sekhar
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's typesNishant Joshi
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaAbhilash Nair
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Services provided by os
Services provided by osServices provided by os
Services provided by osSumant Diwakar
 

What's hot (20)

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Process synchronization in Operating Systems
Process synchronization in Operating SystemsProcess synchronization in Operating Systems
Process synchronization in Operating Systems
 
Introduction to Web Services
Introduction to Web ServicesIntroduction to Web Services
Introduction to Web Services
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
Control structures in java
Control structures in javaControl structures in java
Control structures in java
 
Threads (operating System)
Threads (operating System)Threads (operating System)
Threads (operating System)
 
input/ output in java
input/ output  in javainput/ output  in java
input/ output in java
 
Networking Models
Networking ModelsNetworking Models
Networking Models
 
Web services
Web servicesWeb services
Web services
 
Threads concept in java
Threads concept in javaThreads concept in java
Threads concept in java
 
Error managing and exception handling in java
Error managing and exception handling in javaError managing and exception handling in java
Error managing and exception handling in java
 
Constructor in java
Constructor in javaConstructor in java
Constructor in java
 
Java multi threading
Java multi threadingJava multi threading
Java multi threading
 
5. protocol layering
5. protocol layering5. protocol layering
5. protocol layering
 
Semophores and it's types
Semophores and it's typesSemophores and it's types
Semophores and it's types
 
Java naming conventions
Java naming conventionsJava naming conventions
Java naming conventions
 
Constants, Variables and Data Types in Java
Constants, Variables and Data Types in JavaConstants, Variables and Data Types in Java
Constants, Variables and Data Types in Java
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Services provided by os
Services provided by osServices provided by os
Services provided by os
 

Similar to SERVER SIDE PROGRAMMING

Similar to SERVER SIDE PROGRAMMING (20)

TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Ajp notes-chapter-06
Ajp notes-chapter-06Ajp notes-chapter-06
Ajp notes-chapter-06
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
 
J servlets
J servletsJ servlets
J servlets
 
Weblogic
WeblogicWeblogic
Weblogic
 
Servlet by Rj
Servlet by RjServlet by Rj
Servlet by Rj
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Servlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, APIServlet in java , java servlet , servlet servlet and CGI, API
Servlet in java , java servlet , servlet servlet and CGI, API
 
Marata
MarataMarata
Marata
 
Servlet classnotes
Servlet classnotesServlet classnotes
Servlet classnotes
 
JavaEE6 my way
JavaEE6 my wayJavaEE6 my way
JavaEE6 my way
 
WEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptxWEB TECHNOLOGY Unit-3.pptx
WEB TECHNOLOGY Unit-3.pptx
 
Servlet
Servlet Servlet
Servlet
 
Java servlets
Java servletsJava servlets
Java servlets
 
Ftp servlet
Ftp servletFtp servlet
Ftp servlet
 

More from Prabu U

Computation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnComputation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnPrabu U
 
Concurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingConcurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingPrabu U
 
File Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasFile Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasPrabu U
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsPrabu U
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APIPrabu U
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingPrabu U
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesPrabu U
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and ObjectsPrabu U
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based ApplicationsPrabu U
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XMLPrabu U
 
WEB SERVICES
WEB SERVICESWEB SERVICES
WEB SERVICESPrabu U
 
Internet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingInternet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingPrabu U
 
Operation Management
Operation ManagementOperation Management
Operation ManagementPrabu U
 
Nature and Importance of Management
Nature and Importance of ManagementNature and Importance of Management
Nature and Importance of ManagementPrabu U
 
Replacement and Maintenance Analysis
Replacement and Maintenance AnalysisReplacement and Maintenance Analysis
Replacement and Maintenance AnalysisPrabu U
 
Elementary Economic Analysis
Elementary Economic AnalysisElementary Economic Analysis
Elementary Economic AnalysisPrabu U
 
Introduction to Engineering Economics
Introduction to Engineering EconomicsIntroduction to Engineering Economics
Introduction to Engineering EconomicsPrabu U
 
Files in C
Files in CFiles in C
Files in CPrabu U
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and PointersPrabu U
 

More from Prabu U (20)

Computation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit LearnComputation Using Scipy, Scikit Image, Scikit Learn
Computation Using Scipy, Scikit Image, Scikit Learn
 
Concurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network ProgrammingConcurrency and Parallelism, Asynchronous Programming, Network Programming
Concurrency and Parallelism, Asynchronous Programming, Network Programming
 
File Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with PandasFile Input/output, Database Access, Data Analysis with Pandas
File Input/output, Database Access, Data Analysis with Pandas
 
Arrays with Numpy, Computer Graphics
Arrays with Numpy, Computer GraphicsArrays with Numpy, Computer Graphics
Arrays with Numpy, Computer Graphics
 
Lambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream APILambdas, Collections Framework, Stream API
Lambdas, Collections Framework, Stream API
 
Exception handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread ProgrammingException handling, Stream Classes, Multithread Programming
Exception handling, Stream Classes, Multithread Programming
 
String Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and InterfacesString Handling, Inheritance, Packages and Interfaces
String Handling, Inheritance, Packages and Interfaces
 
Classes and Objects
Classes and ObjectsClasses and Objects
Classes and Objects
 
Building XML Based Applications
Building XML Based ApplicationsBuilding XML Based Applications
Building XML Based Applications
 
Introduction to XML
Introduction to XMLIntroduction to XML
Introduction to XML
 
WEB SERVICES
WEB SERVICESWEB SERVICES
WEB SERVICES
 
XML
XMLXML
XML
 
Internet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side ProgrammingInternet Principles and Components, Client-Side Programming
Internet Principles and Components, Client-Side Programming
 
Operation Management
Operation ManagementOperation Management
Operation Management
 
Nature and Importance of Management
Nature and Importance of ManagementNature and Importance of Management
Nature and Importance of Management
 
Replacement and Maintenance Analysis
Replacement and Maintenance AnalysisReplacement and Maintenance Analysis
Replacement and Maintenance Analysis
 
Elementary Economic Analysis
Elementary Economic AnalysisElementary Economic Analysis
Elementary Economic Analysis
 
Introduction to Engineering Economics
Introduction to Engineering EconomicsIntroduction to Engineering Economics
Introduction to Engineering Economics
 
Files in C
Files in CFiles in C
Files in C
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 

Recently uploaded

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130Suhani Kapoor
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxwendy cai
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxupamatechverse
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 

Recently uploaded (20)

HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
VIP Call Girls Service Kondapur Hyderabad Call +91-8250192130
 
What are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptxWhat are the advantages and disadvantages of membrane structures.pptx
What are the advantages and disadvantages of membrane structures.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
Introduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptxIntroduction to Multiple Access Protocol.pptx
Introduction to Multiple Access Protocol.pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 

SERVER SIDE PROGRAMMING

  • 1. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 1 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | UNIT II SERVER SIDE PROGRAMMING Servlet - Strengths - Architecture -Life cycle- Generic and HTTP Servlet - Passing parameters- Server Side Include- Cookies- Filters. JSP - Engines-Syntax - Components - Scriplets - JSP Objects - Actions -Tag Extensions - Session Tracking - Database connectivity - Sql statements. J2EE - Introduction - Beans - EJB. SERVLET What are Servlets?  Java servlets are small, platform-independent Java programs that can be used to extend the functionality of a Web Server.  Servlets are not tied to a specific client-server protocol but they are most commonly used with HTTP and the word "Servlet" is often used in the meaning of "HTTP Servlet".  It is available and runs on all major web and application servers. It is based on Java. Hence it is platform and server independent. Functions of Servlets  Dynamically build and return an HTML file based on nature of client request.  Process user input passed by an HTML form and return an appropriate response.  Provide user authentication and Security mechanisms.  Interact with server resources such as databases, other applications and network files to return useful information to the client.  Allow the server to communicate with a client applet via a custom protocol and keep the connection open throughout the conversation.  Automatically attach web page design elements, such as headers or footers, to all pages returned by server.  Forward requests from one server to another for load balancing purpose. Role of Servlets in Web Application Design  Servlets can read explicit data sent in by the browser client. This data can come from an HTML page into which user has entered data or even an applet. Servlets can also read implicit request data which is sent by browser as part of request header.  Servlets can dynamically generate and send content back to client as a response. This process may involve talking to databases, executing an RMI call, executing another server-side component and so on.  The response sent can be in form of pure HTML, plain text, XML, GIF images or even as compressed data.  Servlets can also communicate with one another for load balancing purposes. HTTP is essentially a stateless protocol. However, many applications need to manage state on top of this stateless protocol.
  • 2. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 2 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2.1 STRENGTHS / ADVANTAGES OF SERVLETS 1.Compilation: Compilation offers the advantages of strong error and type checking. Since many errors are flushed out during the compilation, servlets are more stable and easier to develop and debug. 2.Crash Resistance: The JVM does not allow servlets direct access to memory locations, thereby eliminating crashes that results from invalid memory accesses. In addition, before execution, the JVM verifies that compiled Java class files are valid and do not perform illegal operations. Finally, rather than crashing, the JVM will propagate an exception up the calling chain it is caught. Thus, a poorly written or malicious servlet cannot crash server. 3.Cross-Platform: Since servlets are written in Java, they enjoy the same cross platform support as any program. This "write once, run anywhere" capability allows servlets to be easily distributed throughout the enterprise without rewriting for each platform. 4.Cross-Server: Servlets can be run on virtually every popular web server that is in use today. More than a dozen software vendors currently provide native support for servlets within their products. For those servers that do not currently offer native servlet support, there are many third party add-ons that allow these servers to load and run servers. 5.Durable: Servlets are durable objects and remain in memory until specifically instructed to be destroyed. In addition, a servlet can create other durable objects for use across many requests. For Example: Create a single database connection when servlet is first loaded. This connection can then be shared across all requests. 6.Dynamically Loadable across the Network: Servlets can be dynamically loaded either locally or from across the network. Dynamic loading ensures that unused servlets do not consume precious server resources. They are only loaded when needed. 7.Extensible: Since servlets are written in Java, there is a wealth of third-party support for writing and extending them. New development tools, Java class libraries and database drivers are constantly becoming available and they all can be utilized by servlets. 8.Multithreaded: Servlets allow client requests to be handled by separate threads within a single process. Thus it requires far less overhead and executes much more quickly than say a CGI program. 9.Protocol Independent: Servlets are completely protocol independent. Protocol independence allows a servlet to be specially constructed to support FTP commands, SMTP or POP3 e-mail functionality, Telnet sessions, NNTP newsgroup or any other protocols. The servlet API does an excellent job of providing strong support for common HTTP functionality without sacrificing the ability to support other protocols. 10.Secure: Servlets are written in Java. Hence invalid memory access calls and strong typing violations are not possible. Servlets use server's Security Manager for customization and enforcement of specific security policies. 2.2 ARCHITECTURE  A servlet, in its most general form, is an instance of a class which implements javax.servlet.Servlet interface  Most servlets extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet or javax.servlet.http.HtttpServlet.
  • 3. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 3 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Figure: Basic Servlet Architecture 2.2.1 Servlet API  Servlets use classes and interfaces from two packages: javax.servlet and javax.servlet.http.  A servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.Httpservlet.  A protocol-independent servlet should subclass GenericServlet, while an HTTP servlet should subclass HTTPServlet, which is itself a subclass of GenericServlet.  Notice that the classes do not belong to the core Java API. They are extensions to the core API and hence javax. 2.2.2 GenericServlet  It is protocol independent. It implements javax.servlet.GenericServlet.  It makes writing servlets easier.  It provides simple versions of init() and destroy() and of the methods in the ServletConfig interface.  It also implements the log method, declared in the ServletContext interface.  All the lifecycle methods are implemented in GenericServlet class.  To write a generic servlet, override the abstract service(). request response Figure: GenericServlet Class Servlet GenericServlet HTTPServlet MyServlet GenericServlet subclass Web Server service()
  • 4. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 4 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | i) ServletContext interface  It defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.  There is one context per "web application" per JVM.  ServletContext attributes can be used to share information among group of servlets.  The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. ii) ServletConfig interface  This is a servlet configuration object used by a servlet container used to pass information to a servlet during initialization.  It is implemented by GenericServlet.  All of its initialization parameters can only be set in deployment descriptor. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. 2.2.3 HttpServlet  javax.servlet.http.HttpServlet  It has a built-in HTTP protocol support.  Its subclass must override at least one of the following methods: doGet(), doPost(), doHead(), doTrace(), doPut(), doDelete().  One must not override the service() method, since it dispatches a request to the different doXXX() methods for different HTTP requests. Figure: HttpServlet Class  init() and destroy() can be overriden to manage resources that are held for the life of servlet. Servlet can implement getServletinfo() to provide information about itself.  The service() method of HttpServlet dispatches a request to different Java methods for different HTTP request methods. It recognizes the standard HTTP/1.1 methods like GET, HEAD, PUT, POST, DELETE, OPTIONS and TRACE. Other methods are answered with a Bad Request HTTP error.  Do not override the service() method because it handles setup and dispatching to all the doXXX() methods. Since service() method dispatches to doXXX() methods, it passes its request and response objects to these methods. Web Server HTTPServlet subclass service() doGet() doPost()
  • 5. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 5 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |  An HTTP servlet generally overrides doGet() to handle GET requests and doPost() to handle POST type of requests. Example: import java.io.*; // Servlets are not part of standard SDK, they are part of J2EE import javax.servlet.*; import javax.servlet.http.*; //Servlets normally extend HttpServlet public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //Setting the response type res.setContentType("text/html"); // Getting PrintWriter object to send response to client PrintWriter out = res.getWriter(); // Output to the client out.println("<HTML>"); out.println("<HEAD><TITLE>Hello World </TITLE></HEAD>"); out.println("BODY"); out.println("<BIG> Hello World </BIG"); out.println("</BODY></HTML>"); } }; 2.3 LIFECYLCE 1. Servlet Interface Life Cycle Methods init() It is executed once when the servlet is first loaded. service() It is called in a new thread by server for each request. destroy() It is called when server deletes servlet instance. 2. Sequence of Life Cycle Methods The servlet interface defines methods to be called only once during the servlet's lifecycle. They are known as life-cycle methods and are called in the following sequence: 1. The init() method is guaranteed to be called only once during the servlet's lifecycle. The servlet performs one-time setup procedures in this method. It stores the ServletConfig object so that it can be retrieved later by calling the Servlet's getServletConfig() method (This is handled by GenericServlet). The ServletConfig object contains Servlet parameters and a reference to the Servlet's ServletContext. 2. service() method gets called every time a new request comes in. The method's called concurrently( that is, multiple threads may call this method at the same time) so it should be implemented in a thread-safe manner.
  • 6. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 6 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 3. When servlet needs to be unloaded(for example: since a new version should be loaded or the server is shutting down), the destroy() method is called. This method is guaranteed to be called only once during the servlet's lifecycle. All resources which were allocated in init() should be released in destroy(). 3. Steps of Life Cycle Methods The process by which a server invokes a servlet can be broken down into the nine steps 1. The server loads the servlet when the client first requests it or, if configured to do so, at server start-up. The servlet may be loaded from either a local or remote location using the standard Java class loading facility. This step is equivalent to the following code: Class c = Class.forName("edu.skcet.Myservlet"); 2. The server creates one or more instances of the servlet class. Depending on the implementation, the server may create a single instance that services all requests through multiple threads or create a pool of instances from which one is chosen to service each new request. This step is equivalent to the following Java code: Servlet s= (Servlet) c.newinstance(); 3. The server constructs a ServletConfig object that provides initialization information to the servlet. 4. The server calls the servlet's init(ServletConfig cfg) method. The init() method is guaranteed to finish execution prior to the servlet processing the first request. If the server created multiple servlets instances (step 2), then the init method is called one time for each instance. 5. The server constructs a ServletRequest or HttpServletRequest object from the data included in the client's request. It also constructs ServletResponse or HttpServletResponse object that provides methods for customizing the server's response. The type of objects passed in these two parameters depend on whether the server extends the GenericServlet class or the HttpServlet class, respectively. 6. The server calls the servlet's service() (or other, more specific method like doGet() or doPost() for HTTP Servlets), passing the objects constructed in step 5 as parameters. When concurrent requests arrive, multiple service() methods can run in separate threads. 7. The service() method processes the client request by evaluating the ServletRequest or HttpServletRequest object and ServletResponse or HttpServletResponse object. 8. If the server receives another request for this servlet, the process begins at step 5. 9. When instructed to unload the servlet, perhaps by server administrator or programmatically by the server itself, the server calls the servlet's destroy() method. The servlet is then eligible for garbage collection.
  • 7. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 7 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 4. Thread Pooling  Thread pooling save the virtual machine from the work of creating brand new threads for every short-lived task.  In addition, it minimizes overhead associated with getting a thread started and cleaning it up after it dies.  By creating a pool of threads, a single thread from the pool can be recycled over and over for different tasks.  With the thread pooling technique, you can reduce response time. This is because a thread is already constructed and started and is simply waiting for its next task.  In the case of an HTTP servlet, an available thread in the pool can deliver each new file requested.  Without pooling, a brand new thread would have to be constructed and started before the request can be serviced. Figure: Servlet Life Cycle 2.4 GENERIC AND HTTP SERVLET 1. Generic Servlet ( Refer 2.2.2) 2. HttpServlet (Refer 2.2.3)
  • 8. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 8 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 3. Difference between Generic and HttpServlet GENERICSERVLET HTTPSERVLET Can be used with any protocol (means, can handle any protocol). Protocol independent. Should be used with HTTP protocol only (can handle HTTP specific protocols) . Protocol dependent. All methods are concrete except service() method. service() method is abstract method. All methods are concrete (non-abstract). service() is non-abstract method. service() should be overridden being abstract in super interface. service() method need not be overridden. It is a must to use service() method as it is a callback method. Being service() is non-abstract, it can be replaced by doGet() or doPost() methods. Extends Object and implements interfaces Servlet, ServletConfig and Serializable. Extends GenericServlet and implements interface Serializable Direct subclass of Servet interface. Direct subclass of GenericServlet. Defined javax.servlet package. Defined javax.servlet.http package. All the classes and interfaces belonging to javax.servlet package are protocol independent. All the classes and interfaces present in javax.servlet.http package are protocol dependent (specific to HTTP). Not used now-a-days. Used always. 2.5 PASSING PARAMETERS 1. init() method  Each registered servlet can have specific initialization (init) parameters associated with it. These are available to the servlet at any time.  They are often used in the init() method to set initial or default values for a servlet or to customize the servlet's behavior in some way.  Settings of initialization parameters are server specific. This init parameters are specified in web.xml, using <init-param> tags.
  • 9. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 9 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2. getInitParameter() The getInitParameter() method returns the value of the named init parameter or null if it does not exist. The GenericServlet class implements the servlet config interface and thus provides direct access to the getInitParameter() method. Example: web.xml <servlet> <servlet-name>ParameterDemo</servlet-name> <servlet-class>edu.skcet.ParameterDemo</servlet-class> </servlet> <context-param> <param-name>email</param-name> <param-value>admin@email.com</param-value> </context-param> ParameterDemo.java public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { PrintWriter out = response.getWriter(); out.println(getServletContext().getInitParameter("email")); } 3. Reading Request parameter from Servlet Login.jsp <html> <head><title>Login Page</title></head> <body> <form name="LoginForm" action="/login" method="post"> <label>Username</label> <input type="text" name="username" /> <label>Password</label> <input type="password" name="password" /> <input type="submit" value="Login" /> </form> </body> </html>
  • 10. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 10 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | LoginServlet.java import java.io.IOException; import java.io.PrintWriter; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class LoginServlet extends HttpServlet implements Servlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doLogin(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doLogin(request, response); } protected void doLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username = request.getParameter("username"); String password = request.getParameter("password"); PrintWriter out = response.getWriter(); if (username != null && username.equals("administrator") && password != null && password.equals("secret")) { out.println("Success!"); } else { out.println("Denied!"); } out.close(); } }
  • 11. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 11 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2.6 SERVER SIDE INCLUDE  SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).  Servlets are not confined to handling entire requests. Some web servers allow servlets to add small amounts of dynamic content to otherwise static HTML pages.  This is similar to the server-side include functionality found in most web servers, but includes additional servlet-specific functionality.  For example, let's assume that we want to use a server-side include to add a randomly selected advertisement to a page.  A page that uses the advertisement servlet is written just like a normal HTML page, except that it contains one or more <SERVLET> tags and is saved with the .shtml extension.  The <SERVLET> tag is similar to the <APPLET> tag, which loads an applet within a page. When a client requests a .shtml page, the server finds all of the <SERVLET> tags in the text and replaces them with the output from the appropriate servlets.  When you use a <SERVLET> tag, you must include a CODE parameter that identifies the servlet to be loaded. This can be a class name or a servlet alias set up within the server. On some servers, you can specify an optional CODEBASE parameter that loads the servlet code from a remote location.  Any additional parameters are treated as servlet initialization parameters. Each <SERVLET> tag must be matched by a closing</SERVLET> tag.  Between the opening and closing tags, you can include as many <PARAM> tags as necessary, where you specify NAME and VALUE attributes for each one.  The servlet can then access these parameters with getParameter(). Example: Time.shtml <HTML> <HEAD><TITLE>Times!</TITLE></HEAD> <BODY> The current time here is: <SERVLET CODE=CurrentTime> </SERVLET> <P> The current time in London is: <SERVLET CODE=CurrentTime> <PARAM NAME=zone VALUE=GMT> </SERVLET> <P> And the current time in New York is: <SERVLET CODE=CurrentTime> <PARAM NAME=zone VALUE=EST> </SERVLET> <P> </BODY> </HTML>
  • 12. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 12 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | A server-side include that prints the current time CurrentTime.java import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CurrentTime extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out = res.getWriter(); Date date = new Date(); DateFormat df = DateFormat.getInstance(); String zone = req.getParameter("zone"); if (zone != null) { TimeZone tz = TimeZone.getTimeZone(zone); df.setTimeZone(tz); } out.println(df.format(date)); } } 2.7 COOKIES Cookie is a small text file containing client information sent by a web server to a browser that can later be read back from the browser.  When a browser receives a cookie, it saves the cookie and there after sends the cookie back to the server each time it accesses a page on that server, subject to certain rules.  Since cookie's value can uniquely identify a client, cookies are often used for session tracking.  The browser is expected to support 20 cookies for each Web server, 300 cookies total and may limit cookie size to 4kb each. 1. Working with Cookies Cookie can be created using Cookie class which is in the package javax.servlet.http.cookie i) To create cookie use Cookie class constructor public Cookie(String name, String Value0 ii) Once the cookie is created, send the cookie to the browser using the following method: HttpServletResponse.addCookie(Cookie cookie) iii) Cookies can be retrieved by servlet from a request using the following method: HttpServletRequest.getCookies()
  • 13. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 13 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2. Cookie Methods i) public void setComment(java.lang.String purpose) It specifies a comment that describes a cookie's purpose. ii) public java.lang.String getComment() It returns the comment using describing the purpose of this cookie, or null if the cookie has no comment. iii) public void setDomain(java.lang.String pattern) It specifies the domain name set for this cookie. iv) public void setMaxAge(int expiry) It sets the maximum age of the cookie in seconds. A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age. A negative value means that the cookie is not stored persistently and will be deleted when the Web browsers exits. A zero value causes the cookie to be deleted. v) public int getMaxAge() It returns the maximum age of the cookie, specified in seconds. If getMaxAge returns a negative value, the cookie was not stored persistently. This method does not return a zero value, because if a cookie's age was set to zero with setMaxAge, the cookie was deleted. vi) public void setPath(java.lang.String uri) It specifies a path for the cookie, which is the set of URIs to which the client should return the cookie. The cookie is visible to all the pages in the directory you specify, and all pages in that directory's subdirectories. A cookie's path must include the servlet that set the cookie, For Example, servlet/dir1, which makes the cookie visible to all directories on the server under dir1. vii) public java.lang.String getPath() It returns the paths (that is, URIs) on the server to which the browser returns this cookie. The cookie is visible to all subdirectories within the specified path on the server. viii) public void setSecure(boolean flag) It indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL. You should only use this method when the cookie's originating server used a secure protocol to set the cookie's value. The default value is false. ix) public boolean getSecure() It returns true if the browser is sending cookies only over a secure protocol, or false if the browser can use a standard protocol.
  • 14. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 14 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Example: cookieExample.html <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>COOKIES</title> </head> <body> <form action="CookieSer"method="GET"> First Name: <input type="text"name="first_name"> <br/> Last Name: <input type="text"name="last_name"/> <input type="submit"value="Submit"/> </form> </body> </html> CookieSer.java package cookieExample; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CookieSer extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Create cookies for first and last names. Cookie firstName =new Cookie("first_name", request.getParameter("first_name")); Cookie lastName =new Cookie("last_name", request.getParameter("last_name")); // Set expiry date after 24 Hrs for both the cookies. firstName.setMaxAge(60*60*24); lastName.setMaxAge(60*60*24); // Add both the cookies in the response header. response.addCookie( firstName ); response.addCookie( lastName ); // Set response content type response.setContentType("text/html"); PrintWriter out= response.getWriter(); String title ="Setting Cookies Example"; String docType ="<!doctype html public "-//w3c//dtd html 4.0 "+ "transitional//en">n";
  • 15. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 15 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | out.println(docType + "<html>n"+ "<head><title>"+ title +"</title></head>n"+ "<body bgcolor="#f0f0f0">n"+ "<h1 align="center">"+ title +"</h1>n"+ "<ul>n"+ " <li><b>First Name</b>: " + request.getParameter("first_name")+"n"+ " <li><b>Last Name</b>: " + request.getParameter("last_name")+"n"+ "</ul>n"+ "</body></html>"); } } 2.8 FILTERS  Filter is a component which dynamically intercepts requests and responses to transform or use the information contained in the requests or responses.  Filters typically do not themselves create responses but provide universal functions that can be "attached" to any type of servlet or JSP page.  A filter is a program that runs on the server before the servlet with which it is associated. Benefits of Filters  Filters encapsulates common behaviour in a modular and reusable manner.  It separates high-level access decisions from presentation code.  It applies wholesale changes to many different resources. 1. Types / Components of Filter Filters can perform many different types of functions. Based on their functionalities following are the filters i) Authentication: Blocking requests based on user identity. ii) Logging and auditing: Tracking users of a web application. iii) Image conversion: Scaling maps and so on. iv) Localization: Targeting the request and response to particular locale. v) XSL/T Transformations of XML Content: Targeting web application responses to more than one type of client. 2. Programming a Filter Filter API is defined by the Filter, FilterChain and FilterConfig interfaces in the javax.servlet package. Creating a filter involves five basic steps: i) Create a class that implements the Filter interface The class need three methods: doFilter, init, destroy. The doFilter method contains the main filtering code (see Step 2), the init method performs setup operations, and the destroy method does cleanup. ii) Put the filtering behaviour in the doFilter method The first argument to the doFilter method is a ServletRequest object. This object gives filter full access to the incoming information, including form data, cookies and HTTP request headers. The second argument is a ServletResponse; it is mostly ignored in simple filters. The final argument is FilterChain; it is used to invoke the servlet or JSP page as described in the next page.
  • 16. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 16 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | iii) Call the doFilter method of the FilterChain object The doFilter method of the Filter interface takes a FilterChain object as one of its arguments. When the doFilter method of that object is called, the next associated filter is invoked. If no other filter is associated with the servlet or JSP page, then the servlet or page itself invoked. iv) Register the filter with the appropriate servlets and JSP pages Use the filter and filter-mapping elements in the deployment descriptor (web.xml). v) Disable the invoker servlet: Prevent users from bypassing filter setting by using default servlet URLs. 3. Filter Configuration Filter is configured in web.xml and is mapped to servlet or JSP. To map a filter to a servlet:  Declare the filter using the <filter> element in the web application deployment descriptor. This element creates a name for the filter and declares the filter's implementation class and initialization parameters.  Map the filter to a servlet by defining a <filter-mapping> element in the deployment descriptor. This element maps a filter name to a servlet by name or by URL pattern. 4. Filter Elements in web.xml The filter element is placed near the top of deployment descriptor(web.xml) before any element. The filter element contains six possible subelements.  icon: This is a optional element declaring an image file that an IDE can use.  filter-name: This is a required element that assigns a name of your choosing to the filter.  display-name: This is a optional element that provides a short name for use by IDEs  description: This is a optional element that gives information for IDEs. It provides textual documentation.  filter-class: This is a required element that specifies the fully qualified name of the filter implementation class.  init-param: This is an optional element that defines initialization parameters that can be read with the getInitParameter() method of Filterconfig. A single filter element can contain multiple init-param elements. 5. Filter-mapping Element The filter-mapping element goes in the web.xml after the filter element but before the servlet element. It contains three possible subelements.  filer-name: This required element must match the name you gave to the filter when declared it with the filter element.  url-pattern: This element declares a pattern starting with a slash (/) that designates the URLs to which the filter applies. url-pattern or servlet-name in all filter-mapping elements.  servlet-name: This element gives a name that must match a name given to a servlet or JSP page by means of the servlet element.
  • 17. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 17 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 6. Process of Registering Filter with Servlet  One filter can be associated with more than one servlet.  More than one filter can be mapped to a servlet.  A filter can be mapped to all the servlet using an "*"  The filter, filter-mapping, servlet and servlet-mapping elements must appear in the web application deployment descriptor in that order. <filter-mapping> <filter-name> LogFilter </filter-name> <servlet-name>LoginTest </servlet-name> </filter-mapping> <servlet> <servlet-name>LoginTest</servlet-name> <servlet-class> edu.skcet.LoginTest</servlet-class> </servlet> <servlet-mapping> <servlet-name> LoginTest</servlet-name> <url-pattern> /LoginTest </url-pattern> </servlet-mapping> 7. Filter Life Cycle Methods controlling life cycle of a filer are as follows  init()  doFilter()  Destroy() The cycle is similar to that of a servlet. Three methods of Filter interface makes up the life cycle of a filter 1. public void init(FilterConfig config) throws ServletException The init method is executed only once, when the filter is first initialized. It is not executed each time the filter is invoked. 2. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException The doFilter method is executed each time a filter is invoked(ie., once for each request for a servlet or JSP page with which the filter is associated). It is this method that contains the bulk of the filtering logic. 3. public void destroy() This method is called when a server is permanently finished with a given filter object(Example: when the server is being shut down). Most filter simply provide an empty body for this method, but it can used for cleanup tasks like closing files or database connection pools that are used by the filter. Filter interface A filter configuration object used by a servlet container to pass information to a filter during initialization. FilterChain interface  A FilterChain is an object provided by the servlet container giving a view into the invocation chain of a filtered request for a resource.
  • 18. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 18 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |  Filters use the FilterChain to invoke the next filter in the chain, or if the calling filter is the last filter in the chain, to invoke the resource at the end of the chain. For example, The below figure shows how Filters F1 and F3 intercept invocations to Servlet S1. Example: SiteHitCounter.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class SiteHitCounter implements Filter { private int hitCount; public void init(FilterConfig config) throws ServletException { // Reset hit counter hitCount =0; } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // increase counter by one hitCount++; // Print the counter System.out.println("Site visits count :"+ hitCount ); // Pass request back down the filter chain chain.doFilter(request, response); } public void destroy() { // This is optional step but if you like you // can write hitCount value in your database. } } F3 F2 F1 S1 S2 S3
  • 19. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 19 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | web.xml <filter> <filter-name>SiteHitCounter</filter-name> <filter-class>SiteHitCounter</filter-class> </filter> <filter-mapping> <filter-name>SiteHitCounter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> Output Site visits count :1 Site visits count :2 Site visits count :3 Site visits count :4 Site visits count :5
  • 20. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 20 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | JAVA SERVER PAGES (JSP) What is JSP? Java Server Pages (JSP) is a simple, yet powerful technology for creating and maintaining dynamic-content web pages. Based on the Java programming language, JSP offers proven portability, open standards, and a mature re-usable component model. JSP allows developing web applications in a more efficient manner than servlets. JSP separates "presentation logic" from "business logic".  Presentation is in the form of HTML or XML/XSLT  Business logic is implemented in Java beans or custom tags  Thus it provides for better maintainability and reusability Salient features of JSP JSP provides following features over Servlets 1. Portability: JSP files can run on any web server or web-enabled application server that provides support for them. 2. Composition: JSP architecture includes reusable Java components such as Java beans and Servlets. 3. Processing: JSP contains HTML tags + JSP scripting tags. The JSP page is parsed and processed (translated) into a Servlet. JSP versus Servlet  JSP technology is built over Servlet. Servlets are Java code with embedded HTML and JSP is HTML with embedded Java Code.  In fact, all JSP pages when requested, are first converted into Servlet. Thus they inherit all benefits of Servlets.  Although dynamic, interactive pages can be created with Servlets alone, using JSP technology makes the process even easier.  JSP allows to clearly separate content from presentation. This is unlike Servlets where business logic and presentation logic co-exist many times in a single program. JSP versus/advantages over Competing technologies 1. JSP versus ASP.Net and ColdFusion  It is a better language for dynamic part.  It is not portable to multiple servers and operating systems. 2. JSP versus PHP  It is a better language for dynamic part.  It is a better tool support. 3. JSP versus JavaScript  Dynamic information is based on server environment.  It can access server-side resources whereas JavaScript cannot. 4. JSP versus Static HTML  JSP can generate dynamic content whereas HTML cannot.  JSP can access server-side resources whereas HTML cannot. 5. JSP versus Velocity  It is a standard whereas Velocity is not.
  • 21. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 21 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 6. JSP versus Server-Side Includes (SSI)  JSP uses Servlet instead of separate program to generate dynamic part.  JSP allows for richer processing of form data. ARCHITECTURE / ACCESS METHODS / ACCESS MODELS 1. JSP Model 1 Architecture  In this model, the client request comes directly to a Java Server Page.  Suppose the page accesses reusable JavaBean components that performs particular well-defined computations like accessing a database.  Then the result of the Bean's computations called result sets are stored within the Bean as properties.  The page uses such beans to generate dynamic content and present it back to the client. Figure: JSP Model 1 Architecture 2. JSP Model 2 Architecture  In this model, the request comes through a Servlet. The Servlet generates the dynamic content. To handle the response to the client, the Servlet creates a Bean and stores the dynamic content (sometimes called the result set) in the Bean. The Servlet then invokes a Java Server Page that will present the content generated by the Bean.  In this model, the Servlet acts as a controller responsible for processing requests and creating any beans needed by the JSP page. The controller is also responsible for deciding to which JSP page to forward the request. The JSP page retrieves objects created by the Servlet and extracts dynamic content for insertion within a template. This model promotes the use of the Model View Controller (MVC) architectural pattern.  There are two APIs to support this model of request processing using Java Server Pages.  One API facilitates passing context between the invoking Servlet and the Java Server Page.  The other API lets the invoking Servlet specify which Java Server Page to use.
  • 22. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 22 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Figure: JSP Model 2 Architecture JSP PROCESSING MODEL / LIFE CYCLE  JSP is stored as text file(.jsp) in the web application. When the client requests for the page for the first time, the server (web container) translates the JSP into Java source code (.java) and if there are no translation errors then it is compiled into a Servlet class file.  The Servlet class is then loaded by the class loader, and then instantiated. For the first time request, the jspInit() method (if present) is called to initialize resources.  If the request for the JSP page is not the first time request, then the translation to Initialization steps are skipped and the request is directly processed by _jspService() method.  The web container invokes the jspDestroy method(if present), to cleanup resources, when the server shuts down or if the JSP page is replaced with a modified one.  The lifecycle methods of the JSP page is translated into the Servlet have the following form:  public void jspInit()  public void jspDestroy()  public void _jspService(HttpServlet Request request, HttpServletResponse response) throws ServletException, IOException Figure: JSP Life Cycle
  • 23. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 23 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2.9 ENGINES  The web server needs a JSP engine i.e. container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. This tutorial makes use of Apache which has built-in JSP container to support JSP pages development.  A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. JSP Processing: 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 a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behaviour 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: Figure: JSP Processing
  • 24. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 24 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |  Typically, the JSP engine checks to see whether a Servlet for a JSP file already exists and whether the modification date on the JSP is older than the Servlet.  If the JSP is older than its generated Servlet, the JSP container assumes that the JSP hasn't changed and that the generated Servlet still matches the JSP's contents.  This makes the process more efficient than with other scripting languages (such as PHP) and therefore faster.  So in a way, a JSP page is really just another way to write a Servlet without having to be a Java programming wiz. Except for the translation phase, a JSP page is handled exactly like a regular Servlet. 2.10 SYNTAX JSP pages use several delimiters for scripting functions. The most basic is <% ... %>, which encloses a JSP scriptlet. A scriptlet is a fragment of Java code that is run when the user requests the page. 1. JSP Scriptlet  A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.  A JSP scriptlet is used to insert Java code into the _jspService method.  Scriptlets are executed when the JSP engine processes the client request. If the scriplet produces output, then the output is stored in the out object, from which can display it.  Note that code inside a scriptlet gets inserted exactly as written. Any static HTML (template text) before or after a scriptlet gets converted to print statements. Syntax <% Java Code %> Example <html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html> Output
  • 25. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 25 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2. JSP Declarations A JSP declaration is used to define methods or fields that are inserted in the Servlet class outside the _jspService() method. Syntax <%! Java Code %> Example: Count accesses to page since server reboot <%! private int accessCount=0; %> <%=++accessCount %> Declaration can be used to override jspInit() and jspDestroy() methods of Servlet. 3. JSP Expressions  A JSP expression is used to insert Java values directly into the output.  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. Syntax <%=Java Expression %> Example <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> Output Today's date: 17-Jan-2016 21:24:25 4. JSP Comments JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. Syntax <%-- This is JSP comment --%> Example <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> 5. JSP Directives  Directives are messages to the JSP container.  Instruction for the JSP engine that are processed when the JSP page is translated into Servlet.  A JSP Directive affects the overall structure of the Servlet class.  It has the form <%@directive {attribute="value"}* %> There are three types of directives page: It lets you do things like import classes, customize the Servlet super class. include: It lets you insert a file into the Servlet class at that time the JSP file is translated into a Servlet. taglib: It is intended to let JSP authors define their own tags. i) Page Directive  The JSP page directive defines a number of page independent properties and communicates these to the JSP container.  JSP page directive applies to the entire JSP file and any of its static include files called as translation unit.  It can be used more than once in a translation unit.  All attributes except "import" can be used only once per translation unit.
  • 26. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 26 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Syntax <%@page {language="scriptingLanguage"} {extends="className"} {import="importList"} {session="true|false"} {buffer="none|sizekb"} {autoflush="true|false"} {isThreadSafe="true|false"} {info="info_text"} {errorPage="error_url"} {isErrorPage="true|false"} {contentType="ctinfo"} {pageEncoding="peinfo"} {isELIgnored="true|false"} {deferredSyntaxAllowedAsLiteral="true|false"} {trimDirectiveWhitespaces="true|false"} %> Example <%@ page import="java.util.*"%> ii) Include Directive  The include directive includes files at the time the JSP page is translated into a Servlet.  The included file can be an HTML file, a JSP file, a text file or a java code file.  The include process is static.  Change in the included file will not be reflected in the JSP file in which it is included. Syntax <%@include%> Example <html> <head><title> Include Directive </title></head> <body> <%@include file="header.html"%> Page Body <!-- Part specific to this page --> <%@include file="footer.html"%> </body> </html> iii) Taglib Directive  It is intended to let JSP authors define their own tags.  It provides a set of reusable standard tags. Syntax <%@taglib %>
  • 27. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 27 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Example <%@taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <html> <body> <c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}"/> <br/> </c:forEach> </body> </html> 2.11 COMPONENTS Refer 2.10 Syntax 2.12 SCRIPTLETS Refer 2.10 (1. JSP Scriptlets) 2.13 JSP OBJECTS Implicit objects provide programmers with access to many Servlet capabilities in the context of a Java Server Page. Implicit objects have four scopes: application, page, request and session. 1. Application Scope The JSP and Servlet container application owns objects with application scope. Any Servlet or JSP can manipulate such objects. i) application This javax.servlet.ServletContext object represents the container in which the JSP executes. 2. Page Scope Objects with page scope exist only in the page that defines them. Each page has its own instances of the page-scope implicit objects. i) config This javax.servlet.ServletConfig object represents the JSP configuration options. As with servlets, configuration options can be specified in a Web application descriptor. ii) exception This java.lang.Throwable object represents the exception that is passed to the JSP error page. This object is available only in a JSP error page. iii) out This javax.servlet.jsp.JspWriter object writes text as part of the response to a request. This object is used implicitly with JSP expressions and actions that insert string content in a response. iv) page This java.lang.Object object represents the this reference for the current JSP instance. v) pageContext This javax.servlet.jsp.PageContext object hides the implementation details of the underlying Servlet and JSP container and provides JSP programmers with access to the implicit objects discussed in this table.
  • 28. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 28 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | vi) response This object represents the response to the client. The object normally is an instance of a class that implements HttpServletResponse(package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a class that implements javax.servlet.ServletResponse. 3. Request Scope Objects with request scope exist for the duration of the request. For example, a JSP can partially process a request, then forward the request to another Servlet or JSP for further processing. Request-scope objects go out of scope when request processing completes with a response to the client. i) request This object represents the client request. The object normally is an instance of a class that implements HttpServletRequest (package javax.servlet.http). If a protocol other than HTTP is used, this object is an instance of a subclass of javax.servlet.ServletRequest. 4. Session Scope Objects with session scope exist for the client’s entire browsing session. i) session This javax.servlet.http.HttpSession object represents the client session information if such a session has been created. This object is available only in pages that participate in a session. 2.14 JSP ACTIONS JSP actions use constructs in XML syntax to control the behaviour of the Servlet engine. With JSP actions, you can do either of the following:  Dynamically insert a file.  Reuse JavaBeans components.  Forward the user to another page.  Generate HTML for the Java plugin. Available actions include: jsp:include: It includes a file at the time the page is requested. jsp:forward: It forwards a client request to an HTML file, JSP file or Servlet for processing. jsp:plugin: It generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin. jsp:useBean: It finds or instantiates a JavaBean. jsp:setProperty: It sets the property of a JavaBean jsp:getProperty: It inserts the property of a JavaBean into the output. 1. The jsp:include Action The <jsp:include> element allows to include either a static or dynamic file in a JSP file. The results of including static and dynamic files are quite different.  If the file is static, its content is included in the calling JSP file.  If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page. The <jsp:include> action lets insert files into the page being generated.
  • 29. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 29 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Syntax: <jsp:include page="{relative URL | <%=expression%>}" flush="true"/> If the included file is dynamic, <jsp:param> clause to pass the name and value of a parameter to the dynamic file. As an example, you can pass the string username and a user's name to a login form that is coded in a JSP file. Syntax: <jsp:include page="{relative URL | <%=expression%>}" flush="true"/> <jsp:param name="parameterName" value="{parameterValue |<%=expression%>}"/>+ </jsp:include> Example: Banner (banner.html) to include across the top of the XHTML document <!-- banner to include in another document --> <div style = "width: 580px"> <p> Java(TM), C, C++, Visual Basic(R), Object Technology, and <br /> Internet and World Wide Web Programming Training&nbsp;<br /> On-Site Seminars Delivered Worldwide </p> <p> <a href = "mailto:deitel@deitel.com">deitel@deitel.com</a><br /> 978.579.9911<br /> 490B Boston Post Road, Suite 200, Sudbury, MA 01776 </p> </div> Table of contents (toc.html) to include down the left side of the XHTML <!-- contents to include in another document --> <p><a href ="http://www.deitel.com/books/index.html"> Publications/BookStore </a></p> <p><a href ="http://www.deitel.com/whatsnew.html"> What's New </a></p> <p><a href ="http://www.deitel.com/books/download.html">Downloads/Resources</a></p> <p><a href ="http://www.deitel.com/faq/index.html"> FAQ (Frequently Asked Questions) </a></p> <p><a href = "http://www.deitel.com/intro.html"> Who we are </a></p> <p><a href = "http://www.deitel.com/index.html"> Home Pagec </a></p> <p>Send questions or comments about this site to <a href = "mailto:deitel@deitel.com"> deitel@deitel.com </a><br /> Copyright 1995-2002 by Deitel &amp; Associates, Inc. All Rights Reserved. </p> JSP clock2.jsp to include as the main content in the XHTML document <!-- date and time to include in another document --> <table><tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan; font-size: 3em; font-weight: bold;"> <%= new java.util.Date() %> </p> </td></tr> </table>
  • 30. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 30 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | JSPinclude.jsp Includes resources with <jsp:include> <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Using jsp:include</title> <style type = "text/css"> body { font-family: tahoma, helvetica, arial, sans-serif; } table, tr, td { font-size: .9em; border: 3px groove; padding: 5px; background-color: #dddddd; } </style> </head> <body> <table> <tr> <td style = "width: 160px; text-align: center"> <img src = "images/logotiny.png" width = "140" height = "93" alt = "Deitel & Associates, Inc. Logo" /> </td> <td> <%-- include banner.html in this JSP --%> <jsp:include page = "banner.html" flush = "true" /> </td> </tr> <tr> <td style = "width: 160px"> <%-- include toc.html in this JSP --%> <jsp:include page = "toc.html" flush = "true" /> </td> <td style = "vertical-align: top"> <%-- include clock2.jsp in this JSP --%> <jsp:include page = "clock2.jsp" flush = "true" /> </td> </tr> </table> </body> </html>
  • 31. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 31 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Output: 2. The jsp:forward Action  The <jsp:forward> element forwards the request object containing the client request information from one JSP file to another file.  The target file can be an HTML file, another JSP file or a Servlet.  A jsp:forward effectively terminates the execution of the current page.  If the page output is buffered, then the buffer is cleared prior to forwarding. Syntax: <jsp:forward page="{relativeURL | <%=expression %>}" {/> | > [jsp:param name="parameterName" value="{ parameterValue | <%=expression %>}" />]+ </jsp:forward> Example: JSP forward1.jsp receives a firstName parameter, adds a date to the request parameters and forwards the request to forward2.jsp for further processing <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>Forward request to another JSP</title></head> <body> <% // begin scriptlet String name = request.getParameter( "firstName" ); if ( name != null ) { %> // end scriptlet
  • 32. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 32 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | <jsp:forward page = "forward2.jsp"> <jsp:param name = "date" value = "<%= new java.util.Date() %>" /> </jsp:forward> <% // continue scriptlet } // end if else { %> <%-- end scriptlet to insert fixed template data --%> <form action = "forward1.jsp" method = "get"> <p>Type your first name and press Submit</p> <p><input type = "text" name = "firstName" /> <input type = "submit" value = "Submit" /> </p> </form> <% // continue scriptlet } // end else %> <%-- end scriptlet --%> </body> </html> JSP forward2.jsp receives a request (from forward1.jsp in this example) and uses the request parameters as part of the response to the client <?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <!-- forward2.jsp --> <html xmlns = "http://www.w3.org/1999/xhtml"v <head><title>Processing a forwarded request</title> <style type = "text/css"> .big { font-family: tahoma, helvetica, arial, sans-serif; font-weight: bold; font-size: 2em; } </style> </head> <body> <p class = "big"> Hello <%= request.getParameter( "firstName" ) %>, <br /> Your request was received <br /> and forwarded at</p> <table style = "border: 6px outset;"> <tr> <td style = "background-color: black;"> <p class = "big" style = "color: cyan;">
  • 33. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 33 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | <%= request.getParameter( "date" ) %> </p> </td> </tr> </table> </body> </html> jsp:forward versus response.sendRedirect jsp:forward response.sendRedirect Server-side redirect, hence no network traffic Client-side redirect, hence additional network round trip The address of the destination page hidden from user. The address of the destination page visible to user in the address bar. Allows forwarding of the request to another page in the same context as the current page. Allows re-direction of the request to another page in same or different context as the current page. 3. The jsp:plugin Action  The plugin action enables a JSP author to generate HTML that contains the appropriate client browser dependent constructs (OBJECT or EMBED).  The plugin action will result in the download of the Java plugin (if required).  It will execute the Applet or JavaBeans component specified in jsp:plugin action. Syntax: <jsp:plugin type="bean | applet" code= "classFileName" codebase="classFileDirectoryName" [name="instanceName"] [arhive="URIToArchive, ..."] [height="displayPixels"] [width="diplayPixels"] [align="bottom | top | middle | left | right"] [hspace="leftRightPixels"]
  • 34. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 34 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | [vspace="topBottomPixels"] [jreversion="JREVersionNumber | 1.1"] [nspluginurl="URLToplugin"] [iepluginurl=" URLToplugin "] [<jsp:params> [<jsp:param name="parameterName" value="parameterValue" />+ </jsp:params>] [<jsp:fallback> text message for user </jsp:fallback>] </jsp:plugin> Example: HelloApplet.java import java.applet.*; import java.awt.event.*; import java.awt.*; public class HelloApplet extends Applet { public void paint(Graphics g) { g.drawString("Hello",15,12); } public void update(Graphics g) { paint(g); } } plugin.jsp <html> <head><title>Using jsp:plugin to load an applet</title></head> <body> <jsp:plugin type="applet"code="HelloApplet.class" jreversion="1.2" width="150"height="100"> <jsp:fallback> Plugin tag OBJECT or EMBED not supported by browser </jsp:fallback> </jsp:plugin> </body> </head> </html> 4.The <jsp:useBean> Action  A <jsp:useBean> action associates an instance of a Java object defined within a given scope available with a given id via newly declared scripting variable of the same id.  The action tries to find an existing object using id and scope. If it is not found, then it will attempt to create the object using the other attributes. Syntax <jsp:useBean id="beanInstanceName" scope="page|request|session|application" beanName="{package.class | <%=expression%>}" type="package.class" </jsp:useBean>
  • 35. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 35 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 5. The <jsp:setProperty> Action  The jsp:setProperty action sets the value of properties in a bean. The name attribute denotes an object that must be defined before this action appears.  Property in a Bean can be set from either of the following:  one or more parameters in the request object  a String constant  a computed request-time expression Syntax <jsp:setProperty name="beanInstanceName" property="*" | property="propertyName" [ param="parameterName"] | property="propertyName" value="{string| <%=expression%>}" /> Type Conversion for setProperty Action Property Type Conversion from String boolean or Boolean java.lang.Boolean.valueOf(String) byte or Byte java.lang.Byte.valueOf(String) char or Character java.lang.Character.valueOf(String) double or Double java.lang.Double.valueOf(String) int or Integer java.lang.Integer.valueOf(String) float or Float java.lang.Float.valueOf(String) Long or Long java.lang.Long.valueOf(String) 6. The <jsp:getProperty> Action  The jsp:getProperty element retrieves the value of a bean property, converts it to a string, and inserts it into the output.  The two required attributes are:  name: the name of a bean previously referenced via jsp:useBean  property: the property whose value should be inserted. Syntax <jsp:getProperty name="beanInstanceName" property="propertyName"/> Type Conversion for getProperty Action Property Type Conversion from String boolean java.lang.Boolean.toString (boolean) byte java.lang.Byte. toString (byte) char java.lang.Character. toString (char) double java.lang.Double. toString (double) int java.lang.Integer. toString (int) float java.lang.Float. toString (float) long java.lang.Long. toString (long)
  • 36. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 36 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2.15 TAG EXTENSIONS / CUSTOM TAGS  A custom tag is a user-defined JSP element.  Custom tags have a rich set of features. They can  Be customized via attributes passed from the calling page  Pass variables back to the calling page  Access all the objects available to JSP pages  Be nested within one another  Custom tags are required to  Replace the Java code with tags in JSP page.  Help page authors to easily develop JSP page 1. Types of Tags i) Tags with Attributes <example:hello name="Hi"></example:hello> ii) Tags with Bodies <example:reverse> This is body content </example:reverse> iii) Tags with variables <example:hello name="Sham">Hello<%=name%> </example:hello> 2. Process / Steps of Creating Custom Tags i) Creation of Tag Handler Class Tag handler is a java class which handles the tag processing for a particular tag. To create the custom tag, first we need to create the tag handler for that tag. ii) Creation of Tag Library Descriptor Tag Library Descriptor is a file which includes the entries for mapping the tag and its tag handler. This file is saved with TLD extension. iii) Modification of web.xml to use tag library In order to use tags from a specific tag library descriptor in web application, an entry for TLD should be added in web.xml iv) Importing TLD  Once TLD entry is made in web.xml, all jsp files from that web application will be able to use different tags from that TLD file.  To use tags from the specific TLD, we need to import TLD file in jsp by using taglib directive. v) Use of Custom Tags in JSP  After TLD tags are made available for the particular JSP page, one can use different tags from that TLD file in JSP page code at various places.  Thus these custom tags contribute in processing certain functionality required by that JSP page. Properties / Constants of Tag interface EVAL_BODY_INCLUDE: It evaluates body into existing out stream. EVAL_PAGE: It continues evaluating the page. SKIP_BODY: It skips body evaluation. SKIP_PAGE: It skips the rest of the page.
  • 37. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 37 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Step 1:Creation of Tag Handler Class HelloTag.java public class HelloTag extends TagSupport { public int doStartTag() throws JspTagException { return EVAL_BODY_INCLUDE; } public int doEndTag() throws JspTagException { pageContext.getOut().write("Helloworld <br/>"); return EVAL_PAGE; } } Step 2: Creation of the Tag Library Descriptor Demo.tld <taglib> <tlibversion>1.0</tlibversion> <jspversion>2.1</jspversion> <shortname>examples</shortname> <tag> <name>hello</name> <tagclass>lab.wt.HelloTag</tagclass> <bodycontent>empty</bodycontent> <info>Simple Example</info> </tag> </taglib> Step 3 & 4: Entry in web.xml & JSP Page Web.xml <jsp-config> <taglib> <taglib-uri>demo.tld</taglib-uri> <taglib-location>/WEN-INF/demo.tld</taglib-location> </taglib> </jsp-config> Hello.jsp <%@taglib uri="demo.tld" prefix="examples"%> <html> <head><title>First Custom Tag</title></head> <body> This is static output<p/> <i><examples:hello></examples:hello></i> This is static output again </body> </html>
  • 38. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 38 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2.16 SESSION TRACKING The Session Object  JSP makes use of Servlet provided 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.  By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for each new client automatically. Disabling session tracking requires explicitly turning it off by setting the page directive session attribute to false as follows: <%@ page session="false" %> Methods and Description 1. public Object getAttributeStringname This method returns the object bound with the specified name in this session, or null if no object is bound under the name. 2. public Enumeration getAttributeNames This method returns an Enumeration of String objects containing the names of all the objects bound to this session. 3. public long getCreationTime This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. 4. public String getId This method returns a string containing the unique identifier assigned to this session. 5. public long getLastAccessedTime This method returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. 6. public int getMaxInactiveInterval This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. 7. public void invalidate This method invalidates this session and unbinds any objects bound to it. 8. public boolean isNew This method returns true if the client does not yet know about the session or if the client chooses not to join the session. 9. public void removeAttribute Stringname This method removes the object bound with the specified name from this session. 10. public void setAttributeStringname, Objectvalue This method binds an object to this session, using the name specified. 11. public void setMaxInactiveInterval intinterval This method specifies the time, in seconds, between client requests before the Servlet container will invalidate this session. Example: <%@ page import="java.io.* ,java.util.* " %> <% // Get session creation tim e. Date createTime = new Date(session.getCreationTime()); // Get last access tim e of this web page.
  • 39. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 39 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Date lastAccessTime = new Date(session.getLastAccessedTime()); String title = "Welcome Back to my website"; Integer visitCount = new Integer(0); String visitCountKey = new String("visitCount"); String userIDKey = new String("userID"); String userID = new String("ABCD"); // Check if this is new com er on your web page. if (session.isNew()) { title = "Welcome to my website"; session.setAttribute(userIDKey, userID); session.setAttribute(visitCountKey, visitCount); } visitCount = (Integer)session.getAttribute(visitCountKey); visitCount = visitCount + 1; userID = (String)session.getAttribute(userIDKey); session.setAttribute(visitCountKey, visitCount); %> <htm l> <head><title>Session Tracking</title></head> <body> <center> <h1>Session Tracking</h1> </center> <table border="1" align="center"> <tr bgcolor="#949494"> <th>Session info</th> <th>Value</th> </tr> <tr> <td>id</td> <td><% out.print( session.getId()); %></td> </tr> <tr> <td>Creation Tim e</td> <td><% out.print(createTim e); %></td> </tr> <tr> <td>Tim e of Last Access</td> <td><% out.print(lastAccessTime); %></td> </tr> <tr> <td>User ID</td> <td><% out.print(userID); %></td> </tr> <tr> <td>Num ber of visits</td> <td><% out.print(visitCount); %></td> </tr> </table> </body> </html>
  • 40. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 40 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2.17 DATABASE CONNECTIVITY  Java Database Connectivity (JDBC) is a standard SQL database access interface, providing uniform access to a wide range of relational databases.  JDBC allows us to construct SQL statements and embed them inside Java API calls. JDBC Features:  JDBC supports all the advanced features of latest SQL version.  JDBC API provides a rich set of methods.  It provides a clean, simple, uniform vendor independent interface. Example: <%@ page language="java" import="java.sql.*" %> <HTML> <HEAD> <TITLE> The JDBCQuery JSP </TITLE> </HEAD> <BODY BGCOLOR="white"> <% String searchCondition = request.getParameter("cond"); if (searchCondition != null) { %> <H3> Search results for <I> <%= searchCondition %> </I> </H3> <B> <%= runQuery(searchCondition) %> </B> <HR><BR> <% } %> <B>Enter a search condition:</B> <FORM METHOD="get"> <INPUT TYPE="text" NAME="cond" SIZE=30> <INPUT TYPE="submit" VALUE="Ask Oracle"); </FORM> </BODY> </HTML> <%-- Declare and define the runQuery() method. --%> <%! private String runQuery(String cond) throws SQLException { Connection conn = null; Statement stmt = null; ResultSet rset = null; try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); conn = DriverManager.getConnection("jdbc:oracle:oci8:@", "scott", "tiger"); stmt = conn.createStatement(); // dynamic query rset = stmt.executeQuery ("SELECT ename, sal FROM scott.emp "+ (cond.equals("") ? "" : "WHERE " + cond )); return (formatResult(rset)); } catch (SQLException e) { return ("<P> SQL error: <PRE> " + e + " </PRE> </P>n"); }
  • 41. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 41 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | finally { if (rset!= null) rset.close(); if (stmt!= null) stmt.close(); if (conn!= null) conn.close(); } } private String formatResult(ResultSet rset) throws SQLException { StringBuffer sb = new StringBuffer(); if (!rset.next()) sb.append("<P> No matching rows.<P>n"); else { sb.append("<UL>"); do { sb.append("<LI>" + rset.getString(1) + " earns $ " + rset.getInt(2) + ".</LI>n"); } while (rset.next()); sb.append("</UL>"); } return sb.toString(); } %> OUTPUT: 2.18 SQL STATEMENTS SQL stands for Structured Query Language. Pronounced as SEQUEL, SQL was originally developed by IBM based on Dr.E.F. Codd's relational model to define, manipulate and control data in a database. Almost all modern Relational Database Management Systems like MS SQL Server, Microsoft Access, MSDE, Oracle, DB2, Sybase, MySQL, Postgres and Informix use SQL as standard database language. 1. Rules for SQL statements  SQL keywords are not case sensitive. However, normally all commands (SELECT,INSERT, etc) are upper-cased.  Variable and parameter names are displayed as lower-case.  New-line characters are ignored in SQL.  Many DBMS systems terminate SQL statements with a semi-colon character.  Character strings and date values are enclosed in single quotation marks while using them in WHERE clause or otherwise.
  • 42. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 42 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | 2. Standard SQL statement groups GROUPS STATEMENTS DESCRIPTION DQL SELECT Data Query Language - It is used to get data from the database. DML DELETE INSERT UPDATE MERGE Data Manipulation Language - It is used to change database data. DDL DROP TRUNCATE CREATE ALTER Data Definition Language - It is used to manipulate database structures and definitions TCL COMMIT ROLLBACK SAVEPOINT TCL statements are used to manage the transactions. DCL REVOKE They are used to remove and provide access rights to database objects. i) The SELECT Statement public List<Employee> getAllDetails() throws EmployeeException { Connection con=null; Statement st=null; ResultSet rs=null; List<Employee> l=new ArrayList<Employee>(); try { con=new DBConnection().getConnection(); st=con.createStatement(); rs=st.executeQuery("select * from employee_801774"); while(rs.next()) { Employee e=new Employee(); e.setEcode(rs.getInt(1)); e.setEname(rs.getString(2)); e.setDesignation(rs.getString(3)); e.setAge(rs.getInt(4)); e.setBasic_Pay(rs.getDouble(5)); e.setDept_num(rs.getInt(6)); l.add(e); } } catch (SQLException e1) { throw new EmployeeException(e1.getMessage()); } return l; }
  • 43. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 43 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | ii) The INSERT statement public boolean insertEmployee(Employee e) throws EmployeeException { Connection con=null; PreparedStatement ps=null; boolean result=false; try { con=new DBConnection().getConnection(); System.out.println(con); ps=con.prepareStatement("insert into employee_801774 values(?,?,?,?,?)"); ps.setString(1,e.getEname()); ps.setString(2,e.getDesignation()); ps.setInt(3,e.getAge()); ps.setDouble(4,e.getBasic_Pay()); ps.setInt(5,e.getDept_num()); int r=ps.executeUpdate(); if(r>=1) { result=true; } else { result=false; } } catch (SQLException e1) { throw new EmployeeException(e1.getMessage()); } return result; } iii) The DELETE STATEMENT public boolean deleteEmployee(int ecode) throws EmployeeException { Connection con=null; PreparedStatement ps=null; boolean result=false; try { con=new DBConnection().getConnection(); System.out.println(con); if(con!=null) { ps=con.prepareStatement("delete from employee_801774 where Ecode=?"); ps.setInt(1,ecode); int r=ps.executeUpdate(); if(r>=1)
  • 44. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 44 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | { result=true; } else { result=false; } } } catch (SQLException e1) { throw new EmployeeException(e1.getMessage()); } return result; } iv) The UPDATE Statement public boolean updateEmployee(String a,int b) throws EmployeeException { Connection con=null; PreparedStatement ps=null; boolean result=false; try { con=new DBConnection().getConnection(); System.out.println(con); if(con!=null) { ps=con.prepareStatement("update employee_801774 set Ename=? where Ecode=?"); ps.setString(1,a); ps.setInt(2,b); int r=ps.executeUpdate(); if(r>=1) { result=true; } else { result=false; } } } catch (SQLException e1) { throw new EmployeeException(e1.getMessage()); } return result; }
  • 45. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 45 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | JAVA 2 ENTERPRISE EDITION 2.19 J2EE INTRODUCTION J2EE ARCHITECTURE  The J2EE platform uses a distributed multitiered application model for enterprise applications.  Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs.  Figure shows two multitiered J2EE applications divided into the tiers described in the following list. The J2EE application parts shown in Figure are presented in J2EE Components.  Client-tier components run on the client machine.  Web-tier components run on the J2EE server.  Business-tier components run on the J2EE server.  Enterprise information system (EIS)-tier software runs on the EIS server.  Although a J2EE application can consist of the three or four tiers shown in Figure, J2EE multitiered applications are generally considered to be three tiered applications because they are distributed over three locations: client machines, the J2EE server machine, and the database or legacy machines at the back end.  Three-tiered applications that run in this way extend the standard two tiered client and server model by placing a multithreaded application server between the client application and back-end storage. Figure: Multitiered Applications
  • 46. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 46 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | J2EE COMPONENTS & CONTAINERS 1. J2EE COMPONENTS J2EE applications are made up of components. A J2EE component is a self- contained functional software unit that is assembled into a J2EE application with its related classes and files and that communicates with other components. The J2EE specification defines the following J2EE components:  Application clients and applets are components that run on the client.  Java Servlet and Java Server Pages (JSP) technology components are Web components that run on the server.  Enterprise JavaBeans (EJB) components (enterprise beans) are business components that run on the server. i) Application Clients  An application client runs on a client machine and provides a way for users to handle tasks that require a richer user interface than can be provided by a markup language.  It typically has a graphical user interface (GUI) created from the Swing or the Abstract Window Toolkit (AWT) API, but a command-line interface is certainly possible. Application clients directly access enterprise beans running in the business tier.  However, if application requirements warrant it, an application client can open an HTTP connection to establish communication with a servlet running in the Web tier. ii) Web Components  J2EE Web components are either servlets or pages created using JSP technology (JSP pages). Servlets are Java programming language classes that dynamically process requests and construct responses.  JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.  Static HTML pages and applets are bundled with Web components during application assembly but are not considered Web components by the J2EE specification.  Server-side utility classes can also be bundled with Web components and, like HTML pages, are not considered Web components.  As shown in Figure, the Web tier, like the client tier, might include a Java- Beans component to manage the user input and send that input to enterprise beans running in the business tier for processing. Figure: Web Tier and J2EE Applications
  • 47. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 47 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | iii) Business Components  Business code, which is logic that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier.  Figure shows how an enterprise bean receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage.  An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program.  There are three kinds of enterprise beans: session beans, entity beans, and message-driven beans.  A session bean represents a transient conversation with a client. When the client finishes executing, the session bean and its data are gone.  In contrast, an entity bean represents persistent data stored in one row of a database table. If the client terminates or if the server shuts down, the underlying services ensure that the entity bean data is saved.  A message-driven bean combines features of a session bean and a Java Message Service (JMS) message listener, allowing a business component to receive JMS messages asynchronously. Figure: Business and EIS Tiers 2. J2EE CONTAINERS i) Container Services ii) Container Types i) Container Services  Containers are the interface between a component and the low-level platform specific functionality that supports the component.  Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE module and deployed into its container.  The assembly process involves specifying container settings for each component in the J2EE application and for the J2EE application itself.  Container settings customize the underlying support provided by the J2EE server, including services such as security, transaction management, Java Naming and Directory Interface (JNDI) lookups, and remote connectivity.  Here are some of the highlights:
  • 48. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 48 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET |  The J2EE security model lets you configure a Web component or enterprise bean so that system resources are accessed only by authorized users.  The J2EE transaction model lets you specify relationships among methods that make up a single transaction so that all methods in one transaction are treated as a single unit.  JNDI lookup services provide a unified interface to multiple naming and directory services in the enterprise so that application components can access naming and directory services.  The J2EE remote connectivity model manages low-level communications between clients and enterprise beans. After an enterprise bean is created, a client invokes methods on it as if it were in the same virtual machine.  Because the J2EE architecture provides configurable services, application components within the same J2EE application can behave differently based on where they are deployed.  For example, an enterprise bean can have security settings that allow it a certain level of access to database data in one production environment and another level of database access in another production environment.  The container also manages nonconfigurable services such as enterprise bean and servlet life cycles, database connection resource pooling, data persistence, and access to the J2EE platform APIs.  Although data persistence is a nonconfigurable service, the J2EE architecture lets you override container-managed persistence by including the appropriate code in your enterprise bean implementation when you want more control than the default container-managed persistence provides.  For example, you might use bean-managed persistence to implement your own finder (search) methods or to create a customized database cache. ii) Container Types The deployment process installs J2EE application components in the J2EE containers illustrated in Figure. Figure: J2EE Server and Containers
  • 49. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 49 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | J2EE server The runtime portion of a J2EE product. A J2EE server provides EJB and Web containers. Enterprise JavaBeans (EJB) container Manages the execution of enterprise beans for J2EE applications. Enterprise beans and their container run on the J2EE server. Web container Manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server. Application client container Manages the execution of application client components. Application clients and their container run on the client. Applet container Manages the execution of applets. Consists of a Web browser and Java Plugin running on the client together. 2.20 ENTERPRISE JAVABEANS (EJB) 1. Enterprise JavaBeans  They are components that can be connected to form a system.  They can represent data. They can represent behaviour.  Usually, EJBs fall into only one of these categories.  They are typically used in the server tier. EJBs can be persisted. EJBs can interact with other EJBs. Advantages of EJBs:  EJBs are reusable components. Can be reused in different parts of the system. Can be packaged into libraries and sold.  EJBs Can be combined visually using development IDEs.  E.g. Visual Age, Visual Cafe  EJBs provide convenient abstractions so it do not require you to write  Multi-threaded, multiple access code  Database access code (e.g. JDBC)  Network communication code (i.e. it uses RMI) for client/server communication  Network communication code for EJB to EJB communication  Transaction management code  EJBs from different businesses can interact easily. This is because of their well- defined interfaces i) EJB Communication EJBs use IIOP as the wire protocol. Therefore, EJBs are compatible with RMI (i.e., RMI over IIOP) and CORBA libraries. Thus, you could write an EJB client in any language that supports CORBA. ii) EJB as Client/Server Middleware Think of EJBs as just another Client/Server middleware like RMI, CORBA, or Web Services. The EJB instance itself is the server. EJBs have clients (objects that call its methods). One complication is that EJB clients can be:  Java Applets and Applications (using RMI or CORBA)  Non-Java applications (using CORBA)  JSPs and Servlets (using RMI or CORBA)  Other EJBs (using RMI or CORBA)
  • 50. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 50 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | iii) EJBs & 3-Tiered Architectures In enterprise systems, EJB clients are usually: Servlets, JSPs, or Other EJBs. Figure: 3-Tiered Architecture iv) EJBs & Multi-Tiered Architectures Figure: Multi-Tiered Architecture How EJBs Change Things? EJBs are most suitable for developing business logic and data manipulation. If all of the business logic operations and data manipulations are done using EJBs, the JSPs and Servlets will be focused mainly on displaying the results of those operations.
  • 51. Dept of CSE | III YEAR | VI SEMESTER CS T63 | WEB TECHNOLOGY | UNIT 2 51 |Prepared By : Mr. PRABU.U/AP |Dept. of Computer Science and Engineering | SKCET | Session EJBs: Used to represent system behavior (i.e. business logic). e.g. Storing products to purchase in the shopping cart Entity EJBs: Used to represent & manipulate system data. e.g. Finding products that match a search term EJB Types 2. Types of Enterprise Beans i) Session beans Also called business process objects. They represent the business logic of the system. Their lifetime is usually an entire session. When a session is done, the session bean expires. i.e. Session bean instances exist as long as a specific user is using the system. Subtypes of Session Beans: Stateful: Used for operations that require multiple requests to be completed. Maintain data between requests. Stateless: Used for operations that can be performed in a single request. Do not maintain persistent data between subsequent requests from a given client. ii) Entity beans: Also called business data objects. They represent persistent data. Often the data persistence is managed through a database, using JDBC. Subtypes of Entity Beans: Bean-managed persistence: The entity bean handles its own persistence. Often via JDBC (or SQL/J) to a database. The bean author is required to write persistence management code into the bean code itself. Container-managed persistence: The entity bean’s persistence is automatically maintained by the EJB container. This is the easiest way, and often EJB containers do a better job because they provide extra features like connection pooling, load balancing, etc. This method is known to be extremely reliable, since CMP code is usually well tested. Persistence logic is kept in “declarative code” in the EJB deployment descriptor.