Unit4 Servlets, JSP

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

UNIT IV : WEB SERVERS

AND SERVLETS

CONTENTS

Introduction to Servlets

 Lifecycle of a servlet
 The servlet api
 The javax.servlet package
 The javax.servlet.http package
 Handling http request & responses using cookies
 Session tracking and security issues and servlets with database
connectivity
 Introduction to model view controller (mvc): architecture, its structure
components.
INTRODUCTION TO SERVLETS
Servlets offer several advantages in comparison with CGI. First,
performance is significantly better. Servlets execute within the address
space of a web server. It is not necessary to create a separate process to
handle each client request. Second, servlets are platform-independent
because they are written in Java. Third, the Java security manager on the
server enforces a set of restrictions to protect the resources on a server
machine. Finally, the full functionality of the Java class libraries is available
to a servlet. It can communicate with applets, databases,or other software
via the sockets and RMI mechanisms that you have seen already.

THE LIFE CYCLE OF A SERVLET


Three methods are central to the life cycle of a servlet. These are init( ),
service( ), and destroy( ). They are implemented by every servlet and are
invoked at specific times by the server. Let us consider a typical user
scenario to understand when these methods are called. First, assume that a
user enters a Uniform Resource Locator (URL) to a web browser. The
browser then generates an HTTP request for this URL. This request is then
sent to the appropriate server. Second, this HTTP request is received by the
web server. The server maps this request to a particular servlet. The servlet is
dynamically retrieved and loaded into the address space of the server. Third,
the server invokes the init( ) method of the servlet. This method is invoked
only when the servlet is first loaded into memory. It is possible to pass
initialization parameters to the servlet so it may configure itself. Fourth, the
server invokes the service( ) method of the servlet. This method is called to
process the HTTP request.
The servlet remains in the server’s address space and is available to process
any other HTTP requests received from clients. The service( ) method is
called for each HTTP request. Finally, the server may decide to unload the
servlet from its memory. The algorithms by which this determination is
made are specific to each server. The server calls the destroy( ) method to
relinquish any resources such as file handles that are allocated for the
servlet. Important data may be saved to a persistent store. The memory
allocated for the servlet and its objects can then be garbage collected.

JSDK : JAVA SOFTWARE DEVELOPMENT KIT


The JSWDK is the official reference implementation of the servlet 2.1 and
JSP 1.0 specifications. It is used as a small stand-alone server for testing
servlets and JSP pages before they are deployed to a full Web server that
supports these technologies. It is free and reliable, but takes quite a bit of
effort to install and configure.
install_dir/web
pages/WEB-
INF/servlets
Standard
location for
servlet classes.
• install_dir/classes
Alternate location for servlet classes.
• install_dir/lib
Location for JAR files containing classes.

THE SERVLET API


Two packages contain the classes and interfaces that are required to build
servlets. These are javax.servlet and javax.servlet.http. They constitute the
Servlet API. Keep in mind that these packages are not part of the Java core
packages. Instead, they are standard extensions provided by Tomcat.
Therefore, they are not included with Java SE
6. The Servlet API has been in a process of ongoing development and
enhancement.
THE JAVAX.SERVLET PACKAGE
The javax.servlet package contains a number of interfaces and classes
that establish the framework in which servlets operate. The following
table summarizes the core interfaces that are provided in this package.
The most significant of these is Servlet. All servlets must implement this
interface or extend a class that implements the interface. The
ServletRequest and ServletResponse interfaces are also very important.

The Servlet Interface


All servlets must implement the Servlet interface. It declares the init( ),
service( ), and destroy( ) methods that are called by the server during the
life cycle of a servlet. A method is also provided that allows a servlet to
obtain any initialization parameters.
The init( ), service( ), and destroy( ) methods are the life cycle
methods of the servlet. These are invoked by the server.

The ServletConfig Interface


The getServletConfig( ) method is called by the servlet to obtain
initialization parameters. A servlet developer overrides the
getServletInfo( ) method to provide a string with useful information (for
example, author, version, date, copyright). This method is also invoked by
the server.

The ServletContext Interface


The ServletContext interface enables servlets to obtain information about
their environment.

The ServletRequest Interface


The ServletRequest interface enables a servlet to obtain information about a
client request.

The ServletResponse Interface


The ServletResponse interface enables a servlet to formulate a response for a
client.
57
The

58
GenericServlet Class
The GenericServlet class provides implementations of the basic life cycle
methods for a servlet. GenericServlet implements the Servlet and
ServletConfig interfaces. In addition, a method to append a string to the
server log file is available. The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
Here, s is the string to be appended to the log, and e is an exception that
occurred.

The ServletInputStream Class


The ServletInputStream class extends InputStream. It is implemented
by the servlet container and provides an input stream that a servlet
developer can use to read the data from a client request. It defines the
default constructor. In addition, a method is provided to read bytes from
the stream. It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here, buffer is the array into which size bytes are placed starting at offset.
The method returns the actual number of bytes read or –1 if an end-of-stream
condition is encountered.

The ServletOutputStream Class


The ServletOutputStream class extends OutputStream. It is implemented
by the servlet container and provides an output stream that a servlet
developer can use to write data to a client response. A default constructor
is defined. It also defines the print( ) and println( ) methods, which output
data to the stream.

The Servlet Exception Classes


javax.servlet defines two exceptions. The first is ServletException, which
indicates that a servlet problem has occurred. The second is
UnavailableException, which extends ServletException.
It indicates that a servlet is unavailable.

READING SERVLET PARAMETERS


The ServletRequest interface includes methods that allow you to read the
names and values of parameters that are included in a client request. We
will develop a servlet that illustrates their use. The example contains two
files. A web page is defined in PostParameters.htm, and a servlet is defined
in PostParametersServlet.java.

The HTMLsource code for PostParameters.htm is shown in the following


listing. It defines a table that contains two labels and two text fields. One of
the labels is Employee and the other is Phone. There is also a submit
button.
Notice that the action parameter of the form tag specifies a URL. The URL
identifies the servlet to process the HTTP POST request.

<html>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/servlets-
examples/ servlet/PostParametersServlet">
<table>
<tr><td><B>Employee</td><td><input type=textbox name="e"
size="25" value=""></td></tr>
<tr><td><B>Phone</td><td><input type=textbox name="p"
size="25" value=""></td> </tr>
</table>
<input type=submit value="Submit"> </body> </html>
The source code for PostParametersServlet.java is shown in the following
listing. The service( ) method is overridden to process client requests. The
getParameterNames( ) method returns an enumeration of the parameter
names. These are processed in a loop. The parameter value is obtained via
the getParameter( ) method.

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

public class PostParametersServlet extends GenericServlet {

public void service(ServletRequest request,ServletResponse response)


throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();
// Get enumeration of parameter names.
Enumeration e = request.getParameterNames();
// Display parameter names and values.
while(e.hasMoreElements()) {
String pname =
(String)e.nextEl
ement();
pw.print(pname
+ " = ");
String pvalue =
request.getParameter
(pname);
pw.println(pvalue);
}
pw.close();
}
}

Compile the servlet. Next, copy it to the appropriate directory, and update
the web.xml file, perform these steps to test this example:

1. StartTomcat (if it is not already running).


2. Display the web page in a browser.
3. Enter an employee name and phone number in the text fields.
4. Submit the web page.

THE JAVAX.SERVLET.HTTP PACKAGE


The javax.servlet.http package contains a number of interfaces and
classes that are commonly used by servlet developers. You will see that
its functionality makes it easy to build servlets that work with HTTP
requests and responses.
The following table summarizes the core interfaces that are provided in this
package:
The following table summarizes the core classes that are provided in this
package. The most important of these is HttpServlet. Servlet developers
typically extend this class in order to process HTTP requests.

The HttpServletRequest Interface


The HttpServletRequest interface enables a servlet to obtain information
about a client request.
The HttpServletResponse Interface
The HttpServletResponse interface enables a servlet to formulate an HTTP
response to a client. Several constants are defined. These correspond to the
different status codes that can be assigned to an HTTP response. For
example, SC_OK indicates that the HTTP request succeeded, and
SC_NOT_FOUND indicates that the requested resource is not available.
The HttpSession Interface
The HttpSession interface enables a servlet to read and write the state
information that is associated with an HTTP session.. All of these methods
throw an IllegalStateException if the session has already been invalidated.

USING COOKIES & SESSION TRACKING


The Cookie Class
The Cookie class encapsulates a cookie. A cookie is stored on a client and
contains state information. Cookies are valuable for tracking user
activities. A user visits an online store. Acookie can save the user’s name,
address, and other information. The user does not need to enter this data
UNIT V: INTRODUCTION TO JSP
(Java Server Pages)

CONTENTS

 Introduction to JSP : The problem with servlet


 The anatomy of a JSP page : JSP processing, JSP applications
 JSP components: Comments, expressions, scriplets, JSTL tag library,
JSP database connectivity.
 Introduction to Web Servers
 Installing the Java software development kit
 Tomcat server & testing tomcat
 Structure of web application[Model-II MVC Architecture]
 Deploying web application [Tomcat Directory structure]
 IIS web server and GWS web server.
THE PROBLEM WITH SERVLET AND INTRODUCTION TO
JAVASERVERPAGES

JavaServer Pages (JSP) technology enables you to mix regular, static HTML with
dynamically generated content. To simple write the regular HTML in the normal
manner, using familiar Web-page-building tools. You then enclose the code for the
dynamic parts in special tags, most of which start with <% and end with%>.

We can think of servlets as Java code with HTML inside; you can think of JSP as
HTML with Java code inside. Now, neither servlets nor JSP pages are restricted to
using HTML, but they usually do and this over-simplified description is a common
way to view the technologies. Now, despite the large apparent differences between
JSP pages and servlets, behind the scenes they are the same thing. JSP pages are
translated into servlets, the servlets are compiled, and at request time it is the
compiled servlets that execute. So, writing JSP pages is really just another way of
writing servlets.

Even though servlets and JSP pages are equivalent behind the scenes, they are not
equally useful in all situations. Separating the static HTML from the dynamic
content provides a number of benefits over servlets alone, and the approach used in
JavaServer Pages offers several advantages over competing technologies.

Benefits of JSP

JSP pages are translated into servlets. So, fundamentally, any task JSP pages can
perform could also be accomplished by servlets. However, this underlying
equivalence does not mean that servlets and JSP pages are equally appropriate in all
scenarios. The issue is not the power of the technology, it is the convenience,
productivity, and maintainability of one or the other. After all, anything you can do
on a particular computer platform in the Java programming language you could also
do in assembly language. But it still matters which you choose.
JSP provides the following benefits over servlets alone:

It is easier to write and maintain the HTML. Your static code is


ordinary HTML: no extra backslashes, no double quotes, and no
lurking Java syntax.
You can use standard Web-site development tools. For example, we use
Macromedia Dreamweaver for most of the JSP pages in the book. Even
HTML tools that know nothing about JSP can be used because they simply
ignore the JSP tags.
You can divide up your development team. The Java programmers can work
on the dynamic code. The Web developers can concentrate on the presentation
layer. On large projects, this division is very important. Depending on the size
of your team and the complexity of your project, you can enforce a weaker or
stronger separation between the static HTML and the dynamic content.

THE ANATOMY OF JSP

The visible elements that make up a JSP page can include the
following: Directive elements
Template data
Action
Scripting elements
A JSP page does not need to have all of these visible elements, but you will very
likely encounter all of them if you look into any moderately complex JSP project.
The following sections briefly describe each visible element.
Directives
Unlike other JSP elements, directives are not used to generate output directly.
Rather, they are used to control some characteristics of a JSP page. Directives may
be used to give special instructions to the JSP container about what to do during the
translation of the page. You can always tell a directive from other elements because
it is enclosed in a special set of braces: <%@ ... directive ... %>

Three directives are allowed in JSP:


❑ page directive ❑ taglib directive ❑ include directive
XML-compatible syntax

A directive — for example, a taglib directive — typically appears in a JSP as <%@


taglib .............................................................................................................%>
The same element can also appear in a JSP as : <jsp:directive.taglib />
This is an XML-compatible syntax for expressing the JSP directive. There are
many advantages to expressing a JSP page in XML. For example, many developer
tools can work with XML documents directly. Enterprise technologies, such as
Web services, also make extensive use of XML. The emerging new XHTML
standard is also XML-based. Because JSP works intimately with these technologies
and the standard <%@ %> syntax is not valid XML, this alternative notation is
necessary.
All professional JSP developers are trained in the <%@ %> notation. There are
millions of lines of existing JSP code in this notation, so it will likely be supported for
the foreseeable future.

Template data
Template data is static text. This static text is passed directly through the JSP
container unprocessed. For example, it may be text that provides static HTML. The
template data is the static HTML.
Although most JSP pages are used in generating HTML pages, JSP is not specific
to HTML generation. If a JSP page is expressed in XML syntax, typically
contained in a .jspx file, the template data portion may have characters that need to
be escaped. For example, the characters < and > are not allowed directly in an
XML document and must be expressed as &lt; and &gt;, respectively.
Action
Action elements are JSP elements that are directly involved in the processing of the
request. In most cases, action elements enable you to access data and manipulate or
transform data in the generation of the dynamic output. For example, an online store
may have a JSP page that displays a shopping cart. This cart JSP shows the products
that you have purchased. Action elements may be used to generate the listing of the
products (dynamic content) on the page and to calculate the cost and shipping
(dynamic content), while template data (static HTML) is used to display the logo and
shipping policy statements.
Action elements can be either standard or custom. A standard action is dependably
available in every JSP container that conforms to the JSP 2.0 standard.
A custom action is an action created using JSP’s tag extension mechanism. This
mechanism
enables developers to create their own set of actions for manipulating data or generating
dynamic output within the JSP page.
Every XML tag has a name, optional attributes, and an optional body. For example, the
standard

<jsp:include> action can be coded as follows:


<jsp:include page=”news.jsp” flush=”false”/>

The name of this tag is jsp:include, the attributes are page and flush, and
this <jsp:include> instance does not have a body. The XML empty
notation is used.
An XML tag can also have a body containing other tags, of course:
<jsp:include page=”news.jsp” flush=”false”>
<jsp:param name=”user” value=”$,param.username-”/> </jsp:include>
In this tag, the name is still jsp:include and the attributes are still page and flush, but
now the body is no longer empty. Instead, the body contains a <jsp:param> standard
action. After template data, actions are the next most frequently used elements in JSP
coding. Actions are synonymous with tags because every action is an XML tag. The
terms are used interchangeably in this book, just as they are in the JSP developer
community.

Scripting elements
The practice of embedding code in another programming language within a JSP
page is called scripting. Scripting elements are embedded code, typically in the
Java programming language, within a JSP page. There are three different types of
scripting elements:
❑ Declarations ❑ Scriptlets ❑ Expressions
Declarations are Java code that is used to declare variables and methods. They appear as
follows:
<%! ... Java declaration goes here... %>
The XML-compatible syntax for declarations is:
<jsp:declaration> ... Java declaration goes here ... </jsp:declaration>
Scriptlets are arbitrary Java code segments. They appear as follows:
<% ... Java code goes here ... %>
The XML-compatible syntax for scriptlets is:
<jsp:scriptlet> ... Java code goes here ... </jsp:scriptlet>
Expressions are Java expressions that yield a resulting value. When the JSP is
executed, this value is converted to a text string and printed at the location of
the scripting element. Expression scripting elements appear as:
<%= ... Java expression goes here ... %>

The XML-compatible syntax for expressions is:


<jsp:expression> ... Java expression goes here ... </jsp:expression>

JSP PROCESSING

Just as a web server needs a servlet container to provide an interface to servlets, the
server needs a JSP container to process JSP pages. The JSP container is responsible
for intercepting requests for JSP pages. To process all JSP elements in the page, the
container first turns the JSP page into a servlet (known as the JSP page
implementation class). The conversion is pretty straightforward; all template text is
converted to println( ) statements similar to the ones in the handcoded servlet and all
JSP elements are converted to Java code that implements the corresponding dynamic
behavior. The container then compiles the servlet class. Converting the JSP page to a
servlet and compiling the servlet form the translation phase. The JSP container
initiates the translation phase for a page automatically when it receives the first
request for the page. Since the translation phase takes a bit of time, the first user to
request a JSP page notices a slight delay. The translation phase can also be initiated
explicitly; this is referred to as precompilation of a JSP page. Precompiling a JSP
page is a way to avoid hitting the first user with this delay. The JSP container is also
responsible for invoking the JSP page implementation class (the generated servlet) to
process each request and generate the response. This is called the request processing
phase. The two phases are illustrated in Figurebelow

As long as the JSP page remains unchanged, any subsequent request goes straight to
the request processing phase (i.e., the container simply executes the class file). When
the JSP page is modified, it goes through the translation phase again before entering
the request processing phase. The JSP container is often implemented as a servlet
configured to handle all requests for JSP pages. In fact, these two containers --a
servlet container and a JSP container--are often combined in one package under the
name web container. 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: it's loaded once and called repeatedly, until the
server is shut down. By virtue of being an automatically generated servlet, a JSP page
inherits all the advantages of a servlet as platform and vendor independence,
integration, efficiency, scalability, robustness, and security.

JSP APPLICATION DESIGN WITH MVC

JSP technology can play a part in everything from the simplest web application,
such as an online phone list or an employee vacation planner, to full-fledged
enterprise applications, such as a human-resource application or a sophisticated
online shopping site. How large a part JSP plays differs in each case, of course. In
this section, I introduce a design model called Model-View-Controller (MVC),
suitable for both simple and complex applications.

MVC was first described by Xerox in a number of papers published in the late
1980s. The key point of using MVC is to separate logic into three distinct units: the
Model, the View, and the Controller. In a server application, we commonly classify
the parts of the application as business logic, presentation, and request processing.
Business logic is the term used for the manipulation of an application's data, such as
customer, product, and order information. Presentation refers to how the application
data is displayed to the user, for example, position, font, and size. And finally,
request processing is what ties the business logic and presentation parts together. In
MVC terms, the Model corresponds to business logic and data, the View to the
presentation, and the Controller to the request processing.

MVC Architechture

An application data structure and logic (the Model) is typically the most stable part
of an application, while the presentation of that data (the View) changes fairly often.
Just look at all the face-lifts many web sites go through to keep up with the latest
fashion in web design. Yet, the data they present remains the same. Another
common example of why presentation should be separated from the business logic is
that you may want to present the data in different languages or present different
subsets of the data to internal and external users. Access to the data through new
types of devices, such as cell phones and personal digital assistants (PDAs), is the
latest trend. Each client type requires its own presentation format. It should come as
no surprise, then, that separating business logic from the presentation makes it easier
to evolve an application as the requirements change; new presentation interfaces can
be developed without touching the business logic.

JSP pages are used as both the Controller and the View, and JavaBeans components
are used as the Model. A single JSP page that handles everything, can use separate
pages for the Controller and the View to make the application easier to maintain.
Many types of real-world applications can be developed this way, but what's more
important is that this approach allows you to examine all the JSP features without
getting distracted by other technologies.
JSP Components
JSP categorized into 4 types
* Directives
* Standard Action elements
* Scriptlet Eléments
* Comments

a) Directives
 A directives tag always appears at the top of your JSP file.
 It is global definition sent to the JSP engine.
 Directives contain special processing instructions for the web container.
 You can import packages, define error handling pages or the session
information of the JSP page.
 Directives are defined by using <%@ and %> tags.
 Syntax -
<%@ directive attribute="value" %>
Directive elements
a) <%@ page ...%> Defines page-dependent attributes, such as session tracking, error
page, and buffering requirements
b) <%@ include ... %> Includes a file during the translation phase

c) <%@ tag lib ... %>Declares a tag library, containing custom actions, that is used in

Examples:
1)
<html>
<body>
<%@ page
import="java.util.Date" %>
Today is: <%= new Date() %>
</body>
</html>
2)
<html>
<body>
<%@ page
contentType="text/html" %>
Today is: <%= new
java.util.Date() %>
</body>
</html>
3)
<html>
<body>
<%@ include file="header.html" %>
Today is: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>

b) Standard Action Elements


 Action elements typically perform some action based on information
that is required at the exact time the JSP page is requested by a browser.
 An action can, for instance, access parameters sent with the request to
do a database lookup.
 It can also dynamically generate HTML, such as a table filled with
information retrieved from an external system.

c) Scripting Elements
Scripting elements, allow you to add small pieces of code (typically Java code)
in a JSP page Like actions, they are also executed when the page is requested.
i) Scriplets
 In this tag we can insert any amount of valid java code.
 These codes are placed in _jspService method by the JSP engine.
 Scriptlets can be used anywhere in the page.
 Scriptlets are defined by using <% and %> tags.
 Syntax - <% Scriptlets%>

Examples:
index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<% String name=request.getParameter("uname");
out.print("welcome "+name); %>
</body>
</html>

ii)Expressions:
 Expressions in JSPs is used to output any data on the generated page.
 These data are automatically converted to string and printed on the output stream.
 It is an instruction to the web container for executing the code with in
the expression and replace it with the resultant output content.
 For writing expression in JSP use <%= and %> tags.
 Syntax - <%= expression %>
Examples:
index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>

iii) Declarations
This tag is used for defining the functions and variables to be used in the JSP.
This element of JSPs contains the java variables and methods which you can call in
expression block of JSP page. Declarations are defined by using <%! and %> tags.
Whatever you declare within these tags will be visible to the rest of the
page. Syntax - <%! declaration(s) %>
Example1:
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
Example2:
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>

Comments
 This tag is used for defining the functions and variables to be used in the JSP.
 This element of JSPs contains the java variables and methods which
you can call in expression block of JSP page.
 Declarations are defined by using <%! and %> tags.
 Whatever you declare within these tags will be visible to the rest of the page.
 Syntax - <%! declaration(s) %>
<b>Last Name:</b><%= request.getParameter("last_name")%>
</body>
</html>

JSP - Standard Tag Library (JSTL)


 The Java Server Pages Standard Tag Library (JSTL) is a collection of
useful JSP tags which encapsulates the core functionality common to
many JSP applications.
 Classification of The JSTL Tags
According to their functions, The JSTL tags can be classified, into the following
JSTL tag library groups that can be used when creating a JSP page −
 Core Tags
 Formatting tags
 SQL tags
 XML tags
 JSTL Functions

a) Core Tags
 The core group of tags are the most commonly used JSTL tags.
 Following is the syntax to include the JSTL Core library in your JSP
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

b) FormattingTags
 The JSTL formatting tags are used to format and display text, the date,
the time, and numbers for internationalized Websites.
 Following is the syntax to include Formatting library in your JSP −
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>

c) SQL Tags

 The JSTL SQL tag library provides tags for interacting with
relational databases (RDBMSs) such as Oracle, mySQL, or
Microsoft SQL Server.
 Following is the syntax to include JSTL SQL library in your JSP −
<%@ taglib prefix = "sql" uri = "http://java.sun.com/jsp/jstl/sql" %>

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

XML tags
e)
 The JSTL XML tags provide a JSP-centric way of creating and
manipulating the XML documents.
 Following is the syntax to include the JSTL XML library in your JSP.
 The JSTL XML tag library has custom tags for interacting with the XML data.
<%@ taglib prefix = "x" uri = "http://java.sun.com/jsp/jstl/xml" %>

Database Connectivity with JSP Steps for connecting servlet to database(Mysql)


1)Import JDBC Packages
 This is for making the JDBC API classes immediately available to the
application program.
 The following import statement should be included in the program
irrespective of the JDBC driver being used:
Eg:import java.sql.*;
2) Load and register the JDBC driver.
 The first need is load the driver or register it before using it in the program .
 Registration is to be done once in your program.
 a)Class.forName() : Here we load the driver’s class file into memory at the
runtime..
 The following example uses Class.forName() to load the mysql driver –
Class.forName(―com.mysql.jdbc.Driver‖);
3) Create the connections
After loading the driver, establish connections using :
Connection con = DriverManager.getConnection(url,user,password)
Where user is username for database password is password for database
url is local host name with port number
4) Create a statement
 Once a connection is established you can interact with the database.
 The JDBCStatement, CallableStatement, and PreparedStatement
interfaces define the methods that enable to send SQL commands and
receive data from the database.
Eg: Prepared Statement ps= con.CreateStatement();
5) Execute the query
 The executeQuery() method of Statement interface is used to
execute queries of retrieving values from the database.
 This method returns the object of ResultSet that can be used to get all the
records of a table.
The executeUpdate(sql query) method of Statement interface is used to
execute queries of updating/inserting .
Eg:ps.executeUpdate();
6) Close the connections
 By closing connection, objects of Statement and Result Set
will be closed automatically.
 The close() method of Connection interface is used to close the connection.
Eg:con.close();
Example: (index.html)
<!doctype html>
<html >
<head>
<title>Document</title>
</head>
<body>
<h1> Welcome to Database Connectivity </h1>
<form action="login.jsp">
<h2> click the submit button to get data from register table </h2>
<input type ="submit" value="submit">
</form>
</body>
</html>
Login.jsp
<%@ page import="java.sql.*" %>
<% Class.forName("com.mysql.jdbc.Driver"); %>
<html>
<head> <title>The Publishers Database Table </title> </head>
<body>
<h1>The Publishers Database Table </h1>
<% Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/user1","root","
password"); Statement stmt = con.createStatement();
ResultSet resultset = stmt.executeQuery("select * from register") ; %>
<table border="1">
<tr>
<th>Name</th>
<th>Password</th>
<th>email</th>
<th>phone</th>
</tr>
<% while(resultset.next()){ %>
<tr>
<td> <%= resultset.getString(1) %></td>
<td> <%= resultset.getString(2) %></td>
<td> <%= resultset.getString(3) %></td>
<td> <%= resultset.getString(4) %></td>
</tr>
<% } %>
<% con.close(); %>
</table>
</body>
</html>

INSTALLING JSDK (JAVA SOFTWARE DEVELOPMENT KIT)

System Requirements
Software - Java 2 SDK Standard Edition, 1.4.2 is supported on i586 Intel and 100%
compatible platforms running Microsoft Windows. For a list of supported operating
systems and desktop managers.

Hardware - Intel and 100% compatible processors are supported. A Pentium 166MHz
or faster processor with at least 32 megabytes of physical RAM is required to run
graphically based applications. At least 48 megabytes of RAM is recommended for
applets running within a browser using the Java Plug-in. Running with less memory
may cause disk swapping which has a severe effect on performance. Very large
programs may require more RAM for adequate performance.

Installation Instructions

In this procedure, we will run the self-installing executable to unpack and install the
Java 2 SDK software bundle. As part of the Java 2 SDK, this installation includes the
Java Plug-in and Java Web Start, as well as an option to include the public Java 2
Runtime Environment. The Java 2 SDK also contains a private J2RE for use only by
its tools. For issues related to Windows Installation (IFTW) and Java Update, see the
Windows Installation (IFTW) and Java Update FAQ. After the Java 2 SDK software
has been installed, you may be asked to reboot your system.
<version> For example, if you are downloading the installer for update 1.4.2_01, the
following file name: j2sdk-1_4_2_<version>-windows-i586.exe would become: j2sdk-
1_4_2_01-windows-i586.exe
1. Check the download file size (Optional) If you save the self-installing
executable to disk without running it from the download page at the web site, notice that
its byte size is provided on the download page. Once the download has completed,
check that you have downloaded the full, uncorrupted software file.
2. If 1.4.2 Beta is installed, uninstall it. Use the Microsoft Windows
Add/Remove Programs utility, accessible from the Control Panel (Start ->
Settings -> Control Panel).
3. Run the Java 2 SDK installer Note - you must have administrative
permissions in order to install the Java 2 SDK on Microsoft Windows 2000 and XP.

Installed Directory Tree


The Java 2 SDK has the directory structure shown below.
j2sdk1.4.2_<version>
|
| | | | | | | ||
| | | | bin lib | demo |
| | | LICENSE | | | jre
| | COPYRIGHT | |
| README.txt include | |
readme.html bin lib

TOMCAT SERVER & TESTING TOMCAT

Downloading and installing tomcat


The steps of downloading and installing are easy and you can learn the process very fast.
Click the link: http://tomcat.apache.org/download-60.cgi and follow the steps according
to your requirement to achieve Tomcat server.
Step 1: Installation of JDK:
Before beginning the process of installing Tomcat on your system, ensure first the
availability of JDK on your system program directory. Install it on your system if not
already installed (because any version of tomcat requires the Java 1.6 or higher versions)
and then set the class path (environment variable) of JDK. To set the JAVA_HOME
Variable: you need to specify the location of the java run time environment to support the
Tomcat else Tomcat server can not run. This variable contains the path of JDK installation
directory.
set JAVA_HOME=C:\Program Files\Java\jdk1.6
Start menu->Control Panel->System->Advanced tab-Environment Variables->New->set the Variable name
= JAVA_HOME and variable value = C:\Program Files\Java\jdk1.6
For Windows OS, go through the following steps:
Now click on all the subsequent ok buttons one by one. It will set the JDK path.
Step 2:
For setting the class path variable for JDK, do like this:
Start menu->Control Panel->System->Advanced tab->Environment
Variables->New-> Set PATH="C:\Program Files\Java\jdk1.6\bin";
%PATH%
OR
First, right click on the
My Computer->properties->advance->Environment
Variables->path. Now, set bin directory path of JDK in the
path variable
Step 3:
The process of installing Tomcat 6.0 begins here from now. It takes various steps for
installing and configuring the Tomcat 6.0. For Windows OS, Tomcat comes in two
forms: .zip file and .exe file (the Windows installer file). Here we are exploring the
installation process by using the .exe file. First unpack the zipped file and simply execute
the '.exe' file.
A Welcome screen shot appears that shows the
beginning of installation process. Just click on
the 'Next' button to proceed the installation
process.

Steps 4:
A screen of 'License Agreement'
displays. Click on the 'I Agree'
button.
Step 5:
A screen shot appears asking for the 'installing
location' choose the default components and
click on the 'Next' button.

Step 6:
A screen shot of 'Configuration Options'
displays on the screen. Choose the location for
the Tomcat files as per your convenience. You
can also opt the default Location The port
number will be your choice on which you want
to run the tomcat server. The port number
8080 is the default port value for tomcat server
to proceed the HTTP requests. The user can
also change the 'port number' after completing
the process of installation; for this, users have
to follow the following tips. Go to the
specified location as " Tomcat 6.0 \conf \server.xml ". Within the server.xml file choose
"Connector" tag and change the port number. Now, click on the 'Next' button to further
proceed the installation process.

Step 7:
A Window of Java Virtual Machine
displays on the screen .This window
asks for the location of the installed
Java Virtual Machine. Browse the
location of the JRE folder and click on
the Install button. This will install the
Apache tomcat at the specified
location.

Step 8:
A processing window of installing
displays on the screen. To get the
information about installer click on
the "Show details" button
Step 9:
A screen shot of 'Tomcat Completion' displays on
the screen. Click on the 'Finish' button.

Step 10:
A window of Apache Service Manager appears with
displaying the running process. Let the running
process goes on.

Step 11:
After completing the installation process, the Apache Tomcat
Manager appears on the toolbar panel like shown in the picture.

Start the Tomcat Server:


1. Start the tomcat server from the bin folder of Tomcat 6.0 directory by double clicking
the "tomcat6.exe" file. OR create a shortcut of this .exe file at your desktop.
2. Now Open web browser and type URL http://localhost:8080 in the address bar to test the
server.
3. To Stop the Tomcat Server: Stop the server by pressing the "Ctrl + c" keys. The screen of
Apache Tomcat software looks like this:

You might also like