Page 1
JSP Tutorials - Writing First JSP
Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP
provide excellent server side scripting support for creating database driven web applications.
JSP enable the developers to directly insert java code into jsp file, this makes the development
process very simple and its maintenance also becomes very easy. JSP pages are efficient, it
loads into the web servers memory on receiving the request very first time and the subsequent
calls are served within a very short period of time.
In today's environment most web sites servers dynamic pages based on user request.
Database is very convenient way to store the data of users and other things. JDBC provide
excellent database connectivity in heterogeneous database environment. Using JSP and JDBC
its very easy to develop database driven web application.
Java is known for its characteristic of "write once, run anywhere." JSP pages are platform
independent. Your port your .jsp pages to any platform.
Installing JSP
First of all download JavaServer Web Development Kit
(JSWDK1.0.1) fromhttp://java.sun.com/products/servlet/download.html. JSWDK comes with full
documentation and it's very easy to install, so the installation process is not mentioned here.
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.
Other Servers that support JSP
Apache Tomcat.
Tomcat is the official reference implementation of the servlet 2.2 and JSP 1.1
Page 2
specifications. It can be used as a small stand-alone server for testing servlets and JSP
pages, or can be integrated into the Apache Web server.
Allaire JRun.
JRun is a servlet and JSP engine that can be plugged into Netscape Enterprise or
FastTrack servers, IIS, Microsoft Personal Web Server, older versions of Apache, O?
Reilly?s WebSite, or StarNine WebSTAR.
New Atlanta?s ServletExec.
ServletExec is a fast servlet and JSP engine that can be plugged into most popular Web
servers for Solaris, Windows, MacOS, HP-UX and Linux. You can download and use it
for free, but many of the advanced features and administration utilities are disabled until
you purchase a license.
Gefion's LiteWebServer (LWS). LWS is a small free Web server that supports servlets
version2.2 and JSP 1.1.
GNU JSP . free, open source engine that can be installed on apache web server.
PolyJSP . PolyJsp is based on XML/XSL and has been designed to be extensible. Now
supportsWebL
JRUN . Available for IIS server.
WebSphere . IBM's WebSphere very large application server now implements JSP.
Developing first JSP
Java Server Pages are save with .jsp extension. Following code which generates a simple html
page.
Execute the example. <html>
<head>
<title>First JSP page.</title>
</head>
<body>
<p align="center"><font color="#FF0000" size="6"><%="Java Developers
Page 3
Paradise"%></font></p>
<p align="center"><font color="#800000" size="6"><%="Hello JSP"%> </font></p>
</body>
</html>
In jsp java codes are written between '<%' and '%>' tags. So it takes the following form : <%=
Some Expression %> In this example we have use
<%="Java Developers Paradise"%>
Tutorials - Java Server Pages Technology
JavaServer Pages
JavaServer Pages (JSP) technology is the Java platform technology for delivering dynamic
content to web clients in a portable, secure and well-defined way. The JavaServer Pages
specification extends the Java Servlet API to provide web application developers with a robust
framework for creating dynamic web content on the server using HTML, and XML templates,
and Java code, which is secure, fast, and independent of server platforms. JSP has been built
on top of the Servlet API and utilizes Servlet semantics. JSP has become the preferred request
handler and response mechanism. Although JSP technology is going to be a powerful
successor to basic Servlets, they have an evolutionary relationship and can be used in a
cooperative and complementary manner.
Servlets are powerful and sometimes they are a bit cumbersome when it comes to generating
complex HTML. Most servlets contain a little code that handles application logic and a lot more
code that handles output formatting. This can make it difficult to separate and reuse portions of
the code when a different output format is needed. For these reasons, web application
developers turn towards JSP as their preferred servlet environment.
Page 4
Evolution of Web Applications
Over the last few years, web server applications have evolved from static to dynamic
applications. This evolution became necessary due to some deficiencies in earlier web site
design. For example, to put more of business processes on the web, whether in business-to-
consumer (B2C) or business-to-business (B2B) markets, conventional web site design
technologies are not enough. The main issues, every developer faces when developing web
applications, are:
1. Scalability - a successful site will have more users and as the number of users is increasing
fastly, the web applications have to scale correspondingly.
2. Integration of data and business logic - the web is just another way to conduct business, and
so it should be able to use the same middle-tier and data-access code.
3. Manageability - web sites just keep getting bigger and we need some viable mechanism to
manage the ever-increasing content and its interaction with business systems.
4. Personalization - adding a personal touch to the web page becomes an essential factor to
keep our customer coming back again. Knowing their preferences, allowing them to configure
the information they view, remembering their past transactions or frequent search keywords are
all important in providing feedback and interaction from what is otherwise a fairly one-sided
conversation.
Apart from these general needs for a business-oriented web site, the necessity for new
technologies to create robust, dynamic and compact server-side web applications has been
realized. The main characteristics of today's dynamic web server applications are as follows:
1. Serve HTML and XML, and stream data to the web client
2. Separate presentation, logic and data
3. Interface to databases, other Java applications, CORBA, directory and mail services
4. Make use of application server middleware to provide transactional support.
Page 5
5. Track client sessions
Now let us have a look on the role of Java technology and platform in this regard.
Java's Role for Server Applications
Sun Microsystems, having consulted many expert partners from other related IT industries, has
come out with a number of open APIs for the technologies and services on server side. This
collection of APIs is named as Java 2 Enterprise Edition (J2EE). The J2EE specification
provides a platform for enterprise applications, with full API support for enterprise code and
guarantees of portability between server implementations. Also it brings a clear division
between code which deals with presentation, business logic and data.
The J2EE specification meets the needs of web applications because it provides:
1. Rich interaction with a web server via servlets and built-in support for sessions available in
both servlets and EJBs.
2. The use of EJBs to mirror the user interaction with data by providing automatic session and
transaction support to EJBs operating in the EJB server.
3. Entity EJBs to represent data as an object and seamless integration with the Java data
access APIs
4. Flexible template-based output using JSP and XML
This family of APIs mean that the final web page can be generated from a user input request,
which was processed by a servlet or JSP and a session EJB, which represents the user's
session with the server, using data extracted from a database and put into an entity EJB. Thus,
the Java revolution of portable code and open APIs is married with an evolution in existing
products such as database, application, mail and web servers. The wide availability of products
to run Java applications on the server has made this a fast-moving and very competitive market,
but the essential compatibility through specifications, standard APIs and class libraries has held.
This makes server-side Java a very exciting area.
Page 6
JavaServer Pages - An Overview
The JavaServer Pages 1.2 specification provides web developers with a framework to build
applications containing dynamic web content such as HTML, DHTML, XHTML and XML. A JSP
page is a text based document containing static HTML and dynamic actions which describe how
to process a response to the client in a more powerful and flexible manner. Most of a JSP file is
plain HTML but it also has, interspersed with it, special JSP tags.
There are many JSP tags such as:
JSP directive denoted by <%@,
2. scriplets indicated by <% ... %> tags and
directive includes the contents of the file sample.html in the response at that point.
To process a JSP file, we need a JSP engine that can be connected with a web server or can
be accommodated inside a web server. Firstly when a web browser seeks a JSP file through an
URL from the web server, the web server recognizes the .jsp file extension in the URL
requested by the browser and understands that the requested resource is a JavaServer Page.
Then the web server passes the request to the JSP engine. The JSP page is then translated
into a Java class, which is then compiled into a servlet.
This translation and compilation phase occurs only when the JSP file is requested for the first
time, or if it undergoes any changes to the extent of getting retranslated and recompiled. For
each additional request of the JSP page thereafter, the request directly goes to the servlet byte
code, which is already in memory. Thus when a request comes for a servlet, an init() method is
called when the Servlet is first loaded into the virtual machine, to perform any global initialization
that every request of the servlet will need. Then the individual requests are sent to a service()
method, where the response is put together. The servlet creates a new thread to run service()
method for each request. The request from the browser is converted into a Java object of type
HttpServletRequest, which is passed to the Servlet along with an HttpServletResponse object
that is used to send the response back to the browser. The servlet code performs the operations
specified by the JSP elements in the .jsp file.
Page 7
The Components of JSPs
JSP syntax is almost similar to XML syntax. The following general rules are applicable to all JSP
tags.
1. Tags have either a start tag with optional attributes, an optional body, and a matching end tag
or they have an empty tag possibly with attributes.
2. Attribute values in the tag always appear quoted. The special strings ' and " can be
used if quotes are a part of the attribute value itself.
Any whitespace within the body text of a document is not significant, but is preserved, which
means that any whitespace in the JSP being translated is read and preserved during translation
into a servlet.
The character \ can be used as an escape character in a tag, for instance, to use the %
character, \% can be used.
JavaServer Pages are text files that combine standard HTML and new scripting tags. JSPs look
like HTML, but they get compiled into Java servlets the first time they are invoked. The resulting
servlet is a combination of HTML from the JSP file and embedded dynamic content specified by
the new tags. Everything in a JSP page can be divided into two categories:
1. Elements that are processed on the server
2. Template data or everything other than elements, that the engine processing the JSP
engines.
Element data or that part of the JSP which is processed on the server, can be classified into the
following categories:
1. Directives
2. Scripting elements
Page 8
3. Standard actions
JSP directives serve as messages to the JSP container from the JSP. They are used to set
global values such as class declaration, methods to be implemented, output content type, etc.
They do not produce any output to the client. All directives have scope of the entire JSP file.
That is, a directive affects the whole JSP file, and only that JSP file. Directives are characterized
by the @ character within the tag and the general syntax is:
The three directives are page, include and taglib.
Scripting elements are used to include scripting code (Java code) within the JSP. They allow to
declare variables and methods, include arbitrary scripting code and evaluate an expression. The
three types of scripting element are: Declaration, Scriptlets and Expressions.
A declaration is a block of Java code in a JSP that is used to define class-wide variables and
methods in the generated class file. Declarations are initialized when the JSP page is initialized
and have class scope. Anything defined in a declaration is available throughout the JSP, to
other declarations, expressions or code.
A scriptlet consists of one or more valid Java statements. A scriptlet is a block of Java code that
is executed at request-processing time. A scriptlet is enclosed between "<%" and "%>". What
the scriptlet actually does depends on the code, and it can produce output into the output
stream to the client. Multiple scriptlets are combined in the compiled class in the order in which
they appear in the JSP. Scriptlets like any other Java code block or method, can modify objects
inside them as a result of method invocations.
An expression is a shorthand notation for a scriptlet that outputs a value in the response stream
back to the client. When the expression is evaluated, the result is converted to a string and
displayed, An expression is enclosed within <%= and %> "<%=" and "%>". If any part of
expression is an object, the conversion is done using the toString() method of the object.
Standard actions are specific tags that affect the runtime behavior of the JSP and affect the
response sent back to the client. The JSP specification lists some standard action types to be
provided by all containers, irrespective of the implementation. Standard actions provide page
Page 9
authors with some basic functionality to exploit; the vendor is free to provide other actions to
enhance behavior.
How JSP and JSP Container function
A JSP page is executed in a JSP container or a JSP engine, which is installed in a web server
or in a application server. When a client asks for a JSP page the engine wraps up the request
and delivers it to the JSP page along with a response object. The JSP page processes the
request and modifies the response object to incorporate the communication with the client. The
container or the engine, on getting the response, wraps up the responses from the JSP page
and delivers it to the client. The underlying layer for a JSP is actually a servlet implementation.
The abstractions of the request and response are the same as the ServletRequest and
ServletResponse respectively. If the protocol used is HTTP, then the corresponding objects are
HttpServletRequest and HttpServletResponse.
The first time the engine intercepts a request for a JSP, it compiles this translation unit (the JSP
page and other dependent files) into a class file that implements the servlet protocol. If the
dependent files are other JSPs they are compiled into their own classes. The servlet class
generated at the end of the translation process must extend a superclass that is either
1. specified by the JSP author through the use of the extends attribute in the page directive or
2. is a JSP container specific implementation class that implements javax.servlet.jsp.JspPage
interface and provides some basic page specific behavior.
Since most JSP pages use HTTP, their implementation classes must actually implement the
javax.servlet.jsp.HttpJspPage interface, which is a sub interface of javax.servlet.jsp.JspPage.
The javax.servlet.jsp.JspPage interface contains two methods:
1. public void jspInit() - This method is invoked when the JSP is initialized and the page authors
are free to provide initialization of the JSP by implementing this method in their JSPs.
Page 10
2. public void jspDestroy() - This method is invoked when the JSP is about to be destroyed by
the container. Similar to above, page authors can provide their own implementation.
The javax.servlet.jsp.HttpJspPage interface contains one method:
public void _jspService(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
This method generated by the JSP container is invoked, every time a request comes to the JSP.
The request is processed and the JSP generates appropriate response. This response is taken
by the container and passed back to the client.
JSP Architecture
There are two basic ways of using the JSP technology. They are the client/server (page-centric)
2-tier approach and the N-tier approach (dispatcher).
The Page-Centric Approach
Applications built using a client-server (2-tier) approach consist of one or more application
programs running on client machines and connecting to a server-based application to work.
With the arrival of Servlets technology, 2-tier applications could also be developed using Java
programming language. This model allows JSPs or Servlets direct access to some resource
such as database or legacy application to service a client's request. The JSP page is where the
incoming request is intercepted, processed and the response sent back to the client. JSPs differ
from Servlets in this scenario by providing clean code, separating code from the content by
placing data access in EJBs. Even though this model makes application development easier, it
does not scale up well for a large number of simultaneous clients as it entails a significant
amount of request processing to be performed and each request must establish or share a
potentially scarce/expensive connection to the resource in question.
Page-view - This basic architecture involves direct request invocations to a server page with
embedded Java code, and markup tags which dynamically generate output for substitution
within the HTML. This approach has been blessed a number of benefits. It is very
Page 11
straightforward and is a low-overhead approach from a developerment perspective. All the Java
code may be embedded within the HTML, so changes are confined to a very limited area,
reducing complexity drastically.
The big trade-off here is in the level of sophistication. As the scale of the system grows, some
limitations begin to surface, such as bloating of business logic code in the page instead of
factoring forward to a mediating Servlet or factoring back to a worker bean. It is a fact that
utilizing a Servlet and helper beans helps to separate developer roles more cleanly and
improves the potential for code reuse.
Page-view with bean - This pattern is used when the above architecture becomes too cluttered
with business-related code and data access code. The Java code representing the business
logic and simple data storage implementation in the previous model moves from the JSP to the
JavaBean worker. This refactoring leaves a much cleaner JSP with limited Java code, which
can be comfortably owned by an individual in a web-production role, since it encapsulates
mostly markup tags.
The Dispatcher Approach
In this approach, a Servlet or JSP acts as a mediator or controller, delegating requests to JSP
pages and JavaBeans. There are three different architectures. They are mediator-view,
mediator-composite view and service to workers.
In an N-tier application, the server side of the architecture is broken up into multiple tiers. In this
case, the application is composed of multiple tiers, where the middle tier, the JSP, interacts with
the back end resources via another object or EJBs component. The Enterprise JavaBeans
server and the EJB provide managed access to resources, support transactions and access to
underlying security mechanisms, thus addressing the resource sharing and performance issues
of the 2-tier approach.
The first step in N-tiered application design should be identifying the correct objects and their
interaction and the second step is identifying the JSPs or Servlets. These are divided into two
categories.
Page 12
Front end JSPs or Servlets manage application flow and business logic evaluation. They act as
a point to intercept the HTTP requests coming from the users. They provide a single entry point
to an application, simplifying security management and making application state easier to
maintain.
Presentation JSPs or Servlets generate HTML or XML with their main purpose in life being
presentation of dynamic content. They contain only presentation and rendering logic.
These categories resemble to the Modal-View design pattern, where the front-end components
is the model and the presentation component the view. In this approach, JSPs are used to
generate the presentation layer and either JSPs or Servlets to perform process-intensive tasks.
The front-end component acts as the controller and is in charge of the request processing and
the creation of any beans or objects used by the presentation JSP, as well as deciding,
depending on the user's actions, which JSP to forward this request to. There is no processing
logic within the presentation JSP itself and it simply responsible for retrieving any objects or
beans that may have been previously created by the Servlet and extracting the dynamic content
for insertion within static templates.
Benefits of JSP
One of the main reasons why the JavaServer Pages technology has evolved into what it is
today and it is still evolving is the overwhelming technical need to simplify application design by
separating dynamic content from static template display data. Another benefit of utilizing JSP is
that it allows to more cleanly separate the roles of web application/HTML designer from a
software developer. The JSP technology is blessed with a number of exciting benefits, which
are chronicled as follows:
1. The JSP technology is platform independent, in its dynamic web pages, its web servers, and
its underlying server components. That is, JSP pages perform perfectly without any hassle on
any platform, run on any web server, and web-enabled application server. The JSP pages can
be accessed from any web server.
2. The JSP technology emphasizes the use of reusable components. These components can be
combined or manipulated towards developing more purposeful components and page design.
Page 13
This definitely reduces development time apart from the At development time, JSPs are very
different from Servlets, however, they are precompiled into Servlets at run time and executed by
a JSP engine which is installed on a Web-enabled application server such as BEA WebLogic
and IBM WebSphere.
Conclusion
JSP and Servlets are gaining rapid acceptance as means to provide dynamic content on the
Internet. With full access to the Java platform, running from the server in a secure manner, the
application possibilities are almost limitless. When JSPs are used with Enterprise JavaBeans
technology, e-commerce and database resources can be further enhanced to meet an
enterprise's needs for web applications providing secure transactions in an open platform. J2EE
technology as a whole makes it easy to develop, deploy and use web server applications
instead of mingling with other technologies such as CGI and ASP. There are many tools for
facilitating quick web software development and to easily convert existing server-side
technologies to JSP and Servlets.
Many application server vendors are aggressively deploying JSP within their products. This
results in developing robust e-commerce applications as JSP provides XML functionality and
scalability. By providing a clear separation between content and coding, JSP solves many
problems attached with existing server-side applications.
JSP ARCHITECTURE
JSP pages are high level extension of servlet and it enable the developers to embed java
code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled
servlet is used by the engine to serve the requests.
Page 14
javax.servlet.jsp package defines two interfaces:
JSPPage
HttpJspPage
These interfaces defines the three methods for the compiled JSP page. These methods are:
jspInit()
jspDestroy()
_jspService(HttpServletRequest request,HttpServletResponse response)
In the compiled JSP file these methods are present. Programmer can
define jspInit() and jspDestroy()methods, but the _jspService(HttpServletRequest
request,HttpServletResponse response) method is generated by the JSP engine.
JSP Actions
In this section we will explain you about JSP Action tags and in the next section we will explain the uses
of these tags with examples. We will also show how to use JSP Action Tags in the JSP application.
What is JSP Actions?
Servlet container provides many built in functionality to ease the development of the applications.
Programmers can use these functions in JSP applications. The JSP Actions tags enables the
programmer to use these functions. The JSP Actions are XML tags that can be used in the JSP page.
Here is the list of JSP Actions:
jsp:include
The jsp:include action work as a subroutine, the Java servlet temporarily passes the request and
Page 15
response to the specified JSP/Servlet. Control is then returned back to the current JSP page.
jsp:param
The jsp:param action is used to add the specific parameter to current request. The jsp:param tag
can be used inside a jsp:include, jsp:forward or jsp:params block.
jsp:forward
The jsp:forward tag is used to hand off the request and response to another JSP or servlet. In
this case the request never return to the calling JSP page.
jsp:plugin
In older versions of Netscape Navigator and Internet Explorer; different tags is used to embed
applet. The jsp:plugin tag actually generates the appropriate HTML code the embed the Applets
correctly.
jsp:fallback
The jsp:fallback tag is used to specify the message to be shown on the browser if applets is not
supported by browser.
Example:
<jsp:fallback>
<p>Unable to load applet</p>
</jsp:fallback>
jsp:getProperty
The jsp:getPropertyB is used to get specified property from the JavaBean object.
jsp:setProperty
The jsp:setProperty tag is used to set a property in the JavaBean object.
jsp:useBean
The jsp:useBean tag is used to instantiate an object of Java Bean or it can re-use existing java
bean object.
In the next sections we will learn how to use these JSP Actions (JSP Action tags).
Page 16
INTRODUCTION TO JSP TAGS
In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags
can be devided into 4 different types. These are:
1. Directives
In the directives we can import packages, define error handling pages or the session information
of the JSP page.
2. Declarations
This tag is used for defining the functions and variables to be used in the JSP.
3. Scriplets
In this tag we can insert any amount of valid java code and these codes are placed in
_jspServicemethod by the JSP engine.
4. Expressions
We can use this tag to output any data on the generated page. These data are automatically
converted to string and printed on the output stream.
Now we will examine each tags in details with examples. DIRECTIVES
Syntax of JSP directives is:
<%@directive attribute="value" %>
Where directive may be:
1. page: page is used to provide the information about it.
Example: <%@page language="java" %>
Page 17
2. include: include is used to include a file in the JSP page.
Example: <%@ include file="/header.jsp" %>
3. taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined
our own tags).
Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
and attribute may be:
1. language="java"
This tells the server that the page is using the java language. Current JSP specification supports
only java language.
Example: <%@page language="java" %>
2. extends="mypackage.myclass"
This attribute is used when we want to extend any class. We can use comma(,) to import more
than one packages.
Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %>
3. session="true"
When this value is true session data is available to the JSP page otherwise not. By default this
value is true.
Example: <%@page language="java" session="true" %>
4. errorPage="error.jsp"
errorPage is used to handle the un-handled exceptions in the page.
Example: <%@page language="java" session="true" errorPage="error.jsp" %>
5. contentType="text/html;charset=ISO-8859-1"
Use this attribute to set the mime type and character set of the JSP.
Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-
1" %>
Page 18
INTRODUCTION TO JSP DECLARATIVES
Syntax of JSP Declaratives are:
<%!
//java codes
%>
JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP
Declaratives. Variables and functions defined in the declaratives are class level and can be used
anywhere in the JSP page. Example:
<%@page contentType="text/html" %>
<html>
<body>
<%!int cnt=0;private int getCount(){//increment cnt and return the valuecnt++;return cnt;}%>
<p>Values of Cnt are:</p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
<p><%=getCount()%></p>
</body>
</html>
Page 19
The above example prints the value of variable cnt.
To execute the code click below.
INTRODUCTION TO JSP SCRIPTLETS
Syntax of JSP Scriptles are:
<%
//java codes
%>
JSP Scriptlets begins with <% and ends %> .We can embed any amount of java code in the JSP
Scriptlets. JSP Engine places these code in the _jspService() method. Variables available to the JSP
Scriptlets are:
request:
request represents the clients request and is a subclass of HttpServletRequest. Use this variable
to retrieve the data submitted along the request.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
response:
response is subclass of HttpServletResponse.
session:
session represents the HTTP session object associated with the request.
out:
out is an object of output stream and is used to send any output to the client.
Other variable available to the scriptlets are pageContext, application,config and exception.
Page 20
INTRODUCTION TO JSP EXPRESSIONS
Syntax of JSP Expressions are:
<%="Any thing" %>
JSP Expressions start with
Syntax of JSP Scriptles are with <%= and ends with %>. Between these this you can put anything and
that will converted to the String and that will be displayed.
Example:
<%="Hello World!" %>
Above code will display 'Hello World!'.
JSP date example
Till now you learned about the JSP syntax, now I will show you how to create a simple dynamic JSP page
that prints the current date and time. So the following code accomplish this:
Page 21
<%@page contentType="text/html" import="java.util.*" %>
<!--
http://www.roseindia.net/jsp
-->
<html><body><p> </p><div align="center"><center><table border="0" cellpadding="0" cellspacing="0" width="460" bgcolor="#EEFFCA">
<tr><td width="100%"><font size="6" color="#008000"> Date Example</font></td>
</tr><tr><td width="100%"><b> Current Date and time is: <font color="#FF0000">
<%= new java.util.Date() %></font></b></td></tr></table></center></div></body></html>
The heart of this example is Date() function of the java.util package which returns the current data and
time.
In the JSP Declaratives
<%@page contentType="text/html" import="java.util.*" %>
we are importing the java.util package and following JSP Expression code
Page 22
<%= new java.util.Date() %>
prints the current date on the page.
Execute the example.
Download the code
Reading Request Information
When an HTTP client such as web browser sends a request to a wen server, along with the request it
also sends some HTTP variables like Remote address, Remote host, Content type etc. In some cases
these variables are useful to the programmers. So here is the code of the jsp file which prints the HTTP
request information:
<%@page contentType="text/html" import="java.util.*" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p><font size="5" color="#800000">Request Information:</font></p>
<div align="left">
<table border="0" cellpadding="0" cellspacing="0" width="70%" bgcolor="#EEFFCA">
<tr>
<td width="33%"><b><font color="#800000">Request
Page 23
Method:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getMethod()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request URI:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRequestURI()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Request Protocol:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getProtocol()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path Info:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathInfo()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Path translated:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getPathTranslated()%></font></td>
Page 24
</tr>
<tr>
<td width="33%"><b><font color="#800000">Query String:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getQueryString()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content length:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentLength()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Content type:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getContentType()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server name:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerName()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Server
Page 25
port:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getServerPort()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote user:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteUser()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote address:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteAddr()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Remote host:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getRemoteHost()%></font></td>
</tr>
<tr>
<td width="33%"><b><font color="#800000">Authorization scheme:</font></b></td>
<td width="67%"><font color="#FF0000"><%=request.getAuthType()%></font></td>
Page 26
</tr>
</table>
</div>
</body>
</html>
Execute the example.
Download the code
Retrieving the data posted to a JSP file from HTML file
Now I will show you how to retrieve the data posted from a HTML file in a JSP page. Consider an html
page that prompts the user to enter his/her name, let's call it getname.htm. Here is the code of the html
file:
<html><head><title>Enter your name</title></head><body><p> </p><form method="POST" action="showname.jsp">
<p><font color="#800000" size="5">Enter your name:</font><input type="text" name="username" size="20"></p>
Page 27
<p><input type="submit" value="Submit"name="B1"></p></form></body></html>
The target of form is "showname.jsp", which displays the name entered by the user. To retrieve the value
entered by the user we uses the
request.getParameter("username");
code.
Here is the code of "showname.jsp" file:
<%@pagecontentType="text/html" %>
<!--
http://www.roseindia.net/jsp
-->
<html>
<body>
<p><font size="6">Welcome : <%=request.getParameter("username")%></font></p>
</body>
</html>
Execute the example.
Page 28
Download the code
Accessing database from JSP
Introduction
In This article I am going to discuss the connectivity from MYSQL database with JSP.we take a example
of Books database. This database contains a table named books_details. This table contains three
fields- id, book_name& author. we starts from very beginning. First we learn how to create tables in
MySQl database after that we write a html page for inserting the values in 'books_details' table in
database. After submitting values a table will be showed that contains the book name and author name.
Database
The database in example consists of a single table of three columns or fields. The database name is
"books" and it contains information about books names & authors.
Table:books_details
ID Book Name Author
1. Java I/O Tim Ritchey
2. Java & XML,2 Edition
Brett McLaughlin
3. Java Swing, 2nd Edition
Dave Wood, Marc Loy,
Start MYSQL prompt and type this SQL statement & press Enter-
MYSQL>CREATE DATABASE `books` ;
This will create "books" database.
Now we create table a table "books_details" in database "books".
Page 29
MYSQL>CREATE TABLE `books_details` (
`id` INT( 11 ) NOT NULL AUTO_INCREMENT ,
`book_name` VARCHAR( 100 ) NOT NULL ,
`author` VARCHAR( 100 ) NOT NULL ,
PRIMARY KEY ( `id` )
) TYPE = MYISAM ;
This will create a table "books_details" in database "books"
JSP Code
The following code contains html for user interface & the JSP backend-
<%@ page language="java" import="java.sql.*" %><%
String driver = "org.gjt.mm.mysql.Driver";Class.forName(driver).newInstance();
Connection con=null;ResultSet rst=null;Statement stmt=null;
try{String
url="jdbc:mysql://localhost/books?user=<user>&password=<password>";
con=DriverManager.getConnection(url);stmt=con.createStatement();
}catch(Exception e){
System.out.println(e.getMessage());}if(request.getParameter("action") != null){
String bookname=request.getParameter("bookname");
String author=request.getParameter("author");
stmt.executeUpdate("insert into books_details(book_name,author) values('"+bookname+"','"+author+"')");
rst=stmt.executeQuery("select * from books_details");
%><html><body><center>
<h2>Books List</h2><table border="1"
Page 30
cellspacing="0" cellpadding="0">
<tr><td><b>S.No</b></td><td><b>Book
Name</b></td>
<td><b>Author</.b></td></tr> <%
int no=1;while(rst.next()){%><tr> <td><%=no%></td> <td><
%=rst.getString("book_name")%></td>
<td> <%=rst.getString("author")%> </td>
</tr><%no++;
}rst.close();stmt.close();con.close();
%></table></center>
</body></html>
<%}else{%><html><head>
<title>Book Entry FormDocument</title><script language="javascript"> function validate(objForm){
if(objForm.bookname.value.length==0){alert("Please enter Book
Name!");objForm.bookname.focus();return false;}
if(objForm.author.value.length==0){alert("Please enter Author
name!");objForm.author.focus();return false;}return true;
}</script>
Page 31
</head>
<body><center>
<form action="BookEntryForm.jsp" method="post" name="entry" onSubmit="return validate(this)">
<input type="hidden" value="list" name="action">
<table border="1" cellpadding="0" cellspacing="0">
<tr><td>
<table><tr><td colspan="2"
align="center"><h2>Book Entry Form</h2></td>
</tr><tr><td
colspan="2"> </td></tr><tr><td>Book Name:</td><td><input
name="bookname" type="text" size="50"></td>
</tr><tr>
<td>Author:</td><td><input name="author" type="text" size="50"></td>
</tr><tr>
<td colspan="2" align="center"><input type="submit" value="Submit"></td>
</tr></table>
</td></tr>
</table></form>
</center></body>
</html><%}%>
Now we explain the above codes.
Page 32
Declaring Variables: Java is a strongly typed language which means, that variables must be explicitly
declared before use and must be declared with the correct data types. In the above example code we
declare some variables for making connection. Theses variables are-
Connection con=null;
ResultSet rst=null;
Statement stmt=null;
The objects of type Connection, ResultSet and Statement are associated with the Java sql. "con"
is a Connection type object variable that will hold Connection type object. "rst" is a ResultSet type object
variable that will hold a result set returned by a database query. "stmt" is a object variable of
Statement .Statement Class methods allow to execute any query.
Connection to database: The first task of this programmer is to load database driver. This is achieved
using the single line of code :-
String driver = "org.gjt.mm.mysql.Driver";
Class.forName(driver).newInstance();
The next task is to make a connection. This is done using the single line of code :-
String url="jdbc:mysql://localhost/books?user=<userName>&password=<password>";
con=DriverManager.getConnection(url);
When url is passed into getConnection() method of DriverManager class it returns connection object.
Executing Query or Accessing data from database:
This is done using following code :-
stmt=con.createStatement(); //create a Statement object
rst=stmt.executeQuery("select * from books_details");
stmt is the Statement type variable name and rst is the RecordSet type variable. A query is always
executed on a Statement object.
A Statement object is created by calling createStatement() method on connection object con.
Page 33
The two most important methods of this Statement interface are executeQuery() and executeUpdate().
The executeQuery() method executes an SQL statement that returns a single ResultSet object. The
executeUpdate() method executes an insert, update, and delete SQL statement. The method returns the
number of records affected by the SQL statement execution.
After creating a Statement ,a method executeQuery() or executeUpdate() is called on Statement
objectstmt and a SQL query string is passed in method executeQuery() or executeUpdate().
This will return a ResultSet rst related to the query string.
Reading values from a ResultSet:
while(rst.next()){
%>
<tr><td><%=no%></td><td><%=rst.getString("book_name")%></td><td><%=rst.getString("author")
%></td></tr>
<%
}
The ResultSet represents a table-like database result set. A ResultSet object maintains a cursor
pointing to its current row of data. Initially, the cursor is positioned before the first row. Therefore, to
access the first row in the ResultSet, you use the next() method. This method moves the cursor to
the next record and returns true if the next row is valid, and false if there are no more records in
theResultSet object.
Other important methods are getXXX() methods, where XXX is the data type returned by the method at
the specified index, including String, long, and int. The indexing used is 1-based. For example, to
obtain the second column of type String, you use the following code:
resultSet.getString(2);
You can also use the getXXX() methods that accept a column name instead of a column index. For
instance, the following code retrieves the value of the column LastName of type String.
Page 34
resultSet.getString("book_name");
The above example shows how you can use the next() method as well as the getString()method.
Here you retrieve the 'book_name' and 'author' columns from a table called 'books_details'. You then
iterate through the returned ResultSet and print all the book name and author name in the format "
book name | author " to the web page.
Summary:
This article presents JDBC and shows how you can manipulate data in a relational database from your
JSP page. To do this, you need to use the java.sql
package: DriverManager, Connection,Statement, and ResultSet. Keep in mind, however, that
this is only an introduction. To create a Web application, you need JDBC to use more features such as
prepared statements and connection pooling.
To Download Example click here
When you click on the above link a Book Entry Form will open
Fill the book name and author fields and press Submit button. A page will open and show a table of book
name and authors like...
Page 35
Implement JavaScript with JSP
In this section we are going to implement insert data, delete data, and update data using with JDBC
database and also using of JavaScript.
Step 1: Create employee form (EmployeeInformation.jsp) .
In this step first of all create Employee information form and retrieved employee id from database using
with JDBC database.
Here is the code EmployeeInformation.jsp
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<html><body border="1" bgcolor="pink" width="650"><%Connection con = null;String url =
Page 36
"jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);Statement stmt=null;%>
<form method="GET" ACTION="ProcessAction.jsp"><h3> <P ALIGN="CENTER"> <FONT SIZE=5> EMPLOYEE INFORMATION </FONT> </P> </h3> </br> </br><br><br><table callspacing=5 cellpadding=5 bgcolor="lightblue" colspan=2 rowspan=2 align="center"><tr><td> <font size=5> Enter Employee ID </td><td> <input type="TEXT" ID="id" name="empid"> </font> <select name="empIds" onchange="document.getElementById('id').value=this.options[this.selectedIndex].text"> <option>Select One</option><%String rec="SELECT empid,empname FROM Employee ORDER BY empid";try {stmt=con.createStatement();ResultSet rs=stmt.executeQuery(rec);while(rs.next()){%><option><%= rs.getInt(1)%></option><%}}catch(Exception e){System.out.println(e);}%>
Page 37
</select></font> </td></tr><tr><td> <font size=5> Enter Employee Name </td><td><input type="text" name="empname"> </font> </td></tr><tr> <font size=5> <B><td><input type="RADIO" name="r1" VALUE="add" >Insert </td></tr><tr><td><input type="RADIO" name="r1" VALUE="del" >Delete </td></tr><tr><td><input type="RADIO" name="r1" VALUE="mod" >Modify </td></tr></font> </b><tr> <td><input type="SUBMIT" VALUE="Submit"> <input type="RESET" value="Reset"> </TD></tr></body></html>
Step 2 : Create "ProcessAction.jsp" for Process the Data and forward according to user
requirement.
In this step first of all we will create ProcessAction.jsp for getting all string value using
withgetParameter() method and forward on different page like JSPInsertAction.jsp, ClearAction.jsp, and
update.jsp.
<%@ page language="java" %><%@ page import="java.lang.*" %><%@ page import="java.sql.*" %><%String str=request.getParameter("r1");String name=request.getParameter("empname");String code=request.getParameter("empid");
Page 38
if(str.equals("add")) {%><jsp:forward page="JSPInsertAction.jsp"/>
<%}else if(str.equals("del")) {%><jsp:forward page="ClearAction.jsp" /><%}else if(str.equals("mod")) {%><jsp:forward page="update.jsp" /><%}else {%><jsp:forward page="Noresponse.html" /><%}%>
Step 3: Create data insert action page ("JSPInsertAction.jsp").
This code using for insert data into database by using JDBC database. When you will select same
employee id and employee name then massage will display employee id already exit in database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<HTML><BODY><FORM NAME="f1" ACTION="EmplyeeInformation.jsp"><%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
String str=request.getParameter("r1");
Page 39
String empname=request.getParameter("empname");String code=request.getParameter("empid");int ent=0;String failed="";try{String click="SELECT COUNT(*) FROM Employee WHERE empid='"+code+"' and empname='"+empname+"'";Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);Statement stmt=null;stmt=con.createStatement();ResultSet ok = stmt.executeQuery(click);while(ok.next()) {ent=ok.getInt(1);}if(ent==0) {String insertQry = "insert Employee values('"+code+"','"+empname+"')"; int val = stmt.executeUpdate(insertQry);
%><script language="javascript">alert("Insertion successful");document.location="EmplyeeInformation.jsp";</script><%}if(ent==1) {%><script language="javascript">alert("This Emp ID already Exists");document.location="EmplyeeInformation.jsp";</script><%}stmt.close();con.close();}catch(Exception e) {out.println(e.toString());}%></FORM></BODY></HTML>
Page 40
Step 4: Create data deletion code from database ("ClearAction.jsp").
In this step you will learn how to delete data from database. When, you will select employee id and
employee name then select delete radio button after selecting delete radio button when you will click on
submit button then data will successfully delete from database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
String str=request.getParameter("r1");String name=request.getParameter("empname");String code=request.getParameter("empid");int EmpID=Integer.parseInt(code);try {Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);String sql = "delete from Employee where empid= ?";PreparedStatement stmt=null;stmt=con.prepareStatement(sql);stmt.setInt(1,EmpID);int erase=stmt.executeUpdate();if(erase==0) { %><script language="javascript">alert("Deletion successful");</script><%}if(erase==1) { %><script language="javascript">alert("Deletion successful");</script><%}
stmt.close();con.close();out.println("Data delete successfully from database.");
Page 41
}catch(Exception e) {out.println(e);}%>
Step 5: Create update data code ("update.jsp").
In this step you will learn, how to modify data in database by using JDBC database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<HTML><BODY><%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
String rep=request.getParameter("empname");String code=(String)request.getParameter("empid");int ID=Integer.parseInt(code);try {Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);String rec="UPDATE Employee SET empname='"+rep+"' where empid='"+ID+"'";
Statement stmt=null;stmt=con.createStatement();int mod=stmt.executeUpdate(rec);if(mod==0) { %><script language="javascript">alert("This Emp ID already Exists");</script><%}if(mod==1) { %><script language="javascript">alert("Record Updated Successfully");
Page 42
</script><%}con.commit();stmt.close();con.close();
}catch(Exception e) { %><script language="javascript">alert("Please Enter New Name");document.location="EmplyeeInformation.jsp";</script><%}
%></BODY></HTML>
Here is the output of this program:
When you will enter new employee id and employee name and select insert button after selecting insert
button click on submit button then data will insert successfully in database.
Page 43
If you will select same employee id then massage will display like this.
Page 45
If you want to modify record then select employee id and enter new employee name. When you will select
modify radio button then click on submit button then massage will display like this.
Working with sessions
This JSP Tutorial shows you how to track the session between different JSP pages. In any web
application user moves from one page to another and it becomes necessary to track the user data and
objects throughout the application. JSP provide an implicit object "session", which can be use to save the
data specific the particular to the user.
Page 46
In this tutorial we will create an application that takes the user name from the user and then saves into the
user session. We will display the saved data to the user in another page.
Here is the code of the JSP file (savenameform.jsp) that takes the input from user:
<%@ page language="java" %><html><head><title>Name Input Form</title></head><body><form method="post" action="savenametosession.jsp"><p><b>Enter Your Name: </b><input type="text" name="username"><br><input type="submit" value="Submit">
</form>
</body>
The above page prompts the user to enter his/her name. Once the user clicks on the submit button,
savenametosession.jsp is called. The JSP savenametosession.jsp retrieves the user name from request
attributes and saves into the user session using the functionsession.setAttribute("username",username);.
Here is the code of savenametosession.jsp:
<%@ page language="java" %><%String username=request.getParameter("username");if(username==null) username="";
session.setAttribute("username",username);%>
<html><head><title>Name Saved</title></head><body><p><a href="showsessionvalue.jsp">Next Page to view the session value</a><p>
</body>
Page 47
The above JSP saves the user name into the session object and displays a link to next pages
(showsessionvalue.jsp). When user clicks on the "Next Page to view session value" link, the JSP
pageshowsessionvalue.jsp displays the user name to the user. Here is the code of showsessionvalue.jsp:
<%@ page language="java" %><%String username=(String) session.getAttribute("username");if(username==null) username="";%><html><head><title>Show Saved Name</title></head><body><p>Welcome: <%=username%><p>
</body>
The function session.getAttribute("username") is used to retrieve the user name saved in the session.
JSP Cookies Example
This tutorial shows how to handle cookies in JSP pages. In this tutorial you will learn how to add cookies
through jsp page and then show the value of the same cookie in another JSP page.
Let's understand the cookies. Cookies are short pieces of data sent by web servers to the client browser.
The cookies are saved to clients hard disk in the form of small text file. Cookies helps the web servers to
identify web users, by this way server tracks the user. Cookies pay very important role in the session
tracking.
Cookie Class
In JSP cookie are the object of the class javax.servlet.http.Cookie. This class is used to creates a
cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later
sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for
Page 48
session management. A cookie has a name, a single value, and optional attributes such as a comment,
path and domain qualifiers, a maximum age, and a version number.
The getCookies() method of the request object returns an array of Cookie objects. Cookies can be
constructed using the following code:
Cookie(java.lang.String name, java.lang.String value)
Cookie objects have the following methods.
Method Description
getComment()Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.
getMaxAge() Returns the maximum specified age of the cookie.
getName() Returns the name of the cookie.
getPath() Returns the prefix of all URLs for which this cookie is targeted.
getValue() Returns the value of the cookie.
setComment(String)If a web browser presents this cookie to a user, the cookie's purpose will be described using this comment.
setMaxAge(int)
Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behavior: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted
setPath(String)This cookie should be presented only with requests beginning with this URL.
setValue(String)
Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the "at" sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.
Example Using Cookies
No we will write code in JSP file to set and then display the cookie.
Create Form
Here is the code of the form (cookieform.jsp) which prompts the user to enter his/her name.
<%@ page language="java" %>
Page 49
<html><head><title>Cookie Input Form</title></head><body><form method="post" action="setcookie.jsp"><p><b>Enter Your Name: </b><input type="text" name="username"><br><input type="submit" value="Submit">
</form>
</body>
Above form prompts the user to enter the user name. User input are posted to the setcookie.jsp file,
which sets the cookie. Here is the code of setcookie.jsp file:
<%@ page language="java" import="java.util.*"%><%String username=request.getParameter("username");if(username==null) username="";
Date now = new Date();String timestamp = now.toString();Cookie cookie = new Cookie ("username",username);cookie.setMaxAge(365 * 24 * 60 * 60);response.addCookie(cookie);
%>
<html><head><title>Cookie Saved</title></head><body><p><a href="showcookievalue.jsp">Next Page to view the cookie value</a><p>
</body>
Above code sets the cookie and then displays a link to view cookie page. Here is the code of display
cookie page (showcookievalue.jsp):
<%@ page language="java" %><%
Page 50
String cookieName = "username";Cookie cookies [] = request.getCookies ();Cookie myCookie = null;if (cookies != null){for (int i = 0; i < cookies.length; i++) {if (cookies [i].getName().equals (cookieName)){myCookie = cookies[i];break;}}}%><html><head><title>Show Saved Cookie</title></head><body>
<%if (myCookie == null) {%>No Cookie found with the name <%=cookieName%><%} else {%> <p>Welcome: <%=myCookie.getValue()%>.<%}%></body>
When user navigates to the above the page, cookie value is displayed.
Cookie Example to Store and Show only 10 values
Page 51
Example program to show last 10 Cookies value
This cookie example illustrates how you can manage cookie value in your JSP page. This example is
saving and displaying cookies and also it is managing cookies size in such manner that if cookie size
becomes greater than a limit (e.g 10 in this case), it will automatically deletes the oldest cookie from the
list. Cookies age can be set using the following code:
setMaxAge(365*24*60*60)
User can add new cookie by entering the cookie name and value from the JSP page. On the form submit
event user input will be added into cookie array by the following method:
response.addCookie(<cookie name>)
We are managing cookies by the cookie age. If the cookie ages is set to zero then it will be deleted. We
are using the MaxAge property of the cookie to delete the cookie. To delete any cookie you can set its
MaxAge to zero e.g. MaxAge="0".
<% if(cookies.length >=10) { int start=cookies.length-10; cookies[start].setMaxAge(0); response.addCookie(cookies[start]); }%>
Full JSP code is given as below:
1. CookieHandling.jsp
<%@ page import="java.util.*" %><%
Page 52
Cookie[] cookies = request.getCookies(); if (cookies == null) cookies = new Cookie[0]; String name = request.getParameter("name"); Cookie added = null; if (name!=null && name.length()>0) { added = new Cookie(name,name); response.addCookie(added); added.setMaxAge(365*24*60*60); }%><HTML><HEAD><TITLE>Cookie List</TITLE></HEAD><BODY><% for (int i=0; i<cookies.length-1; i++) { out.println("Cookie Value Number :"+i+" and value "+cookies[i].getName()); out.println("<br>"); if (added!=null && added.getName().equals(cookies[i].getName())) added = null; } if (added != null) out.println("New Symbol: "+added.getName());%>
<% if(cookies.length >=10) { int start=cookies.length-10; cookies[start].setMaxAge(0); response.addCookie(cookies[start]); } out.println("Length of cookie is "+cookies.length);%>
<FORM><P>Get Cookie Value<INPUT TYPE='TEXT' NAME='name'></P><INPUT TYPE='SUBMIT' VALUE='Submit'>
Page 53
</FORM></BODY></HTML>
Output:
First time when JSP page would run then it looks like that
As and when we store new values in cookie it will add till 10 values
as soon as we will add 11th value then first will be deleted.
this value will be deleted from the JSP page.
Page 54
Download Source Code
Disabling Session in JSP
In this tutorial you will learn how to disable session creation in the JSP pages. Disabling the session in
some pages will improve the performance of your JSP container.
Every time a JSP is requested, JSP creates an HttpSession object to maintain state for each unique
client. The session data is accessible in the JSP as the implicit session object. In JSPs, sessions are
enabled by default.
Session object uses the server resources. Each session object uses up a small amount of system
resources as it is stored on the server side. This also increases the traffic as the session ID is sent from
server to client. Client also sends the same session ID along with each request. If some of the JSP pages
on your web site are getting thousands of hits from internet browser and there is not need to identify the
user, so its better to disable the session in that JSP page.
You can tell the container to disable session in the JSP file by setting the session attribute to false. Set
Page 55
the session attribute of the page directive to false, as shown in the following example:
<%@ page session="false" %>
Here is the full code of jsp file in which session is disabled:
<%@ page language="java" session="false"%><html><head><title>Session Disabled</title></head><body><p>Session is Disabled in this page</body></html>
JSP PDF books
Collection is jsp books in the pdf format. You can download these books and study it offline.
1. The Servlets and JavaServer pages
Servlets are Java technology?s answer to Common Gateway Interface (CGI) programming. They
are programs that run on a Web server, acting as a middle layer between a request coming from
a Web browser or other HTTP client and databases or applications on the HTTP server. Their job
is to:-
* Read any data sent by the user:-This data is usually entered in a form on a Web page, but could
also come from a Java applet or a custom HTTP client program.
* Look up any other information about the request that is embedded in the HTTP request :- This
information includes details about browser capabilities, cookies, the host name of the requesting
client, and so forth.
2. The First Servlets
The previous chapter showed you how to install the software you need and how to set up your
Page 56
development environment. Now you want to really write a few servlets. Good. This chapter shows
you how, outlining the structure that almost all servlets follow, walking you through the steps
required to compile and execute a servlet, and giving details on how servlets are initialized and
when the various methods are called. A browser generates this request when the user types a
URL on the address line, follows a link from a Web page, or submits an HTML form that does not
specify a METHOD. Servlets can also very easily handle POST requests, which are generated
when someone submits an HTML form that specifies METHOD="POST".
3. JSP Scripting Elements
JavaServer Pages (JSP) technology enables you to mix regular, static HTML with dynamically
generated content from servlets. You simply write the regular HTML in the normal manner, using
familiar Web-page-building tools. 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 such as ASP, PHP, or ColdFusion. Section 1.4
gives some details on these advantages, but they basically boil down to two facts: that JSP is
widely supported and thus doesn?t lock you into a particular operating system or Web server and
that JSP gives you full access to servlet and Java technology for the dynamic part, rather than
requiring you to use an unfamiliar and weaker special-purpose language.
4. The Developing XML solutions with JSP Technology
XML is a set of syntax rules and guidelines for defining text-based markup languages. XML
languages have a number of uses including: * Exchanging information * Defining document types
* Specifying messages Information that is expressed in a structured, text-based format can easily
be transmitted between, transformed, and interpreted by entities that understand the structure. In
this way XML brings the same cross-platform benefits to information exchange as the JavaTM
programming language has for processing. JavaServer PagesTM (JSPTM) technology provides
specification and serving of documents that combine static markup language elements and
elements created dynamically by Java programming language objects.
5. JSP Tag Libraries
JSP 1.1 introduced an extremely valuable new capability: the ability to define your own JSP tags.
You define how the tag, its attributes, and its body are interpreted, then group your tags into
collections called tag libraries that can be used in any number of JSP files. The ability to define
tag libraries in this way permits Java developers to boil down complex server-side behaviors into
simple and easy-to-use elements that content developers can easily incorporate into their JSP
pages. Custom tags accomplish some of the same goals as beans that are accessed with
Page 57
jsp:useBean - encapsulating complex behaviors into simple and accessible forms. There are
several differences, however. First, beans cannot manipulate JSP content; custom tags can.
Second, complex operations can be reduced to a significantly simpler form with custom tags than
with beans. Third, custom tags require quite a bit more work to set up than do beans. Fourth,
beans are often defined in one servlet and then used in a different servlet or JSP page whereas
custom tags usually define more self-contained behavior. Finally, custom tags are available only
in JSP 1.1, but beans can be used in both JSP 1.0 and 1.1.
6. Using the JavaBeans with JSP
The JavaBeans API provides a standard format for Java classes. Visual manipulation tools and
other programs can automatically discover information about classes that follow this format and
can then create and manipulate the classes without the user having to explicitly write any code.
Full coverage of JavaBeans is beyond the scope of this book. The jsp:useBean action lets you
load a bean to be used in the JSP page. Beans provide a very useful capability because they let
you exploit the reusability of Java classes without sacrificing the convenience that JSP adds over
servlets alone. The simplest syntax for specifying that a bean should be used is: <jsp:useBean
id="name" class="package.Class" /> .
7. The free servlet and JSP Books
Slides and exercises from Marty Hall's world-renowned live training courses are now available
online. The materials on this page are based on the first edition of Marty's book Core Servlets and
JavaServer Pages and have been tested by Marty in live courses in the US, Canada, Australia,
Puerto Rico, Japan, and the Philippines. See the training materials home page for slides based
on More Servlets and JavaServer Pages, Core Web Programming, the second edition of Core
Servlets and JavaServer Pages, and online tutorials and conference talks on servlets, JSP, JSTL,
Apache Struts, and JSF. Materials in Japanese also available. The HTML and PDF versions of
the slides are freely available to anyone for personal use. These versions contain the complete
text of the PowerPoint slides, and are what you want if your goal is to learn or review the
technology.
8. The advanced servlet and JSP Tutorial
The advanced servlet and JSP tutorials on this page are based on Marty's book More Servlets
and JavaServer Pages, and have been tested by Marty in live training courses in the US,
Canada, Australia, Puerto Rico, Japan, and the Philippines. The PDF versions of the tutorials are
freely available to anyone for personal use. These versions contain the complete text of the
PowerPoint slides, and are what you want if your goal is to learn or review the technology. As a
Page 58
courtesy, coreservlets.com also makes the original PowerPoint slides available to faculty teaching
courses that do not compete with Marty's live courses.
Authentication in Web Application
Example for Authenticating user in JSP based application using servlet and
MySql
In this example we will show you how to authenticated the user against database user name and
password. This program constists of a JSP page and a Servlet to authenticate the user against database
password.
User enters the username and password on the JSP page and clicks on the the "Check" button. On the
form submit event data is posted to the Servlet for authenticating the user. Servlet makes JDBC
connection and authenticate the user.
We are using tomcat server for running Servlet and JSP page. You can use any
browser to test the application
Authentication means that user can be recognized that the user really exist for which he
is inputting values. We are using two
files Authentication.jsp andAuthentication.java and we are making the application in
"webapps/JSPMultipleForms" in tomcat server. We have used MySQL for database
connection and by putting values in "user" table we have authenticated the input of
user. Table structure code for "user" table is given as below:
User Table Structure of MySQL:
CREATE TABLE `user` (`user` varchar(256) default NULL,`password` varchar(256) default NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Page 59
/*Data for the table `user` */
insert into `user`(`user`,`password`) values ('amit','kumar');
Authentication.jsp is calling Servlet to authenticate user's input. Servlet "Authentication.java" which will
first establishes the JDBC connection to the database on the machine whose IP address
is192.168.10.59. The database used in this application is messagepaging. You can change the
database before running the example at your machine. Then program authenticates the user against
database. If input given by user is correct then a message will flash on the browser that "User
Authenticated" else "You are not an authentic person".
The code for Authentication.java is given below:
1. Authentication.java
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Authentication extends HttpServlet{
private ServletConfig config;
public void init(ServletConfig config)
throws ServletException{
this.config=config;
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
PrintWriter out = response.getWriter();
String connectionURL = "jdbc:mysql://192.168.10.59/messagepaging";
Connection connection=null;
ResultSet rs;
String userName=new String("");
Page 60
String passwrd=new String("");
response.setContentType("text/html");
try {
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "root", "root");
//Add the data into the database
String sql = "select user,password from User";
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
userName=rs.getString("user");
passwrd=rs.getString("password");
}
rs.close ();
s.close ();
}catch(Exception e){
System.out.println("Exception is ;"+e);
}
if(userName.equals(request.getParameter("user")) &&
passwrd.equals(request.getParameter("pass"))){
out.println("User Authenticated");
}
else{
out.println("You are not an authentic person");
}
}
}
2. Authentication.jsp
<%@ page language="java" %>
Please enter your Name and Password here:
<br>
Page 61
<br>
<form name="frm" action="/JSPMultipleForms/Authentication" method="Post" >
Name: <input type="text" name="user" value=""/>
Password:<input type="text" name="pass" value=""/>
<input type="submit" value="Check" />
</form>
For invoking servlet in tomcat server we have to include the following lines into "web.xml" file.
3. web.xml
<!--web.xml code -->
<servlet><servlet-name>Authentication</servlet-name><servlet-class>Authentication</servlet-class></servlet>
<servlet-mapping><servlet-name>Authentication</servlet-name><url-pattern>/Authentication</url-pattern></servlet-mapping>
To Run the above example you have to follow these steps:
1.Create and Save Authentication.java.
2.Compile Authentication.java and place the class file into classes folder.
3.Insert the servlet name and mapping in web.xml.
4.Create and Save Authentication.jsp file in JSPMultipleForms folder.
5.Deploy the Tomcat Server.
6.Type the following line in address bar "http://localhost:8080/JSPMultipleForms/Authentication.jsp"
Output :
Authentiocation.jsp
Page 62
User authenticated
User not authenticated
Page 63
Download Source Code
Calling Servlet to build a List of data from database and show this on the JSP page in table
In this example we are calling a servet to retrieve all the data from database and then add the data into
list. The list is then added to the request object and sen to JSP page. On the JSP page this value is
displayed.
This example illustrate how a servlet can be used to create a data list from database and how it can be
added to the request object and sent to the JSP page. We are using tomcat to run and test the application
In our example "DataServlet.java" is the servlet which is making the connection to the database and
retrieves the data from database. After getting the values from database, data is added to the Data List.
Page 64
Then data list is added to the request object and sent to the JSP page. In JSP page the values are
displayed using Iterator class object.
Table structure for "message" is :
create table `message` (`id` double ,`message` varchar (256)); insert into `message` (`id`, `message`) values('1','amit');insert into `message` (`id`, `message`) values('2','kumar');insert into `message` (`id`, `message`) values('3','singh');insert into `message` (`id`, `message`) values('4','raghuwanshi');insert into `message` (`id`, `message`) values('5','vineet');insert into `message` (`id`, `message`) values('6','sandeep');insert into `message` (`id`, `message`) values('7','suman');insert into `message` (`id`, `message`) values('8','vineet');
Following code ads the data into request object:
request.setAttribute("data",dataList);
Following code forwards the request to a JSP page:
RequestDispatcher dispatcher = request.getRequestDispatcher(page);if (dispatcher != null){dispatcher.forward(request, response);}
The code for "DataServlet.java" is given as below:
Page 65
1. DataServlet.java
import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DataServlet extends HttpServlet{
private ServletConfig config;
//Setting JSP page
String page="DataPage.jsp";
public void init(ServletConfig config)
throws ServletException{
this.config=config;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
Page 66
throws ServletException,IOException
{
PrintWriter out = response.getWriter();
//Establish connection to MySQL database
String connectionURL = "jdbc:mysql://192.168.10.59/messagepaging";
Connection connection
= null;
ResultSet rs;
response.setContentType("text/html");
List dataList
= new ArrayList();
try {
// Load the database driver
Class.forName("com.mysql.jdbc.Driver");
// Get a Connection to the database
connection = DriverManager.getConnection(connectionURL, "root", "root");
//Select the data from the database
String sql = "select * from message";
Page 67
Statement s = connection.createStatement();
s.executeQuery (sql);
rs = s.getResultSet();
while (rs.next ()){
//Add records into data list
dataList.add(rs.getInt("id"));
dataList.add(rs.getString("message"));
}
rs.close ();
s.close ();
}catch(Exception e){
System.out.println("Exception is ;"+e);
}
request.setAttribute("data",dataList);
//Disptching request
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null){
Page 68
dispatcher.forward(request, response);
}
}
}
Code for "DataPage.jsp" is given as below:
2. DataPage.jsp
<%@page language="java" import="java.util.*" %><html><head><title>Data Page</title></head><body> <table border="1" width="303"><tr><td width="119"><b>ID</b></td><td width="168"><b>Message</b></td></tr><%Iterator itr;%><% List data= (List)request.getAttribute("data");for (itr=data.iterator(); itr.hasNext(); ){%><tr><td width="119"><%=itr.next()%></td><td width="168"><%=itr.next()%></td></tr><%}%></table></body></html>
For servlet to be invoked we have to do following entry in the web.xml file for servlet mapping.
Page 69
3. web.xml
<!--web.xml code -->
<servlet><servlet-name>DataServlet</servlet-name><servlet-class>DataServlet</servlet-class></servlet>
<servlet-mapping><servlet-name>DataServlet</servlet-name><url-pattern>/DataServlet</url-pattern></servlet-mapping>
For running the above example we have to follow the following steps:
1.Create and Save "DataServlet.java".
2.Compile that java file and place the DataServlet.class file into classes folder.
3.Do the servlet mapping in the web.xml
4.Create and Save "DataPage.jsp" and place it into appropriate folder.
5.Deploy the Tomcat Server.
6.Type following line in address bar "http://localhost:8080/JSPMultipleForms/DataServlet".
Output:
Page 70
Download Source Code
Access all the fields from table through JSP
This is detailed java program to connect java application with MySql database and execute query to
display data from the specified table. Before running this java code you need mysql-connector-java-
3.1.6-bin.jar file and set class path to this file.
This is first jsp page that has a link 'show data from table', which displays all the data from table when
clicked. This is the code of first welcome jsp page.
Page 71
welcome_to_database_query.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>display data from the table using jsp</title>
</head>
<body>
<TABLE style="background-color: #ffffcc;">
<TR>
<TD align="center">
<h2>To display all the data from the table click here...</h2></TD>
</TR>
<TR>
<TD align="center"><A HREF="ConnectJspToMysql.jsp">
<font size="4" color="blue">show data from
table</font></A></TD>
</TR>
</TABLE>
</body>
</html>
Save this code with the name "welcome_to_database_query.jsp" in the application directory in Tomcat.
Start tomcat server and type url 'http://localhost:8080/user/welcome_to_database_query.jsp' in address
bar of browser and run.
Page 72
This page has a link, to show data from the database click on the link that calls another .jsp file named
ConnectJspToMysql.jsp
ConnectJspToMysql.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>display data from the table using jsp</title>
</head>
<body>
<h2>Data from the table 'stu_info' of database 'student'</h2>
<%
try {
/* Create string of connection url within specified
format with machine name, port number and database name.
Here machine name id localhost and database name is student. */
String connectionURL = "jdbc:mysql://localhost:3306/student";
// declare a connection by using Connection interface
Page 73
Connection connection = null;
// declare object of Statement interface that is used for
executing sql statements.
Statement statement = null;
// declare a resultset that uses as a table for output data
from tha table.
ResultSet rs = null;
// Load JBBC driver "com.mysql.jdbc.Driver".
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection()
method that takes parameters of string type
connection url, user name and password to connect to database. */
connection = DriverManager.getConnection(connectionURL, "root",
"root");
/* createStatement() is used for create statement
object that is used for sending sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the secified table.
String QueryString = "SELECT * from stu_info";
rs = statement.executeQuery(QueryString);
%>
<TABLE cellpadding="15" border="1" style="background-color: #ffffcc;">
<%
while (rs.next()) {
%>
<TR>
<TD><%=rs.getInt(1)%></TD>
<TD><%=rs.getString(2)%></TD>
<TD><%=rs.getString(3)%></TD>
Page 74
<TD><%=rs.getString(4)%></TD>
</TR>
<% } %>
<%
// close all the connections.
rs.close();
statement.close();
connection.close();
} catch (Exception ex) {
%>
</font>
<font size="+3" color="red"></b>
<%
out.println("Unable to connect to database.");
}
%>
</TABLE><TABLE>
<TR>
<TD><FORM ACTION="welcome_to_database_query.jsp" method="get" >
<button type="submit"><-- back</button></TD>
</TR>
</TABLE>
</font>
</body>
</html>
Save this code with name ConnectJspToMysql.jsp in the same dirctory of
welcome_to_database_query.jsp. Click on the link given in the first jsp page,that calls this jsp page and
show all data from the table.
Page 75
Click on the <--back button to go to first page of the application.
Download source code
Use Break Statement in jsp code
The break statement is used to terminate the execution of near most enclosing loop or conditional
statement. Now the next statement outside the loop is executed.
In the example given below the elements of an array are added one by one. After each addition, the sum
is checked whether it is more than 12. If the sum is less than 12 then the message "we are in loop..." is
displayed otherwise the control comes out of the loop and does not print the same line again for this
Page 76
iteration. The rest iterations are also not executed because the loop is now terminated and the control is
on the next statement after loop.
break_statement_jsp.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> <HEAD> <TITLE>Using the break Statement</TITLE> </HEAD> <BODY> <H1>use break statement in jsp code</H1> <% double array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int sum = 0; for(int i = 0; i < array.length; i++) { sum += array[i];
// use break statement. if (sum > 12) break; out.println("we are in loop...<BR>"); } out.println("The sum exceeded the max allowed value 12."); %> </BODY></HTML>
Save this code as a jsp file named "break_statement_jsp.jsp" in your application directory (user, for
this example) in Tomcat and run this jsp page
withhttp://localhost:8080/user/break_statement_jsp.jsp url in address bar of the browser.
Page 77
Download Source Code
Use Compound Statement in JSP Code
A compound statement is collection of statements enclosed with in braces. In general, statement works
without braces but it only execute single statement and rest of the statements takes as normal statement
and execute them.
Example :
if( boolean condition) statement1; statement2; statement3;
Here in the above code only statement1 will be execute if boolean condition gets true and rest statements
execute as a normal statement.
if( boolean condition) {
Page 78
statement1; statement2; statement3;}
In the code above all the three statements are executed if boolean condition gets true because all the
statements are bound with braces in if condition.
Compound statements are used with:
if statementwhile statementfor statementtry statementmethod definitionclass definition etc.
Create an application directory named "user" in the tomcat-6.0.16/webapps. The following jsp code will
show you how to use compound statement.
compound_statement.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<HTML>
<HEAD>
<TITLE>Compound statement in jsp</TITLE>
</HEAD>
<BODY bgcolor="#6E6E6E">
<FORM NAME="form1" ACTION="compound_statement.jsp" METHOD="get">
<TABLE bgcolor="#D8D8D8">
<tr>
<td> Enter number </td>
<td><input type="text" name="num"></td>
</tr>
<tr align="center"><td></td>
Page 79
<td><INPUT TYPE="submit" VALUE="check"></td></tr></TABLE>
<br>
<TABLE bgcolor="#E0ECF8"><tr><td>
</FORM>
<% try {
// Here if statement is used for more than one statement.
if (request.getParameter("num") != null &&
request.getParameter("num")!=""){
// Compound statement is used in 'if' statement
if (Long.parseLong(request.getParameter("num"))>0 ){
out.println("You have given a positive number.<br>");
out.println("Absolute value is = " +
Math.abs(Long.parseLong(request.getParameter("num"))));
}
if (Long.parseLong(request.getParameter("num"))<0 ){
out.println("You have given a negative number.<br>");
out.println("Absolute value is = " +
Math.abs(Long.parseLong(request.getParameter("num"))));
}
// only single statement is used in 'if' statement
if (Long.parseLong(request.getParameter("num"))==0 )
out.println("You have entered ZERO.");
}
}
catch(Exception ex){
out.println("<font color=\"red\">You have entered
wrong input value</font>");
out.println("<font color=\"green\">Try
again</font>");
}
%>
</BODY>
</HTML>
Page 80
Save this code as a .jsp file named "compound_statement.jsp" in the directory
Tomcat-6.0.16/webapps/user/. Run tomcat server by clicking on startup.bat file in bin directory of tomcat.
Run this jsp page with following url in address bar of the
browser:http://localhost:8080/user/compound_statement.jsp
This is the first page, user enter valid digit in the text box and click check button. This application check
that given number is positive or negative or zero and show appropriate message.
When user click on check button.......
Page 81
If user enters invalid value in text box then this application shows an error message.....
Download Source Code
Connect JSP with mysql
Create a database : First create a database named 'usermaster' in mysql. To create
this database we need to run the following query in sql prompt.
mysql> create database
Page 82
usermaster;
This query creates database 'usermaster' in Mysql.
Connect JSP with mysql :
Now in the following jsp code, you will see how to connect with the database. First you
need to copy my sql connector jar file in lib directory of your application. Name of mysql
driver is passed to the forName() method of 'Class' class which loads the driver. To get
the connection with the database, getConnection() method of DriverManager class is
used which takes three parameters connection url, username and password.
Here is the full jsp code.
ConnectJspToMysql.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>Connection with mysql database</title>
</head>
<body>
<h1>Connection status </h1>
<%
try {
/* Create string of connection url within specified format with machine name,
port number and database name. Here machine name id localhost and database
name
is usermaster. */
String connectionURL = "jdbc:mysql://localhost:3306/usermaster";
// declare a connection by using Connection interface
Connection connection = null;
// Load JBBC driver "com.mysql.jdbc.Driver".
Page 83
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection() method that takes parameters
of
string type connection url, user name and password to connect to database. */
connection = DriverManager.getConnection(connectionURL, "root", "root");
// check weather connection is established or not by isClosed() method
if(!connection.isClosed())
%>
<font size="+3" color="green"></b>
<%
out.println("Successfully connected to " + "MySQL server using TCP/IP...");
connection.close();
}
catch(Exception ex){
%>
</font>
<font size="+3" color="red"></b>
<%
out.println("Unable to connect to database.");
}
%>
</font>
</body>
</html>
Output of the program when connection is established with specified mysql database :
Page 84
Output of the program when unable to connect to specified mysql database :
Download source code
Page 85
Create a Table in Mysql database through SQL Query in JSP
This is detailed java code to connect a jsp page to mysql database and create a table of given name in
the specified database.
Create a database : First create a database named 'usermaster' in mysql and create table
"user_master". Create an application directory named 'user' in the Tomcat. Before running this java code
you need mysql connector jar in the Tomcat-6.0.16/webapps/user/WEB-INF/lib directory.
Creating JSP pages:
In this example, we have created two JSP pages. First page is to provide link to create table and the next
page for processing the table creation.
1. welcome_to_database_query.jsp
2.create_table.jsp
1. welcome_to_database_query.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <html> <head> <title>Create table in mysql database using jsp</title> </head> <body> <TABLE style="background-color: #ffffcc;"> <TR> <TD align="center"><h2>To create table click on the link given below</h2></TD> </TR> <TR> <TD align="center"><A
Page 86
HREF="create_table.jsp"> <font size="+2" color="blue">create table</font> </TR> </TABLE> </body> </html>
Save this code as a .jsp file named "welcome_to_database_query.jsp" in the directory
Tomcat-6.0.16/webapps/user/. You can run this jsp page
typinghttp://localhost:8080/user/welcome_to_database_query.jsp url in address bar of the browser.
2.create_table.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<html>
<head>
<title>display data from the table using jsp</title>
</head>
<body>
<%
/* Create string of connection url within specified
format with machine name, port number
and database name. Here machine name id localhost
Page 87
and database name is usermaster. */
String connectionURL = "jdbc:mysql://localhost:3306/usermaster";
// declare a connection by using Connection interface
Connection connection = null;
// declare object of Statement interface that is used
for
// executing sql statements.
Statement statement = null;
try {
// Load JBBC driver "com.mysql.jdbc.Driver".
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using
getConnection() method
that takes parameters of string type connection url, user
name and password to connect to database. */
connection =
DriverManager.getConnection(connectionURL, "root", "root");
/* createStatement() is used for create statement object
that is used for sending
sql statements to the specified database. */
statement = connection.createStatement();
// sql query to retrieve values from the
secified table.
String QueryString =
"create table user_master(id int not null auto_increment,name
" +
"varchar(25),city varchar(20), primary key(id));";
// execyteUpdate() mothod execute
specified sql query.
statement.executeUpdate(QueryString);
%> <TABLE border="0" style="background-color:
#ffffcc;">
<TR>
<TD align="center" ><font size="+3" color="green">Congratulations
Page 88
!
</font></TD>
<tr><TD align="center" ><font size="+2">Table of specified name is
created successfully.</font>
</TD></tr>
</TR>
<% } catch (Exception ex) {%>
<TABLE border="0" style="background-color: #ffffcc;">
<TR>
<TD align="center" ><font size="+3" color="red">Some problems
to create table.</font></TD>
</TR>
<% } finally {
// close all the connections.
statement.close();
connection.close();
}
%><tr><td align="center" >
<A HREF="welcome_to_database_query.jsp">
<font size="5" color="blue">back to home page</font></A></td>
</tr> </TABLE>
</body>
</html>
Save this code with name "create_table.jsp" in the directory Tomcat-6.0.16/webapps/user/. This jsp code
creates table of specified name in the mysql database and shows a response page.
Page 89
If table exists already or found any error to make connection with database then shows an error page.
Download Source code
Create dynamic page through JSP
Page 90
This is detailed jsp code that shows how to create dynamic page. This code shows one by one record of
student from database on click a button named 'next record'. On each click of button, application fetch
next record from database.
Create a database : Before running this jsp code, first create a database named 'student'
through the sql query given below in mysql command prompt :-
mysql> create database student;
Then create a table named 'stu_info' in the same database through following sql
query :-
create table stu_info ( ID int not null auto_increment, Name varchar(20), Address varchar(20), Phone varchar(15), primary key(ID));
Create your application directory named "user" in the Tomcat server. Before running this java code you
need mysql connector jar in the Tomcat-6.0.16/webapps/user/WEB-INF/lib.
ConnectJspToMysql.jsp:
This file provides full code how to connect with database and showing the next record of database in JSP.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<HTML>
<HEAD>
<TITLE>Navigating in a Database Table </TITLE>
</HEAD>
<BODY bgcolor="#ffffcc">
Page 91
<font size="+3" color="green"><br>Welcome in www.roseindia.net !</font>
<br>
<font size="+1" color="#6E6E6E"><br>This is dynamic page that shows data<br>
from database as per user choice.</font>
<% int current = 0;
// declare a connection by using Connection interface
Connection connection = null;
/* Create string of connection url within specified
format with machine
name, port number and database name. Here machine name id
localhost
and database name is student. */
String connectionURL =
"jdbc:mysql://localhost:3306/student";
/*declare a resultSet that works as a table resulted by execute a
specified
sql query. */
ResultSet rs = null;
%>
<FORM NAME="form1" ACTION="ConnectJspToMysql.jsp" METHOD="get"><%
if (request.getParameter("hidden") != null) {
current = Integer.parseInt(request.getParameter("hidden"));
}
// Declare statement.
Statement statement = null;
try {
// Load JDBC driver "com.mysql.jdbc.Driver"
Class.forName("com.mysql.jdbc.Driver").newInstance();
/* Create a connection by using getConnection()
method that takes
parameters of string type connection url, user name and
password to
connect to database. */
connection = DriverManager.getConnection(connectionURL,
"root", "root");
Page 92
/* createStatement() is used for create
statement object that is
used for sending sql statements to the specified database. */
statement = connection.createStatement();
// executeQuery() method execute specified sql
query.
rs = statement.executeQuery("select * from stu_info");
for (int i = 0; i < current; i++) {
rs.next();
}
if (!rs.next()) {
%>
<FONT size="+2" color="red"></b>
<%
out.println("Sorry ! found some problems with database.");
} else {
%>
<TABLE style="background-color: #ECE5B6;" WIDTH="30%" >
<TR><TH width="50%">ID</TH><TD width="50%"> <%= rs.getInt(1)%> </TD></tr>
<TR><TH>Name</TH><TD> <%= rs.getString(2)%> </TD></tr>
<TR><TH>City</TH><TD> <%= rs.getString(3)%> </TD></tr>
<TR><TH>Phone</TH><TD> <%= rs.getString(4)%> </TD></tr>
</TR>
</TABLE>
<BR>
<INPUT TYPE="hidden" NAME="hidden" VALUE="<%=current + 1%>">
<INPUT TYPE="submit" VALUE="next record">
</FORM>
<%
}
}
catch (Exception ex) {
%>
<FONT size="+3" color="red"></b>
Page 93
<%
out.println("Unable to connect to database.");
} finally {
// close all the connections.
rs.close();
statement.close();
connection.close();
}
%>
</FONT>
</FORM>
</body>
</html>
Save this code as a .jsp file named "ConnectJspToMysql.jsp" in the directory
Tomcat-6.0.16/webapps/user/ and run this jsp page with following url in address bar of the browser
"http://localhost:8080/user/ConnectJspToMysql.jsp".
Page 94
When click on button, application control goes to database and check for the next record. If next record is
found in table, it is shown in browser else an error message.
Error message page:
Page 95
Download Source code
Retrieve image from mysql database through jsp
In this section we will see how to retrieve image from mysql database through jsp code. First create a
database of structure given below and save images. Here we will use table 'save_image' of database
'mahendra'.
Structure of table 'save_image'
First create database named 'mahendra' by query given below....
CREATE TABLE save_image ( id int(5) NOT NULL auto_increment, name varchar(25) default NULL, city varchar(20) default NULL, image blob, Phone varchar(15) default NULL, PRIMARY KEY (`id`) );
Create application directory named "user" in the tomcat-6.0.16/webapps. Before running this java code
you need mysql connector jar file in the Tomcat-6.0.16/webapps/user/WEB-INF/lib.
mysql> create database mahendra;
Page 96
Note : In the jsp code given below, image will be retrieved from database on the basis of 'id' field of the
table. So code will retrieve image of specified 'id' value. In this example we will retrieve image with 'id'
value 11. So before running this jsp code first check whether image for the specified 'id' value is present.
retrieve_image.jsp
<%@ page import="java.sql.*" %><%@ page import="java.io.*" %>
<% // declare a connection by using Connection interface Connection connection = null;/* Create string of connection url within specified format with machine name, port number and database name. Here machine name id localhost and database name is mahendra. */String connectionURL = "jdbc:mysql://localhost:3306/mahendra";/*declare a resultSet that works as a table resulted by execute a specified sql query. */ResultSet rs = null;// Declare statement.PreparedStatement psmnt = null;// declare InputStream object to store binary stream of given image.InputStream sImage;try {// Load JDBC driver "com.mysql.jdbc.Driver"Class.forName("com.mysql.jdbc.Driver").newInstance();/* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */connection = DriverManager.getConnection(connectionURL, "root", "root");/* prepareStatement() is used for create statement object that is used for sending sql statements to the specified database. */psmnt = connection.prepareStatement("SELECT image FROM save_image WHERE id = ?");psmnt.setString(1, "11"); // here integer number '11' is image id from the tablers = psmnt.executeQuery();if(rs.next()) {byte[] bytearray = new byte[1048576];int size=0;sImage = rs.getBinaryStream(1);response.reset();response.setContentType("image/jpeg");
Page 97
while((size=sImage.read(bytearray))!= -1 ){response.getOutputStream().write(bytearray,0,size);}}}catch(Exception ex){out.println("error :"+ex);}finally {// close all the connections.rs.close();psmnt.close();connection.close();}%>
Save this code as a .jsp file named "retrieve_image.jsp" in the application directory in Tomcat-6.0.16
and run this jsp page with following url in address bar of the
browserhttp://localhost:8080/user/retrieve_image.jsp
Page 98
Download Source Code
How To Page Refresh Using JavaScript In JSP
In this section, we develop an User Login application . We created five
filesign.jsp,signout.jsp,user_register.jsp,userlogin.jsp and useradd.jsp.
Brief description of the flow of the application:
User opens sign.jsp in the browser and clicks on "Sign In" button.
Page 99
New opens where user can provide username and password.
If user enters correct username and password user. If the login is successful, parent window is
refreshed and user details is displayed.
User can also signup for new account.
Step 1: Create a web page(sign.jsp) to show a button to Login user.
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<META NAME="Generator" CONTENT="EditPlus">
<META NAME="Author" CONTENT="">
<META NAME="Keywords" CONTENT="">
<META NAME="Description" CONTENT="">
<script>
function signout()
{
window.location.href="signout.jsp";
}
</script>
</HEAD>
<BODY>
<br><br><br><br><br>
<table width="250px" align="center" bgcolor="#CDFFFF" border=0
style="border:1px solid;">
<%
if(session.getAttribute("username")!=null && session.getAttribute("password")!
=null)
Page 100
{
String username="";
String pass="";
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
String data = "";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
username = session.getAttribute("username").toString();
pass = session.getAttribute("password").toString();
String query =
"select * from userregister where username='"+username+"' and
password='"+pass+"'";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next())
{
%>
<tr><td colspan=3 align="center"><b>User Details</b></td></tr>
<tr><td><b>User Name </b></td><td><b>:</b></td><td><
%=rs.getString(2)%></td></tr>
Page 101
<tr><td><b>First Name </b></td><td><b>:</b></td><td><
%=rs.getString(4)%></td></tr>
<tr><td><b>Last Name </b></td><td><b>:</b></td><td><
%=rs.getString(5)%></td></tr>
<tr><td><b>City </b></td><td><b>:</b></td><td><
%=rs.getString(6)%></td></tr>
<tr><td><b>State </b></td><td><b>:</b></td><td><
%=rs.getString(7)%></td></tr>
<tr><td><b>Country</b></td><td><b>:</b></td><td><
%=rs.getString(8)%></td></tr>
<%
}
out.println(data);
}
catch (Exception e) {
e.printStackTrace();
}
%>
<tr>
<td align="center" colspan=3>
<input type="button" name="signout" value="Sign Out" onclick="signout();">
</td>
</tr>
<%
}
else
{
Page 102
%>
<tr><td colspan=2> </td></tr>
<tr><td colspan=2 align="center"><b>To Login User Click on Sign
In</b></td></tr>
<tr><td colspan=2> </td></tr>
<tr>
<td colspan="2" align="center">
<input type="button" name="signin" value="Sign In"
onClick="window.open('userlogin.jsp','mywindow','width=500,
height=350,toolbar=no,resizable=yes,menubar=yes')">
</td></tr>
<tr><td colspan=2> </td></tr>
<%
}
%>
</table>
</BODY>
</HTML>
Step:2Create a web page (userlogin.jsp) to User Login.
<html>
<head>
<style>
a{
font: bold 13px Verdana;
padding: 2px;
Page 103
padding-left: 4px;
display: block;
width: 100px;
color: black;
text-decoration: underline;
}
a:hover{
color: black;
text-decoration: none;
}
</style>
<script>
function validate()
{
if(document.frm.username.value=="")
Page 104
{
alert("Please enter username");
document.frm.username.focus();
return false;
}
if(document.frm.password.value=="")
{
alert("Please enter username");
document.frm.password.focus();
return false;
}
return true;
}
function trim(stringToTrim) {
return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function login()
Page 105
{
if(validate())
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var username =document.getElementById("username").value;
var password =document.getElementById("password").value;
var url="userloginmid.jsp"
url=url+"?username="+username+"&password="+password;
Page 106
//alert(url);
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
}
function stateChanged()
{
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
var showdata = xmlHttp.responseText;
var str = showdata.toString();
if(trim(str)=="successLogin")
Page 107
{
window.opener.location.reload();
window.location.reload();
window.close();
}
else
{
window.location.href="userlogin.jsp?errmsg=error";
}
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
Page 108
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
Page 109
</script>
</head>
<body>
<br><br>
<%
String errmsg="";
if(request.getParameter("errmsg")!=null &&
request.getParameter("errmsg")!="")
{
errmsg ="Invalid username and password";
}
%>
<form name="frm">
<table border="0" width="400px" align="center" bgcolor="#CDFFFF">
Page 110
<tr><td colspan=2 align="center" style="color:red;"><%=errmsg
%></td></tr>
<tr><td colspan=2 align="center"> </td></tr>
<tr><td colspan=2 align="center"><b>User Login</b></td></tr>
<tr><td>Username : </td><td><input type="text" name="username"
id="username"></td></tr>
<tr><td>Password : </td><td><input type="password" name="password"
id="password"></td></tr>
<tr><td colspan=2 align="center"><input type="button" name="submit"
value="Submit" onclick="login();"></td></tr>
<tr><td colspan=2 align="center"><a href="user_register.jsp">New
User</a></td></tr>
</form>
</body>
</html>
Step 3:Create a web page (userloginmid.jsp) to retieve the details of selected user.
Page 111
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username").toString();
String pass = request.getParameter("password").toString();
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
String data = "";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select count(*) from userregister where
username='"+username+"' and password='"+pass+"'";
Page 112
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next())
{
System.out.println(query);
if(rs.getInt(1)>0)
{
session.setAttribute("username",username);
session.setAttribute("password",pass);
data = "successLogin";
}
}
out.println(data);
}
catch (Exception e) {
e.printStackTrace();
}
%>
Page 113
Step 4:Create a web page (useradd.jsp) to add new user.
<%@ page import="java.sql.*" %>
<%
String username = request.getParameter("username").toString();
String pass = request.getParameter("password").toString();
String first_name = request.getParameter("first_name").toString();
String last_name = request.getParameter("last_name").toString();
String city = request.getParameter("city").toString();
String state = request.getParameter("state").toString();
String country = request.getParameter("country").toString();
String data="";
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
Page 114
String userName = "root";
String password = "root";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "insert into userregister set
username='"+username+"',password='"+pass+"',first_name='"+first_name+
"',last_name='
"+last_name+"',city='"+city+"',state='"+state+"',country='"+country+"'";
System.out.println("query : " + query);
st = conn.createStatement();
int i = st.executeUpdate(query);
if(i>0)
{
Page 115
data ="successAdd";
}
out.println(data.trim());
}
catch (Exception e) {
e.printStackTrace();
}
%>
Successful Output of the program:
Click on Sign In to Login User:
Page 116
Output when Successfully Submit the User Login refresh the parent window and show the user details.
For New User.
Download the full web application shows here.
Page 117
Download the application
Display Sum of Table Column Using In JSP
In this section, we develop an application to Display the sum data of a Table column for a specific Date.
We created five filesum_count.jsp, resultForm.jsp, result_count.jsp,
sumcount.java and SumCountBean.java. When a web page ("sum_count.jsp") run on browser then it
will insert the salary amount for a specific date and on this page having a link "Click here To Show Total
Salary" to show the total salary between two specific date and result is display using Jsp Bean..
Step 1: Create a web page(sum_count.jsp) to insert a Salary.
<%@ page import="java.sql.*" %>
<html>
<head>
<style>
A:hover {text-decoration: none;
border: 0px;
font-size:14pt;
color: #2d2b2b; }
</style>
Page 118
<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript" src="datepicker.js"></script>
<script>
function validate()
{
var sdate = document.frm.date.value;
var sdateAr=sdate.split("-");
if(document.frm.date.value=="")
{
alert("Please enter the date.");
document.frm.date.focus();
return false;
}
if(sdateAr.length!=3)
{
alert("Please enter valid Date in mm-dd-yyyy format.");
document.frm.date.value="";
document.frm.date.focus();
return false;
}
if(document.frm.salary.value=="")
{
alert("Please enter the salary.");
document.frm.salary.focus();
return false;
}
}
</script>
</head>
<body>
<%
String salary="";
Page 119
String date="";
String success_msg="";
if(request.getParameter("salary")!=null && request.getParameter("date")!=null
)
{
salary = request.getParameter("salary");
date = request.getParameter("date");
String strar[] = date.split("-");
if(salary !="" && date!="")
{
String cdate = strar[2]+"-" + strar[0]+"-"+ strar[1];
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "sumcount";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query =
"insert into sumcount set emp_salary='"+salary+"',date='"+cdate+"'";
st = conn.createStatement();
int ir = st.executeUpdate(query);
Page 120
if(ir>0)
{
success_msg ="You entered Successfully Salary.";
}
}
catch (Exception e) {
e.printStackTrace();
}
}
salary ="";
date ="";
}
%>
<br><br><br>
<form method="post" name="frm" onSubmit="validate();">
<table border="0" width="400px" align="center" bgcolor="#CDFFFF">
<tr>
<td colspan=2 style="font-size:10pt;color:#ff0000;" align="center"><
%=success_msg%>
</td>
</tr>
<tr>
<td colspan=2 style="font-size:12pt;color:#00000;" align="center">
<h3>Enter Date and Salary</h3></td></tr>
<tr><td> </td></tr>
<tr><td ><b>Date:</b></td><td><input type="text" name="date" id="cdate">
<input type=button value="Select Date" onclick="displayDatePicker('date',
this);">
</td></tr>
<tr><td><b>Salary:</b></td><td><input type="text" name="salary"></td></tr>
<tr><td> </td></tr>
Page 121
<tr><td colspan=2 align="center">
<input type="submit" name="submit" value="Save"></td></tr>
</table>
</form>
<table border="0" width="100%" align="center">
<br>
<br>
<tr>
<td width="100%" align="center">
<a href="resultForm.jsp" style="font-size:14pt;color:blue;" >
Click here to Show Total Salary</a></td>
</tr>
</table>
</body>
</html>
Here is the output of this program:
Page 122
Step 2:Create a web page (resultForm.jsp) to Select a Date.
<%@ page import="java.sql.*" %>
<html>
<head>
<style>
A:hover {text-decoration: none;
border: 0px;
font-size:14pt;
color: #2d2b2b; }
</style>
<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript" src="datepicker.js"></script>
<script>
function validate()
{
var sdate = document.frm.date.value;
var sdateAr=sdate.split("-");
var ldate = document.frm.edate.value;
var ldateAr=ldate.split("-");
if(document.frm.date.value==""){
alert("Please enter Start Date.");
document.frm.date.focus();
return false;
}
if(document.frm.edate.value==""){
alert("Please enter End Date.");
document.frm.edate.focus();
return false;
}
if(sdateAr.length!=3){
alert("Please enter valid Start Date in mm-dd-yyyy format.");
document.frm.date.value="";
document.frm.date.focus();
Page 123
return false;
}
if(ldateAr.length!=3){
alert("Please enter valid End Date in mm-dd-yyyy format.");
document.frm.edate.value="";
document.frm.edate.focus();
return false;
}
if(sdateAr[0]>ldateAr[0] || sdateAr[1]>ldateAr[1] ||
sdateAr[0]>ldateAr[0]){
alert("Start Date must be less then End date.");
document.frm.edate.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<br><br><br>
<form method="post" name="frm" action="sumcount" onSubmit="return
validate();">
<table border="0" width="400" align="center" bgcolor="#CDFFFF">
<tr>
<td colspan=2 style="font-size:12pt;color:#00000;" align="center">
<h3>Please Select Start and End Date</h3>
</td>
</tr>
<tr><td ><b>Start Date:</b></td><td><input type="text" name="date"
id="cdate">
<input type=button value="Select Date" onclick="displayDatePicker('date',
this);">
</td></tr>
<tr><td ><b>End Date:</b></td><td><input type="text" name="edate"
Page 124
id="edate">
<input type=button value="Select Date" onclick="displayDatePicker('edate',
this);">
</td></tr>
<tr><td> </td></tr>
<tr><td colspan=2 align="center"><input type="submit" name="submit"
value="Submit"></td></tr>
</table>
</form>
</body>
</html>
Step 2:Create a Servlet (sumcount.java) to retrieve data.
In this Servlet retrieve the data using mysql Query select sum(emp_salary)
from sumcount where date>='"+cdate+"' and date<='"+ldate+"'";
The cdate and ldate are the posted data from "resultForm.jsp".
After result set in a attribute variable
"sumcount"request.setAttribute("sumcount",sumcount); and forward
to"result_count.jsp" to show the output.
Here is the code of sumcount:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
Page 125
public class sumcount extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "sumcount";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
String date = request.getParameter("date");
String edate = request.getParameter("edate");
String strar[] = date.split("-");
String strar2[] = edate.split("-");
String cdate = strar[2]+"-" + strar[0]+"-"+ strar[1];
String ldate = strar2[2]+"-" + strar2[0]+"-"+ strar2[1];
String query =
"select sum(emp_salary)
from sumcount where date>='"+cdate+"' and date<='"+ldate+"'";
System.out.println("query " + query);
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next())
{
sumcount = rs.getInt(1);
}
request.setAttribute("sumcount",sumcount);
Page 126
request.setAttribute("sdate",date);
request.setAttribute("edate",edate);
String nextJSP = "/result_count.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
out.println(query);
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Save the above file into "sum\WEB-INF\classes" directory.
Step 3: Mapping the servlet (sumcount.java) in to web.xml file:
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<display-name>Welcome to Tomcat</display-name>
<description>
Welcome to Tomcat
</description>
<servlet>
<servlet-name>sumcount</servlet-name>
<servlet-class>sumcount</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sumcount</servlet-name>
<url-pattern>/sumcount</url-pattern>
Page 127
</servlet-mapping>
</web-app>
Step 4: Now compile the java code using javac command from command prompt.
Step 5:Create a Bean File (SumCountBean.java) for mapping the result data.
package com;
public class SumCountBean {
private int sumCount;
private String sdate="";
private String edate="";
public void setSumCount(int sumCount)
{
this.sumCount = sumCount;
}
public int getSumCount() {
return sumCount;
}
public void setSdate(String sdate)
{
this.sdate = sdate;
}
public String getSdate() {
return sdate;
}
public void setEdate(String edate)
{
this.edate = edate;
}
public String getEdate() {
return edate;
}
}
Page 128
Successful Output of the program:
Download the full web application shows here.
Download the application
Combo Box Using Ajax In JSP
In this section, we develop an application to Select the Data from database using Ajax in combo box. We
created two filecombo.jsp and getuser.jsp. When a web page ("combo.jsp") run on browser then it will
having a Select Box Employee Id.On select emp id data come
from database corresponding this id and auto fill the Emp Id and Employee Name.
Step 1: Create a web page(combo.jsp) to show a form.
<%@ page import="java.sql.*" %>
<html>
Page 129
<head>
<style>
A:hover {text-decoration: none;
border: 0px;
font-size:14pt;
color: #2d2b2b; }
</style>
<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript">
function showEmp(emp_value)
{
if(document.getElementById("emp_id").value!="-1")
{
xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request")
return
}
var url="getuser.jsp"
url=url+"?emp_id="+emp_value
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
else
{
alert("Please Select Employee Id");
}
}
Page 130
function stateChanged()
{
document.getElementById("ename").value ="";
document.getElementById("emp_id").value ="";
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
{
var showdata = xmlHttp.responseText;
var strar = showdata.split(":");
if(strar.length==1)
{
document.getElementById("emp_id").focus();
alert("Please Select Employee Id");
document.getElementById("ename").value =" ";
document.getElementById("emp_id").value =" ";
}
else if(strar.length>1)
{
var strname = strar[1];
document.getElementById("emp_id").value= strar[2];
document.getElementById("ename").value= strar[1];
}
}
}
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
Page 131
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body>
<form name="employee">
<br><br>
<table border="0" width="400px" align="center" bgcolor="#CDFFFF">
<div id="mydiv"></div>
<tr><td><b>Select Employee Id</b></td><td>
<select name="semp_id" onchange="showEmp(this.value);">
<option value="-1">Select</option>
<%
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
int sumcount=0;
Page 132
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select * from employee_details";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
%>
<%
while(rs.next())
{
%>
<option value="<%=rs.getString(1)%>"><
%=rs.getString(1)%></option>
<%
}
%>
<%
}
catch (Exception e) {
e.printStackTrace();
}
%>
</select>
</td></tr>
<tr><td ><b>Employee Id:</b></td><td>
<input type="text" name="emp_id" id="emp_id" value=""></td></tr>
<tr><td><b>Employee Name:</b></td><td>
Page 133
<input type="text" name="emp_name" id="ename" value=""></td></tr>
</table>
</form>
<table border="0" width="100%" align="center">
<br>
<br>
</table>
</body>
</html>
Step:2Create a web page (getuser.jsp) to retireve the data from database.
<%@ page import="java.sql.*" %>
<%
String emp_id = request.getParameter("emp_id").toString();
String data ="";
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select * from employee_details where
eid='"+emp_id+"'";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
data = ":" + rs.getString(2) + " " + rs.getString(3) +":"+
Page 134
emp_id;
}
out.println(data);
}
catch (Exception e) {
e.printStackTrace();
}
%>
Successful Output of the program:
Download the full web application shows here.
Download the application
To Upload and insert the file into Database with Current Date and Time In JSP
In this tutorial, you will learn how to upload a file through JSP and insert it into the database. For this, we
have created two jsp pages page.jsp and upload_page.jsp. The page.jsp is created for presentation
Page 135
where a file component is created to let the user select the file to be uploaded and a button to submit the
request. The action is performed on upload_page.jsp. Before proceeding further, we need table in
database. We created table named 'file' for our example.
Step 1 : Create a Table structure for file
CREATE TABLE `file_tbl` (`id` bigint(20) NOT NULL auto_increment,`file_data` text,`file_date` datetime default NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Table "file" is created.
Step 2:Create a Page ("page.jsp") To Upload a file.
<%@ page language="java" %><HTml><HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>
<BODY> <FORM ENCTYPE="multipart/form-data" ACTION="upload_page.jsp" METHOD=POST><br><br><br><center><table border="0" bgcolor=#ccFDDEE><tr><center><td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td></tr><tr>
Page 136
<td colspan="2" align="center"> </td></tr><tr><td><b>Choose the file To Upload:</b></td><td><INPUT NAME="file" TYPE="file"></td></tr><tr><td colspan="2" align="center"> </td></tr><tr><td colspan="2" align="center"><INPUT TYPE="submit" VALUE="Send File" ></td></tr><table></center> </FORM></BODY></HTML>
Step 3: Create a page of upload_page.jsp to upload and insert the file in database with current
date and time.
<%@ page import="java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %><html><%int val =0;String contentType = request.getContentType();if ((contentType != null) &&
Page 137
(contentType.indexOf("multipart/form-data") >= 0)) {DataInputStream in = new DataInputStream(request.getInputStream());int formDataLength = request.getContentLength();byte dataBytes[] = new byte[formDataLength];int byteRead = 0;int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {byteRead = in.read(dataBytes, totalBytesRead, formDataLength);totalBytesRead += byteRead;}String file = new String(dataBytes);String saveFile = file.substring(file.indexOf("filename=\"") + 10);System.out.println("saveFile=" + saveFile);saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));System.out.println("saveFile" + saveFile);saveFile = file.substring(file.indexOf("filename=\"") + 10);saveFile = saveFile.substring(0, saveFile.indexOf("\n"));saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));int lastIndex = contentType.lastIndexOf("=");String boundary = contentType.substring(lastIndex + 1,contentType.length());int pos;
pos = file.indexOf("filename=\"");pos = file.indexOf("\n", pos) + 1;pos = file.indexOf("\n", pos) + 1;pos = file.indexOf("\n", pos) + 1;int boundaryLocation = file.indexOf(boundary, pos) - 4;int startPos = ((file.substring(0, pos)).getBytes()).length;int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
FileOutputStream fileOut = new FileOutputStream(saveFile);fileOut.write(dataBytes, startPos, (endPos - startPos));%>
Page 138
<%Connection con=null;PreparedStatement pstatement = null;String line = null;String value=null;String url = "jdbc:mysql://localhost:3306/";String dbName = "file_upload";String driver = "com.mysql.jdbc.Driver";String userName = "root"; String password = "root";try{StringBuilder contents = new StringBuilder();BufferedReader input = new BufferedReader(new FileReader(saveFile));while (( line = input.readLine()) != null){contents.append(line);}value = contents.toString();System.out.println("Value:"+value);Class.forName("com.mysql.jdbc.Driver");con = DriverManager.getConnection(url+dbName,userName,password);java.util.Date now = new java.util.Date();String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);String strDateNew = sdf.format(now) ;
String queryString = "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'";
//out.println(queryString);
pstatement=con.prepareStatement(queryString);
val = pstatement.executeUpdate();
if(val>0){%>
Page 139
<br><br><b>File <% out.println(saveFile); %> has been uploaded and inserted into Database at <%=strDateNew%>.</b><%}
}catch(Exception e){}}%></html>
This file upload and insert into database with current date and time using JDBC database. This can be
done
(i). To import java.io.*,java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat packages. Java.io
Packages is used to read and write the file uploaded having classes like DataInputStream,
FileOutputStream etc. java.util.*,java.text.*,java.text.SimpleDateFormat is used to retireve the current
Date and Time.
(ii). Prepared Statement is used to insert the data into database having used
pstatement=con.prepareStatement(queryString);
(iii). Using a Query "INSERT INTO file_tbl set file_data='"+value+"',file_date='"+strDateNew+"'" to insert
the data into database.
Step 4: Output when file upload and insert into database with current date and time.
Table Structure after file Upload :
A message has been displayed on the browser.
Page 140
The file is inserted into the database with current date and time.
Download the Code
Calendar In JSP Using JavaScript
In this section, we develop a Calendar application in JSP using JavaScript. We created the following files
for the application:
1. emp_event.jsp
2. viewevent.jsp
3. eventdisp.jsp and
4. emp_event.java
Brief description of the flow of the application:
User opens emp_event.jsp in the browser and clicks on "Save" button.
Import datepicker.js to include a date picker in emp_event.jsp.
Servlet emp_event.java inserts the data into the database and redirects to viewevent.jsp.
Add the Event Description on the particular date and having a link "Click here To Show Event"..
Open a viewevent.jsp in the browser and select Employee Id, date and click on "Show" button.
New Pop window eventdisp.jsp opens which displays the description of event on corresponding
date.
Step 1: Create a web page(emp_event.jsp) to save the event description.
<%@ page import="java.sql.*" %>
<html>
<head>
<style>
A:hover {text-decoration: none;
Page 141
border: 0px;
font-size:14pt;
color: #2d2b2b; }
</style>
<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript" src="datepicker.js"></script>
<script>
function validate()
{
var sdate = document.frm.date.value;
var sdateAr=sdate.split("-");
if(document.frm.date.value=="")
{
alert("Please enter the date.");
document.frm.date.focus();
return false;
}
if(sdateAr.length!=3)
{
alert("Please enter valid Date in
mm-dd-yyyy format.");
document.frm.date.value="";
document.frm.date.focus();
return false;
}
if(document.frm.event_description.value=="")
{
alert("Please enter the event description.");
document.frm.event_description.focus();
return false;
}
return true;
Page 142
}
</script>
</head>
<body>
<br><br><br>
<form method="post" name="frm" action="empevent" onsubmit=
"return validate();"><table border="0" width="400px" align="center"
bgcolor="#CDFFFF">
<tr><td colspan=2 style="font-size:10pt;color:#ff0000;"
align="center"></td></tr><tr><td colspan=2 style="font-
size:12pt;color:#00000;" align="center">
<h3>Employee Event</h3></td></tr>
<tr><td> </td></tr>
<tr><td ><b>Date:</b></td><td><input type="text" name="date"
id="cdate"><input type=button value="Select Date" onclick=
"displayDatePicker('date', this);"></td></tr>
<tr><td><b>Description:</b></td><td>
<textarea name="event_description" rows="5" cols="25">
</textarea></td></tr><tr><td> </td></tr>
<tr><td colspan=2 align="center"><input
type="submit" name="submit" value="Save"></td></tr>
</table>
</form>
<table border="0" width="100%" align="center">
<br>
<br>
<tr>
<td width="100%" align="center">
<a href="viewevent.jsp" style="font-size:14pt;color:blue;"
Page 143
>Click here to Show Event</a></td>
</tr>
</table>
</body>
</html>
Step:2Create a Servlet "emp_event.java" and insert data into database.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
public class emp_event extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
Statement st;
try {
Class.forName(driver).newInstance();
conn =
DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the
database");
String date = request.getParameter("date");
Page 144
String event_description =
request.getParameter("event_description");
String strar[] = date.split("-");
String cdate = strar[2]+"-" + strar[0]+"-"+
strar[1];
String query = "insert into emp_event set
date_of_event='"+cdate+"',event_description='"+event_description+"'";
System.out.println("query " + query);
out.println("query " + query);
st = conn.createStatement();
int i = st.executeUpdate(query);
if(i>0)
{
response.sendRedirect("viewevent.jsp");
}
else
{
response.sendRedirect("emp_event.jsp");
}
out.println(query);
conn.close();
System.out.println("Disconnected from
database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step 3:Create a web page (viewevent.jsp) to select the date and employee id.
Page 145
<%@ page import="java.sql.*" %>
<html>
<head>
<style>
A:hover {text-decoration: none;
border: 0px;
font-size:14pt;
color: #2d2b2b; }
</style>
<link rel="stylesheet" type="text/css" href="datepicker.css"/>
<script type="text/javascript" src="datepicker.js"></script>
<script>
function validate()
{
if(document.getElementById("emp_id").value==-1)
{
alert("Please select employee id");
return false;
}
if(document.getElementById("date").value=="")
{
alert("Please enter date");
return false;
}
return true
}
function mywin()
{
if(validate()) {
var date = document.getElementById("date").value;
var emp_id = document.getElementById("emp_id").value;
var page = "eventdisp.jsp?date="+date + "&emp_id="+emp_id;
windo
w.open(page,'mywindow','width=500,height=350,toolbar=no,resizable=yes,menubar=
Page 146
yes');
}
}
</script>
</head>
<body>
<br><br><br>
<form method="post" name="frm" action="empevent">
<table border="0" width="400px" align="center" bgcolor="#CDFFFF">
<tr><td colspan=2 style="font-size:12pt;color:#00000;"
align="center"><h3>Select Event</h3></td></tr>
<tr><td colspan=2> </td></tr>
<tr><td ><b>Employee Id</b></td><td>
<select name="emp_id" id="emp_id">
<option value=-1>Select</option>
<%
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select * from emp_event order by emp_id";
out.println("query "+query);
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
out.println("dkfhdsf");
while(rs.next()){
%>
<option value=<%=rs.getInt(1)%>><%=rs.getInt(1)%></option>
Page 147
<%
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
</select>
</td></tr>
<tr><td ><b>Date:</b></td><td><input type="text" name="date" id="date">
<input type=button value="Select Date" onclick="displayDatePicker('date',
this);">
</td></tr>
<tr><td> </td></tr>
<tr><td colspan=2 align="center"><input type="button" name="show"
value="Show" onclick="mywin();"></td></tr>
</table>
</form>
</body>
</html>
Step 4:Create a web page eventdisp.jsp to show the Event Description.
<%@ page import="java.sql.*" %>
<br><br>
<span style='padding-left:150px;'><b>Event Description</b></span>
<%
int emp_id =
Integer.parseInt(request.getParameter("emp_id").toString());
String date = request.getParameter("date").toString();
String strar[] = date.split("-");
String edate = strar[2]+"-" + strar[0]+"-"+
strar[1];
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
Page 148
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
int sumcount=0;
Statement st;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
String query = "select * from emp_event where emp_id="+emp_id+"
and date_of_event='"+edate+"'";
st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
if(rs.next()){
%>
<p style="color:#000000;border:1px solid #000000;background-
color:#CDFFFF;"><%=rs.getString(3)%></p>
<%
}
else{
%>
<p style="color:#000000;border:1px solid #000000;background-
color:#CDFFFF;text-align:center">No Description</p>
<%
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
<span style='padding-left:150px;'><a href="javascript:window.close()">Window
Close</a> </span>
Successful Output of the program:
Click on Save To add Event Description:
Page 149
Click on Show To Select Event Description:
Display the Event Description:
Download the full web application from here.
Download the application
Page 150
Popup Window using Ajax In JSP
In this section, we will develop a Popup Window application using Ajax in JSP. For this, we will create the
following files for the application:
1. EmployeeDetail.jsp
2. winopenradio.jsp
3. getuser.jsp
4. process.jsp
5. InsertData.jsp
6. DeleteRow.jsp
7. ModifyForm.jsp
8. Modout.jsp
9. QueryAction.jsp
Brief description of the flow of the application:
Open EmployeeDetail.jsp in the browser and click on "View Database" button.
New Pop window winopenradio.jsp will open which will display the employee id and employee
name.
Import getuser.jsp to display all data from database.
Here is the code of this Application:
Step 1: Create a web page ("EmployeeDetail.jsp").
<%@ page language="java" %><%@ page import="java.lang.*" %><%@ page import="java.sql.*" %>
<html><head>
Page 151
</head><body BGCOLOR="LIGHTYELLOW"><form NAME="form" METHOD="GET" ACTION="process.jsp"><H3><P ALIGN="CENTER"> <FONT SIZE=6> EMPLOYEE DETAILS </FONT> </P></H3></BR>
<table cellspacing=5 cellpadding=5 bgcolor="lightblue" colspan=2 rowspan=2 align="center"><TR><TD> <font SIZE=5> Enter Employee ID </TD><TD> <input TYPE="text" name="empid" id="emp_id"> </TD> <TD> <input TYPE="button" NAME="s1" VALUE="View Database" onClick="window.open('winopenradio.jsp','mywindow','width=500,height=350,toolbar=no,resizable=yes,menubar=yes')"></font> </TD></TR><TR><TD> <font SIZE=5> Enter Employee Name </TD><TD><INPUT TYPE="TEXT" NAME="empname" id="emp_name"></FONT> </TD></TR><TR><TD> <FONT SIZE=5> Enter New Name (For UPDATE only) </TD><TD><INPUT TYPE="TEXT" NAME="nname"> </FONT> </TD></FONT> </TR><TR> <FONT SIZE=6><TD> <INPUT TYPE="SUBMIT" NAME="r1" VALUE="Insert"><INPUT TYPE="SUBMIT" NAME="r1" VALUE="Delete"><INPUT TYPE="SUBMIT" NAME="r1" VALUE="Update"><INPUT TYPE="SUBMIT" NAME="r1" VALUE="Query"> </TD></TR> </FONT><%if(session.getAttribute("empcode") !=null && session.getAttribute("empname") !=null) { %><script language="javascript">document.getElementById('id').value=<%=session.getAttribute("empcode").toString()%>document.getElementById('name').value='<%=session.getAttribute("empname").toString()%>'</script><%session.removeAttribute("empcode");session.removeAttribute("empname");}
%>
Page 152
</form></body></html>
Step 2: Create the data display action file ("winopenradio.jsp") for showing the employee id and
employee name.
<%@ page import="java.sql.*" %> <html><head><script type="text/javascript">function trim(stringToTrim) {return stringToTrim.replace(/^\s+|\s+$/g,"");}
function validate(){var emp_value ="";for (var i=0; i < document.employee.empid.length; i++){if (document.employee.empid[i].checked){var emp_value = document.employee.empid[i].value;}}if(emp_value=="" || emp_value==null){alert("Please select Employee Id");return false;}return true}function showEmp(){ if(validate()){for (var i=0; i < document.employee.empid.length; i++){if(document.employee.empid[i].checked){var emp_value = document.employee.empid[i].value;}}xmlHttp=GetXmlHttpObject();if (xmlHttp==null){alert ("Browser does not support HTTP Request")
Page 153
return}var url="getuser.jsp"url=url+"?emp_id="+emp_value;xmlHttp.onreadystatechange=stateChanged xmlHttp.open("GET",url,true)xmlHttp.send(null)}}function stateChanged(){ if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ var showdata = xmlHttp.responseText; var strar = trim(showdata).split(":");if(strar.length>0){window.opener.location.reload();window.location.reload(); opener.document.getElementById("emp_id").value=strar[1];opener.document.getElementById("emp_name").value=strar[2];
window.close();}}}function GetXmlHttpObject(){var xmlHttp=null;try{// Firefox, Opera 8.0+, SafarixmlHttp=new XMLHttpRequest();}catch (e){//Internet Explorertry{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}}return xmlHttp;}</script>
Page 154
</head><body><form name="employee"><br><br><table border="0" width="400px" align="center" bgcolor="#CDFFFF"><tr><td align="center" colspan=2><b>Select Employee Id</b></td></tr><%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
int sumcount=0; Statement st;try{Class.forName(driver).newInstance();con = DriverManager.getConnection(url+db,userName,password);String query = "select * from Employee";st = con.createStatement();ResultSet rs = st.executeQuery(query);%>
<%while(rs.next()){%><tr><td align="center" width="50%"><input type="radio" name="empid" value=<%=rs.getString(1)%>><%=rs.getString(1)%></td><td width="50%"><%=rs.getString(3)%></td></tr><%}%><%}catch (Exception e) {e.printStackTrace();}%><tr><td align="center" width="50%">
Page 155
<input type="button" value="Select" onclick="javascript:showEmp();"</td></tr></table></form></body></html>
Step 3: Create ("getuser.jsp") file for getting employeeid from database using JDBC Database.
<%@ page import="java.sql.*" %> <%String emp_id = request.getParameter("emp_id").toString();String data ="";
Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
int sumcount=0; Statement st;
try {Class.forName(driver).newInstance();con = DriverManager.getConnection(url+db,userName,password);String query = "select * from Employee where eid='"+emp_id+"'";st = con.createStatement();ResultSet rs = st.executeQuery(query);while(rs.next()){data = ":" + rs.getString(2) + ":" + rs.getString(3) +":"+ emp_id;}out.println(data.trim());}catch (Exception e){e.printStackTrace();}%>
Page 156
Step 4: Create "Process.jsp" for Processing the Data and forward it according to user
requirement.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<%String str=request.getParameter("r1");String name=request.getParameter("empname");String code=request.getParameter("empid");
if(str.equals("Insert")) {%><jsp:forward page="InsertData.jsp" /><%}else if(str.equals("Delete")) {%><jsp:forward page="DeleteRow.jsp" /><%}else if(str.equals("Update")) {%><jsp:forward page="ModifyForm.jsp" /><%}else if(str.equals("Query")) {%><jsp:forward page="QueryAction.jsp" /><%}else {%><jsp:forward page="Noresponse.html" /><%}%>
Page 157
Step 5: Create the "InsertData.jsp" file for Inserting data into database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %><%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
String str=request.getParameter("r1");String empname=request.getParameter("empname");String code=request.getParameter("empid");out.println(empname);out.println(code);
try {Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);PreparedStatement pst = con.prepareStatement("insert into Employee values(?,?,?)");pst.setString(1,"545EE");pst.setString(2,"fghbfgbf");pst.setString(3,"fghfgh12");int i = pst.executeUpdate();if(i!=0){out.println("<br>Record has been inserted");}else{out.println("failed to insert the data");}}catch(Exception e) {out.println(e.toString());}%>
Step 6: Create "DeleteRow.jsp" file for deleting the row from database using JDBC database.
Page 158
<%@ page language="java" import="java.lang.*" import="java.sql.*" %><%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
String str=request.getParameter("r1");String name=request.getParameter("empname");String code=request.getParameter("empid");int EmpID=Integer.parseInt(code);
try {Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);String sql = "delete from Employee where empid= ?";PreparedStatement prest = con.prepareStatement(sql);prest.setInt(1,EmpID);int i = prest.executeUpdate();out.println("Successfully delete from database!");con.close();}catch(Exception e) {out.println(e);} %>
Step 7: Create modify file ("ModifyForm.jsp") .
<html><body bgcolor="lightyellow"><FORM NAME="f1" ACTION="Modout.jsp"><%String empname =request.getParameter("empname");String code=request.getParameter("empid");int empid=Integer.parseInt(code);%><P ALIGN="CENTER"> <FONT SIZE=6> Old Name is <%= empname %> </FONT>
Page 159
</BR> </BR> </BR> </P><TABLE CELLSPACING=5 CELLPADDING=5 BGCOLOR="LIGHTBLUE" COLSPAN=2 ROWSPAN=2 ALIGN="CENTER"><TR> <TD> <FONT SIZE=5> Enter New Name </TD><input type="hidden" name="id" value="<%=empid%>"/><TD> <INPUT TYPE="TEXT" NAME="newname"> </TD> </FONT> </TR><TR> <TD> <INPUT TYPE="SUBMIT" VALUE="Modify"> </TD> </TR></form></br></body></html>
Step 8: Create modify action file ("Modout.jsp").
In this step you can update data into database using "Modout.jsp".
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<HTML><BODY BGCOLOR="LIGHTYELLOW"><%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";
String str=request.getParameter("r1");String newname=request.getParameter("newname");String id=request.getParameter("id");System.out.println("MyId: "+newname);
try {Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);String sql = "UPDATE Employee SET empname = ? WHERE empid = ?";PreparedStatement prest = con.prepareStatement(sql);prest.setString(1,newname);
Page 160
prest.setInt(2,Integer.parseInt(id));
prest.executeUpdate(); out.println("Updating Successfully!"); }catch(Exception e) {out.println(e);}%></BODY></HTML>
Step 9: In this step you will learn, how to retrieve data from database.
<%@ page language="java" import="java.lang.*" import="java.sql.*" %>
<%Connection con = null;String url = "jdbc:mysql://192.168.10.211:3306/";String db = "amar";String driver = "com.mysql.jdbc.Driver";String userName ="amar";String password="amar123";String str=request.getParameter("r1");String name=request.getParameter("name");String code=request.getParameter("empid");
int EmpID=Integer.parseInt(code);try {Class.forName(driver);con = DriverManager.getConnection(url+db,userName,password);String query=null;query="SELECT empname FROM Employee where empid= ?";PreparedStatement prest = con.prepareStatement(query);prest.setInt(1, EmpID);ResultSet rs = prest.executeQuery();out.println("<B> <CENTER> EMPLOYEE NAME </CENTER> </B>");ResultSetMetaData rsmd=rs.getMetaData();
Page 161
int colcount=rsmd.getColumnCount();out.println("<TABLE ALIGN=CENTER BORDER=1 CELLPADDING=2>");out.println("<TR>");for(int i=1;i<=colcount;i++) {out.println("<TH>" +rsmd.getColumnLabel(i)+ "</TH>");out.println("<TR>");while(rs.next()){out.println("<TD>" +rs.getString("empname")+ "</TD>");}out.println("</TABLE>");out.println("</BODY>");con.close();}}catch(Exception e){out.println(e.toString());}%>
Here is the successfully Output:
When you click on View Database button, popup Window will be displayed.
Page 162
Select the radio button. If you have not selected radio button, a massage will display like this.
Page 164
Download Application
User Registration Form Using JSP(JspBeans)
In this section you will learn about the handling of user registration form using jsp. One of the basic
programming tactics of jsp is to assign as much processing as possible to java Bean component. It will
not only provide basic data validation for the registration information input by a user, but will also exhibit
stateful behavior.
Step 1: Create a simple registration form (register.html):
<html><body ><form action="/examples/jsp/proces.jsp" method=post><center><table cellpadding=2 cellspacing=1 border="1" bgcolor="lightblue"><th bgcolor="lightblue" colspan=2><font size=5>User Registration</font><br><font size=2 color="red"><sup>*</sup> Required Fields</font></th><tr bgcolor="lightblue"><td valign=top> <b>First Name<sup>*</sup></b> <br>
Page 165
<input type="text" name="firstName" value="" size=20 maxlength=20></td><td valign=top><b>Last Name<sup>*</sup></b><br><input type="text" name="lastName" value="" size=15 maxlength=20></td></tr><tr bgcolor="lightblue"><td valign=top><b>E-Mail<sup>*</sup></b> <br><input type="text" name="email" value="" size=25 maxlength=125><br></td><td valign=top><b>Zip Code<sup>*</sup></b> <br><input type="text" name="zip" value="" size=10 maxlength=8></td></tr><tr bgcolor="lightblue"><td valign=top colspan=2><b>User Name<sup>*</sup></b><br><input type="text" name="userName" size=20 value="" maxlength=10></td></tr><tr bgcolor="lightblue"><td valign=top><b>Password<sup>*</sup></b> <br><input type="password" name="password1" size=10 value="" maxlength=10></td><td valign=top><b>Confirm Password<sup>*</sup></b><br><input type="password" name="password2" size=10 value="" maxlength=10></td><br></tr><tr bgcolor="lightblue"><td valign=top colspan=2><b>What Technology are you interested in?</b><br>
Page 166
<input type="checkbox" name="faveTech" value="Java">Java <input type="checkbox" name="faveTech" value="JSP">JSP <input type="checkbox" name="faveTech" value="Struts 1.1">Struts 1.1<br><input type="checkbox" name="faveTech" value="Ajax">Ajax <input type="checkbox" name="faveTech" value="Struts 2.0 ">Struts 2.0 <input type="checkbox" name="faveTech" value="Servlets">Servlets<br></td></tr><tr bgcolor="lightblue"><td valign=top colspan=2><b>Would you like to receive e-mail notifications on our special sales?</b><br><input type="radio" name="notify" value="Yes" checked>Yes
<input type="radio" name="notify" value="No" > No <br><br></td></tr><tr bgcolor="lightblue"><td align=center colspan=2><input type="submit" value="Submit"> <input type="reset" value="Reset"></td></tr></table></center></form></body></html>
Step2: These pages would still specify the bulk of the processing to component beans, but they would
also contain some conditional logic to respond to a user's actions. But these controller pages would never
contain presentation logic to display UI elements. This task would always be externalized into separate
JSPs, which will be invoked as needed by the controller.
<%@ page language="java" %><%@ page import="java.util.*" %><%! %>
Page 167
<jsp:useBean id="formHandler" class="test.FormBean" scope="request"><jsp:setProperty name="formHandler" property="*"/></jsp:useBean><% if (formHandler.validate()) {%><jsp:forward page="success.jsp"/><%} else {%><jsp:forward page="retry.jsp"/><%}%>
Step3: In this step when developing beans for processing form data, you can follow a common design
pattern by matching the names of the beans properties with the names of the form input elements. you
would also need to define the corresponding getter and setter methods for each property within the bean.
package test;
import java.io.*;import java.util.*;
public class FormBean {private String firstName;private String lastName;private String email;private String userName;private String password1;private String password2;private String zip;private String[] faveTech;private String notify;private Hashtable errors;public boolean validate() {boolean bool=true;
Page 168
if (firstName.equals("")) {errors.put("firstName","Please enter your first name");firstName="";bool=false;}if (lastName.equals("")) {errors.put("lastName","Please enter your last name");lastName="";bool=false;}if (email.equals("") || (email.indexOf('@') == -1)) {errors.put("email","Please enter a valid email address");email="";bool=false;}if (userName.equals("")) {errors.put("userName","Please enter a username");userName="";bool=false;}if (password1.equals("") ) {errors.put("password1","Please enter a valid password");password1="";bool=false;}if (!password1.equals("") && (password2.equals("") || !password1.equals(password2))) {errors.put("password2","Please confirm your password");password2="";bool=false;}if (zip.equals("") || zip.length() !=6 ) {errors.put("zip","Please enter a valid zip code");zip="";bool=false;} else {try {int x = Integer.parseInt(zip);} catch (NumberFormatException e) {errors.put("zip","Please enter a valid zip code");zip="";
Page 169
bool=false;}}return bool;}public String getErrorMsg(String s) {String errorMsg =(String)errors.get(s.trim());return (errorMsg == null) ? "":errorMsg;}public FormBean() {firstName="";lastName="";email="";userName="";password1="";password2="";zip="";faveTech = new String[] { "1" };notify="";errors = new Hashtable();}public String getFirstName() {return firstName;}public String getLastName() {return lastName;}public String getEmail() {return email;}public String getUserName() {return userName;}public String getPassword1() {return password1;}public String getPassword2() {return password2;}public String getZip() {return zip;
Page 170
}public String getNotify() {return notify;}public String[] getFaveTech() {return faveTech;}public String isCbSelected(String s) {boolean found=false;if (!faveTech[0].equals("1")) {for (int i = 0; i < faveTech.length; i++) {if (faveTech[i].equals(s)) {found=true; break;}}if (found) return "checked";} return "";}public String isRbSelected(String s) {return (notify.equals(s))? "checked" : "";}public void setFirstName(String fname) {firstName =fname;}public void setLastName(String lname) {lastName =lname;}public void setEmail(String eml) {email=eml;}public void setUserName(String u) {userName=u;}public void setPassword1(String p1) {password1=p1;}public void setPassword2(String p2) {password2=p2;}
Page 171
public void setZip(String z) {zip=z;}public void setFaveTech(String[] music) {faveTech=music;}public void setErrors(String key, String msg) {errors.put(key,msg);}public void setNotify(String n) {notify=n;}}
Step 4: Create a "retry.jsp" file for displaying error. If the user submits the form without fulfilling field,
proces.jsp will return on retry.jsp page. The processing logic within the controller page is straight forward.
After the bean is instantiated, its validate() method is invoked. The validate() method has a two-pronged
effect. If an error is encountered during the validation of any form input element, the validate() method not
only resets the value of the corresponding bean property, but also sets an appropriate error message,
which can later be displayed for that input element. If any of the required form elements cannot be
successfully validated, the controller forwards the request to the JSP page retry.jsp allowing the user to
make changes and resubmit the form. If there are no validation errors, the request is forwarded to
success.jsp
<jsp:useBean id="formHandler" class="test.FormBean" scope="request"/><html><body><center><table cellpadding=1 cellspacing=1 border="1" ><th bgcolor="lightblue" colspan=2><font size=5>User Registration Successfull!</font></th><font size=4><tr bgcolor="lightblue"><td valign=top> <b>First Name</b> <br>
Page 172
<jsp:getProperty name="formHandler" property="firstName"/></td><td valign=top><b>Last Name</b><br><jsp:getProperty name="formHandler" property="lastName"/></td></tr><tr bgcolor="lightblue"><td valign=top><b>E-Mail</b> <br><jsp:getProperty name="formHandler" property="email"/><br></td><td valign=top><b>Zip Code</b> <br><jsp:getProperty name="formHandler" property="zip"/></td></tr><tr bgcolor="lightblue"><td valign=top colspan=2><b>User Name</b><br><jsp:getProperty name="formHandler" property="userName"/></td></tr><tr bgcolor="lightblue"><td colspan=2 valign=top><b>What Technology are you interested in?</b><br><%String[] faveTech = formHandler.getFaveTech();if (!faveTech[0].equals("1")) {out.println("<ul>");for (int i=0; i<faveTech.length; i++) out.println("<li>"+faveTech[i]);out.println("</ul>");} else out.println("Nothing was selected");%></td>
Page 173
</tr><tr bgcolor="lightblue"><td colspan=2 valign=top><b>Would you like to receive e-mail notifications on our special sales?</b><br><jsp:getProperty name="formHandler" property="notify"/></td></tr></font></table></center></body></html>
Step5: Create a "success.jsp" file for displaying all data entered by user. As stated earlier, the controller
forwards the request to success.jsp only after all of the submitted form data has been successfully
validated. Success.jsp in turn extracts the bean component from the request and confirms the registration
to the client.
<jsp:useBean id="formHandler" class="test.FormBean" scope="request"/><html> <body><form action="proces.jsp" method=post><center><table cellpadding=4 cellspacing=2 border=0><th bgcolor="lightblue" colspan=2><font size=5>User Registration</font><br><font size=2 color="red"><sup>*</sup> Required Fields </font></th><tr bgcolor="lightblue"><td valign=top> <B>First Name<sup>*</sup></B> <br><input type="text" name="firstName" value='<%=formHandler.getFirstName()%>' size=15 maxlength=20><br><font size=2 color=red><%=formHandler.getErrorMsg("firstName")%></font>
Page 174
</td><td valign=top><B>Last Name<sup>*</sup></B><br><input type="text" name="lastName" value='<%=formHandler.getLastName()%>' size=15 maxlength=20><br><font size=2 color=red><%=formHandler.getErrorMsg("lastName")%></font></td></tr><tr bgcolor="lightblue"><td valign=top><B>E-Mail<sup>*</sup></B> <br><input type="text" name="email" value='<%=formHandler.getEmail()%>' size=25 maxlength=125><br><font size=2 color=red><%=formHandler.getErrorMsg("email")%></font></td><td valign=top><B>Zip Code<sup>*</sup></B> <br><input type="text" name="zip" value='<%=formHandler.getZip()%>' size=5 maxlength=6><br><font size=2 color=red><%=formHandler.getErrorMsg("zip")%></font></td></tr><tr bgcolor="lightblue"><td valign=top colspan=2> <B>User Name<sup>*</sup></B><br><input type="text" name="userName" size=10 value='<%=formHandler.getUserName()%>' maxlength=10><br><font size=2 color=red><%=formHandler.getErrorMsg("userName")%></font></td></tr><tr bgcolor="lightblue"><td valign=top><B>Password<sup>*</sup></B> <br><input type="password" name="password1" size=10
Page 175
value='<%=formHandler.getPassword1()%>' maxlength=10><br><font size=2 color=red><%=formHandler.getErrorMsg("password1")%></font></td><td valign=top><B>Confirm Password<sup>*</sup></B><br><input type="password" name="password2" size=10 value='<%=formHandler.getPassword2()%>' maxlength=10><br><font size=2 color=red><%=formHandler.getErrorMsg("password2")%></font></td><br></tr><tr bgcolor="lightblue"><td colspan=2 valign=top><B>What Technology are you interested in?</B><br><input type="checkbox" name="faveTech" value="Java"<%=formHandler.isCbSelected("Java")%>>Java <input type="checkbox" name="faveTech" value="JSP" <%=formHandler.isCbSelected("JSP")%>>JSP <input type="checkbox" name="faveTech" value="Struts 1.1" <%=formHandler.isCbSelected("Struts 1.1")%>>Struts 1.1<br><input type="checkbox" name="faveTech" value="Ajax" <%=formHandler.isCbSelected("Ajax")%>>Ajax <input type="checkbox" name="faveTech" value="Struts 2.0" <%=formHandler.isCbSelected("Struts 2.0")%>>Struts 2.0 <input type="checkbox" name="faveTech" value="Servlets" <%=formHandler.isCbSelected("Servlets")%>>Servlets<br></td></tr><tr bgcolor="lightblue"><td colspan=2 valign=top><B>Would you like to receive e-mail notifications on our special sales?</B><br><input type="radio" name="notify" value="Yes" <%=formHandler.isRbSelected("Yes")%>>Yes <input type="radio" name="notify" value="No" <%=formHandler.isRbSelected("No")%>> No
Page 176
<br><br></td></tr><tr bgcolor="lightblue"><td colspan=2 align=center><input type="submit" value="Submit"> <input type="reset" value="Reset"></td></tr></table></center></form></body></html>
Here is the successfully Output:
Page 179
Download the Application
Login Authentication using Bean and Servlet In JSP
In this section, we have developed a web application of login authentication using Bean in JSP. Five files
are used "login.jsp", "loginbean.jsp", "welcome.jsp","LoginBean.java" and "login.java" in the code
given below.
Brief description of the flow of application :
1). Create a webpage "login.jsp" to login the user.
2). Create a webpage "loginbean.jsp" to set the parameter using JSP Bean and forward to the Servlet
page.
3). Create a bean file "LoginBean.java" to mapping the parameter from "loginbean.jsp".
Page 180
4). Create a Servlet "login.java" to validate the username and password from the database.
5). Create a webpage "welcome.jsp" display a message after successfully user login.
Step:1 Create a web page "login.jsp" to login the user.
<html>
<head>
</head>
<body>
<form name="loginform" method="post" action="loginbean.jsp">
<br><br>
<table align="center"><tr><td><h2>Login Authentication</h2></td></tr></table>
<table width="300px" align="center" style="border:1px solid
#000000;background-color:#efefef;">
<tr><td colspan=2></td></tr>
<tr><td colspan=2> </td></tr>
<tr>
<td><b>Login Name</b></td>
<td><input type="text" name="userName" value=""></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="password" value=""></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
<tr><td colspan=2> </td></tr>
</table>
</form>
</body>
</html>
Page 181
Step:2 To create a "loginbean.jsp" to set the parameter of the login.
<%@ page language="Java" import="java.sql.*" %>
<HTML>
<HEAD><TITLE>DataBase Search</TITLE></HEAD>
<BODY>
<jsp:useBean id="db" scope="request" class="logbean.LoginBean" >
<jsp:setProperty name="db" property="userName" value="<
%=request.getParameter("userName")%>"/>
<jsp:setProperty name="db" property="password" value="<
%=request.getParameter("password")%>"/>
</jsp:useBean>
<jsp:forward page="hello">
<jsp:param name="username" value="<%=db.getUserName()%>" />
<jsp:param name="password" value="<%=db.getPassword()%>" />
</jsp:forward>
</body>
</html>
Step:3 To create a "LoginBean.java" to mapping the parameter of "loginbean.jsp".
package logbean;
public class LoginBean {
String userName="";
String password="";
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
Page 182
this.password = password;
}
}
Step:4 To create a Servlet "login.java" for validate the user login.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.sql.*;
import java.sql.*;
public class login extends HttpServlet{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "root";
String username="";
String userpass="";
String strQuery= "";
Statement st=null;
ResultSet rs=null;
HttpSession session = request.getSession(true);
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
if(request.getParameter("username")!=null &&
request.getParameter("username")!="" && request.getParameter("password")!
=null &&
Page 183
request.getParameter("password")!="")
{
username = request.getParameter("username").toString();
userpass = request.getParameter("password").toString();
strQuery="select * from userregister where
username='"+username+"' and password='"+userpass+"'";
System.out.println(strQuery);
st = conn.createStatement();
rs = st.executeQuery(strQuery);
int count=0;
while(rs.next())
{
session.setAttribute("username",rs.getString(2));
count++;
}
if(count>0)
{
response.sendRedirect("welcome.jsp");
}
else
{
response.sendRedirect("login.jsp");
}
}
else
{
response.sendRedirect("login.jsp");
}
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
Page 184
}
}
Step :5 To create the webpage "welcome.jsp" to display the message after successful message.
<HTML>
<HEAD><TITLE>Welcome</TITLE></HEAD>
<BODY>
<br><br><br><br>
<table align="center" style="border:1px solid #000000;">
<%
if(session.getAttribute("username")!=null && session.getAttribute("username")!
="")
{
String user = session.getAttribute("username").toString();
%>
<tr><td align="center"><h1>Welcome <b><%= user%></b></h1></td></tr>
<%
}
%>
</table>
</body>
<html>
Output:
Login Authentication form :
Page 185
After Successful Login user :
Download the application
Record user login and logout timing In JSP
In this section, we have developed a web application of maintain record of the user Login and Logout
Time in JSP. Six files are used "home.jsp","login.jsp", "userloginmid.jsp",
"welcome.jsp","logout.jsp" and "userstatus.jsp" in the code given below.
Page 186
Brief description of the flow of application :
1). Create a webpage "home.jsp" to login the user and show the user login status link.
2). Create a webpage "login.jsp" to login the user.
3). Create a webpage "welcome.jsp" to display a message after successful login.
4). Create a webpage "userstatus.jsp" to display all the Login and Logout User status.
Step:1 Create Table for Database :
"userregister"
create table `userregister` ( `id` double , `username` varchar (50), `password` varchar (50), `first_name` varchar (50), `last_name` varchar (50), `city` varchar (50), `state` varchar (50), `country` varchar (50) );
"admin"
create table `admin` ( `id` double , `userid` double , `intime` datetime , `outtime` datetime );
Step:2 Create a web page "home.jsp" to login and display the user status link.
<HTML>
<HEAD>
<TITLE>Login Application</TITLE>
</HEAD>
Page 187
<BODY>
<br><br><br><br><br>
<table align="center">
<%
if(session.getAttribute("username")!=null &&
session.getAttribute("username")!="")
{
%>
<tr><td align="left"><a href="logout.jsp">Click Here to Logout</a></td></tr>
<%
}
else
{
%>
<tr><td align="left"><a href="login.jsp">Click Here to User
Login</a></td></tr>
<%
}
%>
<tr><td align="left"> </td></tr>
<tr><td align="left"><a href="userstatus.jsp">View Users Logon
status</a></td></tr>
</table>
</BODY>
</HTML>
Step:3 To create a "login.jsp" to login the user
<html>
<head>
</head>
<body>
<br><br><br>
<table align="center" width="400px" border=0>
<tr><td align="right" width="300"><a href="home.jsp">Home</a></td></td></tr>
</table>
Page 188
<table align="center"><tr><td colspan=2><h1>User Login</h2></td></tr></table>
<form name="loginform" method="post" action="userloginmid.jsp">
<table align="center" width="300px" style="border:1px solid #000000;" >
<tr><td colspan=2> </td></tr>
<tr>
<td><b>Login Name</b></td>
<td><input type="text" name="userName" value=""></td>
</tr>
<tr>
<td><b>Password</b></td>
<td><input type="password" name="password" value=""></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit"></td>
</tr>
<tr><td colspan=2> </td></tr>
</table>
</form>
</body>
</html>
Step:4 To create a "welcome.jsp" to display the message after succesful login the user.
<%@ page import="java.sql.*,java.util.*" %>
<html>
<body>
<br><br>
<table align="center" width="300px" border=0>
<%
String username="";
if(session.getAttribute("username")!=null && session.getAttribute("username")!
="")
{
username=session.getAttribute("username").toString();
Page 189
%>
<tr>
<td align="right" width="690"><a href="home.jsp">Home</a></td>
<td align="right"><a href="logout.jsp">Logout</a></td>
</tr>
<%
}
else
{
%>
<tr>
<td align="right"><a href="home.jsp">Home</a></td>
<td align="right"><a href="login.jsp">Login</a></td>
</tr>
<%
}
%>
<tr><td colspan=2> </td></tr>
<tr><td colspan=2><h1>Welcome <%=username%></h1></td></tr>
<table>
</body>
</html>
Step:5 Create a webpage "userstatus.jsp" to display the User Status .
<%@ page
import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<html>
<head>
<TITLE>Login Application</TITLE>
</head>
<body>
<br><br>
<table align="center" width="400px" border=0>
<%
Page 190
if(session.getAttribute("username")!=null &&
session.getAttribute("username")!="")
{
%>
<tr>
<td align="right" width="350"><a href="home.jsp">Home</a></td>
<td align="right"><a href="logout.jsp">Logout</a></td>
</tr>
<%
}
else
{
%>
<tr>
<td align="right" width="350"><a href="home.jsp">Home</a></td>
<td align="right"><a href="login.jsp">Login</a></td>
</tr>
<%
}
%>
</table>
<table width="400px" align="center" border=0>
<tr style="background-color:#D9B0D8;">
<td align="center"><b>User Id</b></td>
<td align="center"><b>Username</b></td>
<td align="center"><b>Login</b></td>
<td align="center"><b>Logout</b></td>
</tr>
<%
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "user_register";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
Page 191
String userPassword = "root";
String user = "";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
Statement st = conn.createStatement();
Statement st1 = conn.createStatement();
String queryString = "select * from admin order by userid";
ResultSet rs = st.executeQuery(queryString);
ResultSet rs1=null;
String queryStringuser="";
SimpleDateFormat sdfDestination=null;
int count=0;
String strcolor = "";
while(rs.next())
{
count = count%2;
if(count==0)
{
strcolor = "#D9D9D9";
}
else
{
strcolor = "#EFEFEF";
}
count++;
queryStringuser = "select * from userregister where id="+rs.getInt(2);
rs1 = st1.executeQuery(queryStringuser);
while(rs1.next())
{
user = rs1.getString(2);
}
String inStr="";
String outStr="";
Page 192
java.util.Date date;
String intime="";
String outtime="";
if((rs.getString(3)!=null && rs.getString(3)!=""))
{
inStr =
r
s.getString(3).toString().substring(0,rs.getString(3).toString().indexOf("."))
;
try
{
date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(inStr);
sdfDestination = new SimpleDateFormat("MMM dd, hh:mm:ss");
intime = sdfDestination.format(date);
}
catch (Exception e)
{
e.getMessage();
}
}
if((rs.getString(4)!=null && rs.getString(4)!=""))
{
outStr =
r
s.getString(4).toString().substring(0,rs.getString(3).toString().indexOf("."))
;
try
{
date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(outStr);
sdfDestination = new SimpleDateFormat("MMM dd, hh:mm:ss");
outtime = sdfDestination.format(date);
}
catch (Exception e)
{
Page 193
e.getMessage();
}
}
%>
<tr style="background-color:<%=strcolor%>;">
<td align="center"><%=rs.getInt(2)%></td>
<td align="left" style="padding-left:10px;"><%=user%></td>
<td align="center"><%=intime%></td><td align="center"><%=outtime%></td>
</tr>
<%
}
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
%>
Output:
Login Authentication form :
Page 194
After Successful Login user :
Status of all the User
Download the full code
Retrieve Data from CSV file in JSP
Page 195
CSV file : A CSV file is commonly known as a Comma Delimited File or a Character Separated File. It is
a text file that has a specific format which allows saving of text in organized manner. This format known
as a flat table, is very simple. Each row contains one record of information. The character used to
distinguish each piece of data within each record is most commonly used a comma ",".
"myfile.csv" in the c:\csv folder
Create a Page ("ReadCsvFile.jsp") to retrieve the data from CSV file "myfile.csv".
<%@ page import="java.io.*"%><html><body><% String fName = "c:\\csv\\myfile.csv"; String thisLine; int count=0; FileInputStream fis = new FileInputStream(fName); DataInputStream myInput = new DataInputStream(fis); int i=0; %><table><%while ((thisLine = myInput.readLine()) != null){String strar[] = thisLine.split(",");for(int j=0;j<strar.length;j++){if(i!=0){out.print(" " +strar[j]+ " ");}else{
Page 196
out.print(" <b>" +strar[j]+ "</b> ");}} out.println("<br>");i++;} %></table></body></html>
Output
Download full source code
Export Data into CSV file uing JDBC in JSP
CSV file : A CSV file is commonly known as a Comma Delimited File or a Character Separated File.
Step : 1 Import the packages .
<%@ page import="java.io.*,java.sql.*"%>
Step : 1 .Create a Table "employee_details" in the database.
Page 197
Step : 2 Create a folder "csv" in the C:\ Drive.
Step : 3.Create a Page ("CsvJdbcFile.jsp") to export data into CSV file "myjdbcfile.csv".
<%@ page import="java.io.*,java.sql.*"%><html><body><%
String filename = "c:\\csv\\myjdbcfile.csv";Connection conn = null;String url = "jdbc:mysql://localhost:3306/";String dbName = "user_register";String driver = "com.mysql.jdbc.Driver";String userName = "root"; String password = "root";Statement stmt;try{FileWriter fw = new FileWriter(filename);fw.append("Employee Code");fw.append(',');fw.append("First Name");fw.append(',');fw.append("Last Name");fw.append('\n');
Class.forName(driver).newInstance();conn = DriverManager.getConnection(url+dbName,userName,password);String query = "select * from employee_details";stmt = conn.createStatement();ResultSet rs = stmt.executeQuery(query);while(rs.next())
Page 198
{fw.append(rs.getString(1));fw.append(',');fw.append(rs.getString(2));fw.append(',');fw.append(rs.getString(3));fw.append('\n');}fw.flush();fw.close();conn.close();out.println("<b>You are Successfully Created Csv file.</b>");} catch (Exception e) {e.printStackTrace();}%></table></body></html>
Output :
After successfully created csv file message is display.
"myjdbcfile.csv"
Download full source code
Page 199
Download CSV File from Database in JSP
In this section, you will learn how to download CSV file from database in JSP. In this example, we have
developed two files "viewcsv.jsp" and "file_download.jsp" , code is given below.
Brief description of the flow of application :
1). Create a webpage "viewcsv.jsp"" to display and download the CSV file from database. All CSV file
will show as hyperlink.
2). Another "file_download.jsp" is used to retrieve CSV file..
Step:1 To create a "file" table in Database.
create table `file` (`id` double ,`file_data` blob ,`file_name` varchar (50))
Step:2 Create a "viewcsv.jsp" to display all the CSV file.
<html>
<body>
<br><br>
<table width="200px" style="border:1px solid #ff0000;background-
Page 200
color:f7f7f7" align="center">
<tr style="font-weight:bold;">
<td align="center" align="center" colspan=2 style="border-bottom: 2px
solid #000000;">Download Csv File</td>
</tr>
<tr style="font-weight:bold;">
<td align="center" style="border-bottom: 2px solid #000000;">Id</td>
<td align="center" style="border-bottom: 2px solid #000000;">File</td>
</tr>
<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<%
String connectionURL = "jdbc:mysql://localhost/application";
String url=request.getParameter("WEB_URL");
String Content=new String("");
Statement stmt=null;
Connection con=null;
try
Page 201
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
stmt=con.createStatement();
String qry = "select * from file";
ResultSet rst= stmt.executeQuery(qry);
while(rst.next())
{
%>
<tr>
<td align="center"><%=rst.getInt(1)%></td>
<td align="center">
<a href="file_download.jsp?id=<%=rst.getInt(1)%>"><
%=rst.getString(3)%></a>
</td>
</tr>
<%
}
Page 202
}
catch(Exception e){
e.printStackTrace();
}
%>
</table>
</body>
</html>
Step:3 To create a web page "file_download.jsp" .
<%@ page import="java.io.*,java.util.*,java.sql.*" %>
<%
int id=0;
if(request.getParameter("id")!=null && request.getParameter("id")!="")
{
id = Integer.parseInt(request.getParameter("id").toString());
}
String connectionURL = "jdbc:mysql://localhost/application";
Page 203
String url=request.getParameter("WEB_URL");
String Content=new String("");
Statement stmt=null;
Connection con=null;
try
{
String filename="data"+id+".csv";
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
stmt=con.createStatement();
String qry = "select * from file where id="+id;
ResultSet rst= stmt.executeQuery(qry);
if(rst.next())
{
Content=rst.getString("file_data");
}
out.println(Content);
Page 204
byte requestBytes[] = Content.getBytes();
ByteArrayInputStream bis = new
ByteArrayInputStream(requestBytes);
response.reset();
response.setContentType("application/text");
response.setHeader("Content-disposition","attachment;
filename=" +filename);
byte[] buf = new byte[1024];
int len;
while ((len = bis.read(buf)) > 0){
response.getOutputStream().write(buf, 0,
len);
}
bis.close();
response.getOutputStream().flush();
}
catch(Exception e){
e.printStackTrace();
}
Page 205
%>
Output:
Display CSV file :
Download the CSV File :
Download the application