Documente Academic
Documente Profesional
Documente Cultură
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 2 of 69
Easy JavaWeb
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 3 of 69
Easy JavaWeb
Acknowledgment
One of the great pleasures of writing Easy JavaWeb and acknowledges the efforts
of many people whose names may not appear on the cover, but their hard work,
cooperation, friendship and understanding the situations are invested to complete
this book smoothly.
I would like to thank many people for helping me to complete this book. First; I
would like to convey my very special thanks to MCA/B.Tech students who have
encouraged me a lot. This book would not be there without them.
I would like to thank Srinivas Rao Bora (Senior Technical Associate, MSS) and
Chandrasekhar Kota (Team Lead, MSS) for their work making me to write Easy
JavaWeb. If you enjoy the flow of the sections, contents, and the clarity, then that
is probably in some part due to tehm. I have started writing this book since the year
2008.
I would like to thank to Mr.Prasad V Lokam, CEO, and MSS. When he is having free
time, he used to look at technical, project discussions and training. He used to tell
that dont throw much theory and learn by examples. I have started this book with
this motto only. I have learned many things from him like the way he is articulating
the things.
I am eager to convey my special thanks to Mr.Arjuna Rao A,Prinicipal,MES and
Ms.Madhavi Lokam,Chairman,MES and entire MES Team.I am very thankful to
Mr.Sankar Sastry Matta,Asst Professior,MES for his heartful support.
Last but not least, I would like to convey my heartfelt thanks to my family members
for their patience and bearing problems with me.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 4 of 69
Easy JavaWeb
Preface
Industry working experience on different dominas using different java/J2EE
technologies, IBM tools and teaching of C and JAVA/J2EE motivated me to write this
book. It is targeted to support the students and software engineers.It will help you to
understand Advanced Java Programming concepts like HTML, CSS, JavaScritp, XML
AJAX, JDBC, Servlets, JSP, Custom Tags, and many advanced topics with
programmatic examples and pictorial explanations.
This book Easy JavaWeb addressed many problems and their solutions provided in
terms of algorithms and programming examples.This book contains scenarios which
are reflecting the real time scenarios. Students/Programmer/Developer tends to do
lots of mistakes while coding.This book providing Points to remember section to
alert the programmers not do any coding mistakes.This book contains many
exercises for each possible topic and you can see answers in next version.
You are having a good opportunity to learn advanced topics in java and J2EE
technologies by learning Easy Java, Easy JavaWeb and Easy J2EE books.
Now onwards, you will get more information from www.javasiva.in related to C&DS,
JAVA, Web technologies, DBMS and all universities B.Tech & MCA courses also. I am
expecting some important points from your side that are missing in this book like any
mistakes, readability problems and etc...Please write all your feedback to my email
and I will inject them to improve our book in all aspects. Thanks to all of my students
and Professors in advance for their support to write this book. The motto of this book
is to give good programming knowledge to meet industry requirements.
I have written some content which is somewhat simulated to many good sites and
their style of articulating the things were adapted. The definition of various software
engineering
terms
and
concepts
were
adapted
from
Wikipedia
(http://wikipedia.org/).
Prerequisites:Before start reading this book, please make sure that your system get
installed with JDK5.0/6.x, Netbeans5.5/6.x, Eclipse, and any application server like
GlassFish/Websphere
Application
server
and
any
database
like
IBMDB2/Oracle10g/MySQL. The most of the programs and concepts required JDK5.0
version.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 5 of 69
Easy JavaWeb
Table of Contents
1.
2.
3.
4.
5.
6.
7.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 6 of 69
Easy JavaWeb
7.4. Deployment of Webapplication ------------------------------------------------ Error! Bookmark not defined.
7.5. Servlet Life Cycle -------------------------------------------------------------- Error! Bookmark not defined.
7.6. Servlet API ----------------------------------------------------------------------- Error! Bookmark not defined.
7.7. Servlet Artchitecture---------------------------------------------------------- Error! Bookmark not defined.
7.8. Request Processing ----------------------------------------------------------- Error! Bookmark not defined.
7.9. Creating a Servlet ------------------------------------------------------------- Error! Bookmark not defined.
8.
7.10.
7.11.
Reading Data From HTML Form -------------------------------------- Error! Bookmark not defined.
7.12.
7.13.
7.14.
7.15.
7.16.
7.17.
7.18.
7.19.
7.20.
7.21.
7.22.
7.23.
JSP -------------------------------------------------------------------------------------------------------------------------------- 9
8.1. JSP Phases and Life Cycle -------------------------------------------------------------------------------------- 10
8.2. Anatomy/Structure of a JSP Page --------------------------------------------------------------------------- 11
8.3. JSP Elements -------------------------------------------------------------------------------------------------------- 12
8.4. Implicit Obects ------------------------------------------------------------------------------------------------------ 14
8.5. Creating Webapplication using Eclipse--------------------------------------------------------------------- 15
8.6. Exception Handling ------------------------------------------------------------------------------------------------ 23
8.7. Session Tracking/State Programming---------------------------------------------------------------------- 24
8.8. HttpSession/session ---------------------------------------------------------------------------------------------- 27
8.9. Cookie ------------------------------------------------------------------------------------------------------------------ 29
9.
8.10.
8.11.
JavaBeans -------------------------------------------------------------------------------------------------------- 33
8.12.
8.13.
8.14.
8.15.
8.16.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 7 of 69
Easy JavaWeb
9.1. Tag Life Cycle ------------------------------------------------------------------------------------------------------- 53
9.2. Tag with attributes ------------------------------------------------------------------------------------------------ 56
9.3. Tags With Body ----------------------------------------------------------------------------------------------------- 58
9.4. Tags With Iterations ---------------------------------------------------------------------------------------------- 60
10. AJAX ---------------------------------------------------------------------------------------------------------------------------- 62
10.1.
XMLHttpRequest------------------------------------------------------------------------------------------------ 62
10.2.
10.3.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 8 of 69
Easy JavaWeb
1.
JSP
Java server pages is the J2EE technology for generating dynamic web content.A JSP page is a textbased document that contains two types of text:
static template data: which can be expressed in any text-based format, such as
HTML,SVG, WML, and XML and will be used for presentation.
JSP elements: which construct dynamic content based on the logic.
JSP provides clear separation between logic and presentation. JSP simply puts Java code inside HTML
pages and saving the file with .jsp extension.
Disadvantages with Servlets: When we are developing servlets,we need to have many things in
to consideration like overriding service methods and entries in web.xml. From the developers
perspective Servlets are pure java programs with class and method definitions whereas a JSP page is
much like a text document or web page. With servlets developer must write java code to output the
entire markup, on the other hand a JSP page can be designed like a static web page. JSP separates
static content from dynamic content.Servlets are well suited for handling client request and
executing application logic whereas JSP pages are well suited as views and application logice also.
I am listing out the some of disandvantages.
Thorough Java programming knowledge is needed to develop and maintain all aspects of the
application, since the processing code and the HTML elements are dumped together.
Changing the look and feel of the application, or adding support for a new type of client (such
as a WML client), requires the servlet code to be updated and recompiled.
It's hard to take advantage of web-page development tools when designing the application
interface. If such tools are used to develop the web page layout, the generated HTML must
embedded into the servlet code manually, which is time consuming, error prone, and
extremely boring.
Aim of JSP: Separation of request processing, business logic, and presentation.And also providing
below benefits.
Auto transition and compilation.Means we need not recompile every time when we do
changes in JSP.
JSP are translated and compiled into JAVA servlets but are easier to develop than JAVA
servlets.
JSP uses simplified scripting language based syntax for embedding HTML into JSP.
JSP containers provide easy way for accessing standard objects and actions.
JSP reaps all the benefits provided by JAVA servlets and web container environment, but
they have an added advantage of being simpler and more natural program for web
enabling enterprise developer
JSP use HTTP as default request /response communication paradigm and thus make JSP
ideal as Web Enabling Technology.
We can observe that how JSP coding simplifying the servelt code.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 9 of 69
Easy JavaWeb
Helloworld Servlet
Helloworld JSPPage
import javax.servlet.*;
public class HelloWorldServlet implements
servelet{
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType(text/html);
PrintWriter out=response.getWriter();
out.println(<html>);
out.println(<head>);
out.println ( <title>Hello world</title>);
out.println(</head>);
out.println(<body>);
out.println(<h1>Hello World<\h1>All is well);
out.println(</body>);
out.println(</html>);
}
}
<html>
<head>
<title>Hello world <\title>
</head>
<body>
<h1>Hello World<\h1>
All is well.
</body>
</html>
Whenever a .jsp is requested for the first time, the server does the following phases:
Life cycle of a JSP page consists of three phases, translation phase, compilation phase and
execution phase. As I said earlier that every JSP is a Servlet, a JSP page is translated and
compiled into servlet and the resulting servlet handles the request, So life cycle of a JSP
page cmpletely depends on the Servlet API.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 10 of 69
Easy JavaWeb
Translation Phase: Here the webcontainer will translates the .jsp page into a servlet
compatable java file.Here the entire static markup in the JSP page is converted into
the code that writes the data to response stream. If you look at the source of the
generated Servlet class you will find calls to the out.write() which write data to
ServletOutputStream.
If you have following HTML code into your JSP page
<h1>Hello World<\h1>
It will generate code like out.write(<h1>Hello World<\h1>)
During the translation phase JSP elements are treated as follows:
o
Custom tags are converted into the code that calls method on tag handlers.
Compilation Phase: Here servlet compatible java file will be compiled into a class
file.
Execution Phase: Executes the servlet (response is sent to the client). JSP life cycle's
execution phase is almost similar to that of the Servlet life cycle, because ultimately
it's a servlet which is being executed. The Servlet class generated at the end of the
translation phase represents the contract between container and the JSP page.
According to the JSP specification the servlet class must implement the HttpJspPage
interface which defines the life cycle methods.
JSP life cycle includes three methods jspInit(), _jspService() and jspDestroy()
a.
jspInit():This method is invoked when the JSP page is initialized. This method is
similar to init() method in servlet. If you want to provide initialization for a JSP page,
you define this method in declaration part of the JSP page. But most of the time you
will not need to define this method.
b.
_jspService:This method represents the body of the JSP page and invoked at each
client request. This method is similar to service() method in servlet.
Note: You should never provide implementation _jspService() method as web
container automatically generates this method based on the content of the JSP page
c.
jspDestroy():This method is called only once in JSP's servlet life time, when the JSP
Engine removes the JSP's servlet from memory. It is always better to remove
instance variable resources such as JDBC connections, sockets, other physical
resources in this method to avoid memory leaks.
Note:Please refer Classes and Objects topic in EasyJava book for getting information on
instantiation and initialization.
1.2.
Template Text
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 11 of 69
Easy JavaWeb
<BODY BGCOLOR="FFFFFF" >
<% } else { %>
<BODY BGCOLOR="<%= bgColor %>" >
<% } %>
</BODY>
</HTML>
When a JSP page request is processed, the template text and dynamic content generated by
the JSP elements are merged, and the result is sent as the response to the browser.
1.3.
JSP Elements
There are six types of JSP elements that you can use and they are:
1.
2.
3.
4.
5.
Description
Among all directives, page directive will play major role. So Now I am giving information
about page directive and sub sequent topic will address remaining two directives.
Page directive:Page directive are having these attributes and here I am listing out the
some of important attributes
import :Import is used to import java classes and package methods.This translates
JSP engine to include classes in JSP servlet. Comma is used to separation between
classes and package.
<%@page import="java.sql.*,java.text.SimpleDateForamt"%>
errorPage: errorPage=relativeURL. When an exception is occur in JSP, errorPage
transfer the control of page to defined URL which is set in errorPage. This is
customized presentation of errors to user. If relativeURL found blank, exception will
throw on same page.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 12 of 69
Easy JavaWeb
<%@ page errorPage="error.jsp" %>
isErrorPage: isErrorPage=false | true . isErrorPage in JSP translate JSP engine to
display exception or not. If set false, we can not use exception objects in JSP page.
Default value is true.
<%@ page isErrorPage="true" %>
isThreadSafe: isThreadSafe="true | false" .This attribute translate as JSP class is
thread safe or not. In multiple threads, concurrent number of users can request to
JSP page. JSP process this request, this results in using variable, code at a same
time. We can synchronize request to JSP with this attribute. If isThreadSafe is false,
one request process to JSP at same time, and implement as SingleThreadModel. We
suggest to use isThreadSafe in rare cases when really need it.
<%@ page isThreadSafe="true" %>
Buffer: buffer="none | 8k | size" .buffer in page directive specify the buffer size of
out object to print on client browser. Default size of buffer is 8k, can change to as
requirement.
<%@ page buffer="16kb" %>
autoFlush: autoFlush=true | false .when buffer get full it is automatically flush, if it
is set as true. In false case, it throws exception of overflow.
<%@ page autoFlush="true" %>
session: session=true | false. Session attribute in page translate to JSP engine to
use session object in current JSP page. If session attribute set as false in page
directive we can not use session in current JSP.By default it is true.
<%@ page session="true" %>
extends: extends=class.package.ClassName .extends is used to override the class
hierarchy provided by JSP container. It is something like to deploy own our classes
instead of using JSP container classes. It should be used with precaution unless you
know it clearly. It is used when we need tag libraries.
<%@ page extends="com.myapp.ClassName" %>
6.
Action elements are basically predefined functions and Here is the list of common JSP
actions:
Actions
jsp:include
Purpose
Includes a file at the time the page is requested
jsp:useBean
jsp:setProperty
jsp:getProperty
jsp:plugin
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 13 of 69
Easy JavaWeb
jsp:param
1.4.
Implicit Obects
Implicit objects in jsp are the objects that are created by the container automatically and
makes them available to the JSP.Developers do not need to create them explicitly. Since
these objects are created automatically by the container and are accessed using standard
variables; hence, they are called implicit objects. The implicit objects are parsed by the
container and inserted into the generated servlet code. There are nine implicit objects. Here
is the list of all the implicit objects:
1.
2.
3.
4.
5.
6.
7.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 14 of 69
Easy JavaWeb
8.
application:It is used to share information for all JSPs and Servlets in the
application context. application is instance of javax.servlet.ServletContext.
9.
The scope constrains the accessibility and lifetime of the object and these details are
summarized in below table.This table will be help us in coming examples.
1.5.
Name
Accessible From
Lifetime
page
Current page
request
session
application
Note: We should remember strongly that IDEs does not do any thing and
they are just for helping us many ways to speed up the development and
deployment processes.
Step1: whenever we launch Eclipse then it will ask us for location of workspace where all of
our projects will stroed.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 15 of 69
Easy JavaWeb
Step2: Now its the time to create the server to deploy our applications. In the Servers view
is a view that contains nothing. This view is for application and Web servers; it let us to
control them and monitor their status. Right Click New Server from the contextsensitive menu. The New Server wizard, as shown in below Figure.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 16 of 69
Easy JavaWeb
Click next and then give the base location of tomcat server like below.
Click Finish.
Step3:Next, create a simple Web application likw File New select Dynamic Web Project
and then you will get the below window
Enter a name for the project and note that the Target runtime field is pre-populated with the
servers which we created earlier.So select one of them from this list. Accept the default
values for all the fields in this dialog and click Finish.
Step4:Now you will create a JSP page within your new project. Expand the project you
created and then the WebContent folder.Right-click on the WebContent folder and select the
New JSP menu and then screen will be like below.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 17 of 69
Easy JavaWeb
Enter a name for the file, such as HelloWorld, and click Finish.
Step5:The file is opened in a JSP Editor. Enter the below code
<% out.print("Hello World!!"); %>
Save the file.
Step6:Deploying our Web Application by Right-click on the JSP file, HelloWorld.jsp, in the
ProjectExplorer. Select Run As > Run on Server menu and we can see this in below figure.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 18 of 69
Easy JavaWeb
In the Run On Server dialog box, verify that the server Tomcat V5.5 Server is selected like
below.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 19 of 69
Easy JavaWeb
<HTML>
<BODY>
Hello! The time is now <%= new java.util.Date() %>
</BODY>
</HTML>
Output:
Observe that each time you reload the page in the browser, it comes up with the current
time.The element <%= and %> enclose Java expressions, which are evaluated at run time.
This is what makes it possible to use JSP to generate dyamic HTML pages.
Output:
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 20 of 69
Easy JavaWeb
Observation: We can see how to use the "out" variable to generate HTML output from within a
scriptlet in section A. For more complicated HTML, using the out variable all the time loses some of
the advantages of JSP programming. It is simpler to mix java and HTM using expressions like section
B.
Example3:Demonstration of using JSP declaration,scriptlets and expressions.
<%! int i = 10;
int j = 10;
public int getSum() {
return i + j;
}
%>
<%="Sum=" + getSum()%><br>
<%
out.println("Sum=" + getSum());
%>
Output:
www. javasiva.in
Page 21 of 69
Easy JavaWeb
Output:
www. javasiva.in
Page 22 of 69
Easy JavaWeb
</head>
<body>
<form name="f1" action="/JSPBasics/take.jsp" method="get">
username<input name="usr" ><br>
pasword<input type="password" name="pwd"><br>
Age:<input type="text">
<input type="submit" value="SubGo" >
<input type="button" value="ButGo" >
</form>
</body>
</html>
take.jsp
<%
String us = request.getParameter("usr");
String pw = request.getParameter("pwd");
out.println("<font color=green size=45>usr: " + us + "<br>");
out.print("pswd: " + pw);
%>
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 23 of 69
Easy JavaWeb
The exception object refers to the exception triggered by the page that uses this page as an
exception handler.
The following code demonstrates the use of the exception implicit object. The first page uses
the errorPage directive to set up the JSP page to use when an exception occurs, and the second
page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the exception.
parsing.jsp
<%@ page errorPage = "error.jsp" %>
<%
int i=Integer.parseInt("23a");
out.print(i);
%>
error.jsp
<%@ page isErrorPage="true" %>
<html>
<head>
<title>Implicit Exception Error page</title>
</head>
<body>
The Exception is <strong><%= exception.toString() %></strong><br>
Message : <strong><%=exception.getMessage()%></strong><br>
</body>
</html>
Declarative handling of exceptions: It is also possible to map HTTP error codes and or Java
exception types to an error page in the deployment descriptor. This is done at the web
application level by using the <error-page> tag which is a child of the <web-app> tag.
The following tags would redirect all SQL exception errors to the /errorpage.jsp page.
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>/errorpage.jsp</location>
</error-page>
The following tags would redirect all HTTP 404 errors to the /errorpage.jsp page
<error-page>
<error-code>404</error-code>
<location>/errorPage.jsp</location>
</error-page>
1.7.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 24 of 69
Easy JavaWeb
1.
URL Rewriting:You can append some extra data on the end of each URL that
identifies the session. This is also an excellent solution,when browsers that don't
support cookies or where the user has disabled cookies. You need to use ? and name
and value separated by =.If we have more pairs then use & like below:
http://localhost:8080/rewriting/next.jsp?par=AJP
Data.html
<html>
<head>
<title>Login Form</title>
</head>
<body>
<h1>Login Form</h1>
<form method = "post" action = "/JSPBasics/query/take.jsp">
Enter your name : <input type = text name =txtName><br>
<input type = submit name = submit value = submit >
</form>
</body>
</html>
take.jsp
<a href=/JSPBasics/query/next.jsp?par=<%=request.getParameter("txtName")%> >
next</a>
next.jsp
Welcome to: <%= request.getParameter("par")%>
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 25 of 69
Easy JavaWeb
2.
Hidden form fields: HTML forms have an entry that looks like the following: <INPUT
TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is
submitted, the specified name and value are included in the GET or POST data. This
can be used to store information about the session. However, it has the major
disadvantage that it only works if every page is dynamically generated.Usage of
hidden field will be like below:
<input type=hidden name=par value=AJP>
Data.html
<html>
<head><title>Login Form</title></head>
<body>
<h1>Login Form</h1>
<form method = "post" action = "/JSPBasics/hidden/take.jsp">
Enter your name : <input type = text name =txtName><br>
<input type = submit name = submit value = submit >
</form>
</body>
</html>
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 26 of 69
Easy JavaWeb
next.jsp:
out.print(Welcome to: +request.getParameter("par"));
1.8.
3.
4.
Cookies: Cookie a small data file reside in users system. Cookie is made by web
server to identify users. When user do any request send to web server and web server
know information of user by these cookie. After process request, web server response
back to request through this cookie. javax.servlet.http.Cookie, by this classes we can
create and retrieve cookie. Once we set value in cookie, it lived until cookie gets
expired. Cookie plays a big role in session, because maximum session is tracked by
cookie in Servlets.we will discuss it in later section in detail.
HttpSession/session
Session object is medium to interact with client and server. Session is a connection between
user and server, involving exchange of information between users computer and server.
Server knows information about each other by these session object. Web server put
information of user in session object and whenever it needs information gets it from these
session objects. This session object stores information in key value pair, just like hashtable.
Today programming without session cannot be thinkable. Most of web application is user
based, somewhat use transaction (credit card, database transaction), shopping cart, email,
and this needs session. Web server should know who is doing this transaction. This session
object helps to differentiate users with each other, and increase applications security. Every
user have unique session, server exchange information with session objects until it get
expired or destroyed by web server.
When to use Session:Mostly session is work with user base application, when login
screen is used then set session if login is successful. It set for maximum time
provided by web.xml or defined by application.
When to destroy Session:When user has done their work and want to close
browser, it should be expire or destroy forcefully by user, ensure no other person
can use his session.
Usage of Session:To get HttpSession obect, we need to call getSession() on
request obect like below:
HttpSession session = request.getSession(true);
Def between getSession(true) /getSession() and getSession(false):Both
request.getSession() and request.getSession(true) are same.They will return the
current session and if one does not exist, a new session will be cretaed.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 27 of 69
Easy JavaWeb
If we use request.getSession(false), it will return the current session if one exists
and if one DOES NOT exist, a new one will NOT be cretaed.
session.setAttribute("name",value) is use to set new session variable. If we need to
retrieve session variable, have to use session.getAttribute(name). In this we have
to get it by session variable name here we are using name is session variable as
key.New session can be find by isNew() method of session, when first time session
is created, that is new session.
Inactivate Session Automatically:To inactivate session at runtime, use
session.setMaxInactiveInterval(2700), this will set maximum session time. 2700 is
time in number. In this period, if user dont do anything session get expired
automatically.we can also specify the session period in web.xml like below:
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
Expire Session Forcefully or Remove All Session Variables:When session is no
long needed, should be removed forcefully by user. This can be done by calling
session method of invalidate method session.invalidate(); This method expires
session for current user, who request for log out.
Example3:Demonstration of using session object for marriage details.
bride.html
<form name="f1" method="get" action="/Marriage/ses1.jsp">
<table border=1>
<tr><td>Bride</td><td><input type=text name="txtBride" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
ses1.jsp
<%
String st=request.getParameter("txtBride");
session.setAttribute("bride",st);
%>
<form name="f1" method="get" action="/Marriage/ses2.jsp">
<table border=1>
<tr><td>BrideGrome</td><td><input type=text name="txtBG" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
ses2.jsp
<%
session.setAttribute("BG",request.getParameter("txtBG"));
%>
<center>
<form name="f1" method="get" action="/Marriage/ses3.jsp">
<table border=1>
<tr><td>BrideAge</td><td><input type=text name="Bage" value="" ></td></tr>
<tr><td>Groom Age</td><td><input type=txt name="BGage" value=""></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 28 of 69
Easy JavaWeb
ses3.jsp
<table border="1" align="center">
<thead>
<tr><th>Marriage</th><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr>
<td>Bride</td>
<td><%=session.getAttribute("bride")%></td>
<td><%=request.getParameter("Bage")%></td>
</tr>
<tr>
<td>BrideGroom</td>
<td><%=session.getAttribute("BG")%></td>
<td><%=request.getParameter("BGage")%></td>
</tr>
</tbody>
</table>
Output of the above application like below:
1.9.
Cookie
Cookie a small data file reside in users system. Cookie is made by web server to identify
users. When user do any request send to web server and web server know information of
user by these cookie. After process request, web server response back to request by
knowing through this cookie. JSP provides cookie classes, javax.servlet.http.Cookie, by this
classes we can create and retrieve cookie. Once we set value in cookie, it lived until cookie
gets expired. Cookie plays a big role in session, because maximum session is tracked by
cookie in Servlets.
creating Cookie: Cookie cookie = new Cookie ("key",value);
Then we are adding in cookie of response object like:response.addCookie(cookie);
Expire cookie:To destroy the cookie we need to create the cookie with the same
name and we need to their maximum age like below:
Cookie cookie = new Cookie ("cookieSet",cookieSet);
cookie setMaxAge(0);
This will expire cookie.,with 0 second.
Retrieve cookie:Cookie is in array object, we need to get in request.getCookies()
of array like below:
Cookie[] cookies = request.getCookies();
for (int i=0; i<cookies.length; i++) {
out.println(cookies[i].getName()+" : "+cookies[i].getValue()+"<br/>");
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 29 of 69
Easy JavaWeb
}
Example4:Demonstration of using Cookies for marriage details.
bride.html
<form name="f1" method="get" action="http://localhost:8084/cooki/cook1.jsp">
<table border="1" >
<tr><td>Bride</td><td><input type=text name="txtBride" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
cook1.jsp
<%
String st=request.getParameter("txtBride");
Cookie c1=new Cookie("bride",st);
response.addCookie(c1);
%>
<form name="f1" method="get" action="http://localhost:8084/cooki/cook2.jsp">
<table border="1" >
<tr><td>BrideGrome</td><td><input type=text name="txtBG" value="" ></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
</form>
cook2.jsp
<form name="f1" method="get" action="http://localhost:8084/cooki/cook3.jsp">
<table border=1>
<tr><td>BrideAge</td><td><input type=text name="Bage" value="" ></td></tr>
<tr><td>Groom Age</td><td><input type=txt name="BGage" value=""></td></tr>
<tr><td colspan=2 align=center><input type="submit" name="sub"
value="Go"></td></tr>
</table>
cook3.jsp
<% Cookie ck[]=request.getCookies();%>
<table border="1" align="center">
<thead>
<tr><th>Marriage</th><th>Name</th><th>Age</th></tr>
</thead>
<tbody>
<tr>
<td>Bride</td>
<td><%=ck[0].getValue()%></td>
<td><%=request.getParameter("Bage")%></td>
</tr>
<tr>
<td>BrideGroom</td>
<td><%=ck[1].getValue()%></td>
<td><%=request.getParameter("BGage")%></td>
</tr>
</tbody>
</table>
Output of the above application like below:
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 30 of 69
Easy JavaWeb
1.10.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 31 of 69
Easy JavaWeb
User.jsp
<center>
<%@include file="header.jsp" %>
<hr>
<br> <br>
<jsp:include page="body.jsp"/>
<br> <br><br><br>
<hr>
<%@include file="footer.jsp" %>
</center>
header.jsp
<h3>JavaSiva---<i>Care is my motto</i></h3>
body.jsp
<%
String us = request.getParameter("usr");
String pw = request.getParameter("pwd");
out.println("usr: " + us + "<br>");
out.print("pswd: " + pw);
%>
footer.jsp
<h5>Copyrights Reserved</h5>
www. javasiva.in
Page 32 of 69
Easy JavaWeb
<jsp:include page="/B.jsp">
<jsp:param name="book" value="EasyJavaWeb"/>
</jsp:include>
B.jsp
Here Is the interested book for Java WebTechnologies.<br>
<%
out.println("Favourite Book is "+request.getParameter("book"));
%>
Choosing the required include:There are two include mechanisms available to insert a
file in a JSP page. They are
1. include directive <%@ include file="child.jsp" %>
2. include action <jsp:include page="child.jsp" flush="true" />
The include directive includes the content of the file during the translation phase
where as include action includes the content of the file during execution/request
processing phase.
For include directive, JSP Engine adds the content of the inserted page at translation
phase, so it does not have an impact on performance.
For include action, JSP Engine adds the content of the inserted page at run time
which imposes extra overhead.
1.11.
JavaBeans
The JavaBeans specification defines a set of programming conventions for Java classes that
should be used as pluggable components. Bean is a reusable component which mostly
contains the setter and getter values, we also called it as mutators.To work with java
components we will use <jsp:useBean> which locates or instantiates a Bean with a specific
name and scope.
Syntax:
<jsp:useBean
id="beanInstanceName"
scope="page|request|session|application"
class="package.class"
> child tags </jsp:useBean>
The <jsp:useBean> tag attempts to locates a Bean, or if the Bean does not exist,
instantiates it from a class. To locate or instantiate the Bean, <jsp:useBean> takes the
following steps, in this order:
Attempts to locate a Bean with the scope and name you specify OR defines an
object reference variable with the name you specify.
If it finds the Bean, stores a reference to it in the variable. If you specified type,
gives the Bean that type.
If it does not find the Bean, instantiates it from the class you specify, storing a
reference to it in the new variable with scope you specify.
if it has body tags (between <jsp:useBean> and </jsp:useBean>), executes the
body tags.
The body of a <jsp:useBean> tag often contains a <jsp:setProperty> tag that defines
property values in the object.
Attributes of useBean action:Here I am listing out some of frequently used attributes.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 33 of 69
Easy JavaWeb
1.
2.
3.
page: It means that we can use the Bean within the JSP page.
request: It means that we can use the Bean from any JSP page which
processing the same request.
session: It means that we use the Bean from any Jsp page in the same
session.Means it is per client.
application: It means that we use the Bean from any page in the same
application. Means it will be accessible to all clients.
<jsp:setProperty>:It is a child tag of useBean.We can call bean setter methods.Here is the
syntax.
<jsp:setProperty name = "nameOfBeanInstance"
property="*"| propertyName
value=string | <%= expression%>
param=requestparameter name
>
When you use the <jsp:setProperty> action, the container takes care automatically of the
conversion from text values to the Java types.
<jsp:getProperty>: It is a child tag of useBean.we can call bean getter methods.Here is
the syntax.
<jsp:getProperty name="nameOfBeanInstance" property="propertyName"/>
Example: Demonstration of working with useBean.
Input.html
<HTML>
<head>
<title>Demo Of useBean</title>
</head>
<BODY>
<FORM METHOD=POST ACTION="Collect.jsp">
Name: <INPUT TYPE=TEXT NAME=username><BR>
E-Mail: <INPUT TYPE=TEXT NAME=email><BR>
Age: <INPUT TYPE=TEXT NAME=age><BR>
<INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>
UserData.java: This class is a POJO (Stands for Plain Old Java Object) which should be
coded before you are working with <jsp:useBean>.
To collect this data, we define a Java class with fields "username", "email" and "age" and we
provide setter methods "setUsername", "setEmail" and "setAge", as shown. A "setter"
method is just a method that starts with "set" followed by the name of the field. The first
character of the field name is upper-cased. So if the field is "email", its "setter" method will
be "setEmail". Getter methods are defined similarly, with "get" instead of "set". Note that
the setters (and getters) must be public.
package com.javasiva.ajp.examples;
/**
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 34 of 69
Easy JavaWeb
*
* @author siva
*/
public class UserData {
String username;
String email;
int age;
public void setUsername(String value) {
username = value;
}
public void setEmail(String value) {
email = value;
}
public void setAge(int value) {
age = value;
}
public String getUsername() {
return username;
}
public String getEmail() {
return email;
}
public int getAge() {
return age;
}
}
The method names must be exactly as shown. Once you have defined the class, compile it
and make sure it is available in the WEB-INF/classes folder.
Collect.jsp
All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag. The
useBean tag will look for an instance of the "com.javasiva.ajp.examples.UserData" in
the session. If the instance is already there, it will update the old instance. Otherwise,
it will create a new instance of com.javasiva.ajp.examples.UserData, and put it in the
session.
The setProperty tag will automatically collect the input data, match names against the
bean method names, and place the data in the bean.
www. javasiva.in
Page 35 of 69
Easy JavaWeb
<jsp:useBean id="user" class="com.javasiva.ajp.examples.UserData" scope="session"/>
<HTML>
<BODY>
You Entered<BR><BR>
Name: <jsp:getProperty name="user" property="username"/><BR>
Email: <jsp:getProperty name="user" property="email"/><BR>
Age: <%= user.getAge()%><BR>
</BODY>
</HTML>
Notice that the same useBean tag is repeated. The bean is available as the variable named
"user" of class "com.javasiva.ajp.examples.UserData". The data entered by the End-User is
all collected in the bean.
1.12.
www. javasiva.in
Page 36 of 69