Académique Documents
Professionnel Documents
Culture Documents
Web Programming
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
WEB PROGRAMMING
(13CT1116)
Lecture Notes
N. Durga Prasad
Asst. Professor
CSE Department
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
1
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
UNIT-1
INTRODUCTION
TO
HTML
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
2
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
HTML
Introduction to HTML
HTML also provides tags to make the document look attractive using
graphics, font size and colors. User can make a link to the other document or
the different section of the same document by creating Hypertext Links also
known as Hyperlinks.
The essential tags that are required to create a HTML document are:
<HTML>.............</HTML>
<HEAD>.............</HEAD>
<BODY>.............</BODY>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
3
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
The <HTML> tag encloses all other HTML tags and associated text
within your document. It is an optional tag. You can create an HTML
document that omits these tags, and your browser can still read it and display
it. But it is always a good form to include the start and stop tags.
<HTML>
Your Title and Document (contains text with HTML tags) goes here
</HTML>
Most HTML tags have two parts, an opening tag and closing tag.
The closing tag is the same as the opening tag, except for the slash mark e.g
</HTML>. The slash mark is always used in closing tags.
<HTML>
<HEAD>
.............
.............
.............
</HEAD>
<BODY>
.............
.............
.............
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
4
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
</BODY>
</HTML>
HEAD tag comes after the HTML start tag. It contains TITLE tag to give the
document a title that displays on the browsers title bar at the top.
<HEAD>
<TITLE>
</TITLE>
</HEAD>
The BODY tag contains all the text and graphics of the document with
all the HTML tags that are used for control and formatting of the page.
<BODY>
</BODY>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
5
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Example:
<HTML>
<HEAD>
<TITLE>
My first Page
</TITLE>
</HEAD>
<BODY>
</BODY>
</HTML>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
6
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
INTRODUCTION TO JAVASCRIPT
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
7
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
8
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
9
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
10
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
INTRODUCTION TO CSS
Introduction:
CSS is a formatting language, used to provide more customised web
pages and make it easier to make multiple pages use the same style. The
acronym stands for Cascading Style Sheets. All current browsers can handle
CSS, and it is the best Web page formatting language produced to date.
Some very popular browsers do not handle it as well as they should (see the
section on browser problems) but largely support is good and developers are
tending to use it much more often.
Using CSS, you can define colours, backgrounds, borders, margins,
alignment, fonts, sizes and loads of other things for almost any part of your
web pages.
The word cascading describes many of the features of CSS. Firstly, it
means that many stylesheets can be used and will be merged by the browser
to provide a computed style for each element. If styles defined for one
element oppose each other, the later one will be used, unless another one
more specifically refers to the element (for example, if all paragraphs are
made red, but a paragraph that is in a <div> is made blue, the blue will
override the red for paragraphs in a div, as it more specifically refers to the
desired element). Cascading also means that each object inherits some styles
from its parent object or parent class. The parents are not the same as the
parent objects in JavaScript but use a similar idea. The objects are refered to
by their element tag. The highest object in the structure is the html element.
If any elements do not have their own CSS defined but the html element
does, then the cascading behaviour means they will inherit from
the html element. So, if in the htmlelement we define the text colour to be
white, then any tables will also have white writing in them.
Each element can be in a class. For example, if we define the 'p' tag to
have a text colour red then every paragraph will be red. But if we then define
a class of paragraph called mybold where the text is bold and we create a
paragraph of class mybold, it will have bold text. But remember that style
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
11
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
sheets cascade and elements inherit from their parent class, so the text in the
paragraph of class mybold will also be red. If we define the class mybold to
have blue text then the blue will override the red and the text in the
paragraph of class mybold will be blue.
One of the features of CSS is that if the browser does not understand
something, it will ignore it and move on to the next attribute. It will not
display warnings. This can make things easier in some circumstances, since
you can apply styles without having to worry that a browser might ignore
the entire stylesheet, because it should only ignore the parts it does not
understand (although there are a few exceptions). However, it also means
that it can be difficult to work out if a browser will correctly apply a rule or
not. For example, you may want to apply display:table-
cell;width:25% to an element if it understands it, and width:100% if
not. Unfortunately, CSS does not provide any way to test for support of a
property.
When using CSS, it is important to make sure that browsers use their
most standards compliant response. You will need to ensure that your
DOCTYPE triggers standards mode rendering for these browsers, or they
will assume your code is relying on some mistakes of older browsers, and
will try to replicate some them to various degrees, which can produce
unpredictable results.
There are two ways to include CSS on a page. One is by loading it
from an external file, and one is by embedding it directly in the source code
of the page. One of the most useful features of CSS is the ability to share the
same styles across many pages, so that all pages can be changed by
modifying a single file. To do that, you will need to keep the CSS in a
separate file. This also allows you to keep the clutter out of your document,
and helps avoid several other problems, so even if you only intend to use the
CSS on one page, you may want to include it in an external file anyway.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
12
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
To embed CSS directly into a web page, use the STYLE tag, and set the type
to'text/css':
<style type="text/css">
</style>
Note that CSS should only ever be included in the head of your document,
unless you use inline style attributes on individual elements.
General Syntax:
Firstly define the element the CSS is written for. Then use { and after putting
in the styles, close it with }
This might look like this:
In this case, the 'body' is known as the selector. This can get more
complicated, and can include many different selectors.
For several elements to use the same style, you can separate them with
commas:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
13
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
name_of_style_attribute: value;
You can include as many styles as you want inside the { and } curly braces.
Occasionally, there may be more than one value for a single style, for
example with the border attribute:
To define styles that should only target elements with a certain class, put a
fullstop then the name of the class, after the element. This might look like:
This would also need the class to be written inside the HTML 'p' element
tags to which it refers:
<p class="nameofclass">
There are also some pseudo-classes such as :hover. This particular one
will only work in some browsers (most notably, Internet Explorer 6-)
with 'a'elements. It will be applied when the mouse hovers over the element.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
14
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
One of the most powerful uses of this pseudo class is to produce menus
written only using pure CSS.
If an element has been defined with an ID then it can be given its own style
by using the ID selector. Try to restrict this to cases where it is actually
needed:
You can also target the specific element type, combined with the ID selector:
If you also want to assign that style to p elements, you can combine this with
the comma, as shown earlier:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
15
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Or mix that up however you like. You can also combine it with class
selectors. For example, this will match all li elements whose parents include
a td of classfish:
If at any time you define two or more conflicting styles, the more
specific one should be used by the browser. If you use an inline style, that
should override other styles. There are exceptions to these rules, but I will
not go into those here.
All styles will have a default value, and that may be different for
different elements (for example, the border style has a default value
of 'none', but most browsers use something like '2px groove black' as the
default border for a fieldset). If you have styled an element with a generic
style, and you want to reset it to its default style for that specific element,
you will need to manually set it back to its default value. For example, you
could set all paragraphs to have a 1 pixel border, then set paragraphs not to
have a border if they are inside a div:
p{
p{
And this can be done for one side at a time as well. This is generally most
useful to specify a normal style, then override it for just one side:
p{
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
17
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
border-right-color: green;
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
18
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
UNIT-2
INTRODUCTION TO XML
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
19
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
XML
A number of companies (in 2000) expect that it will be used more
extensively on the web in the future. XML looks something like HTML, in
that it uses tags that surround data. XML tags are intended to contain
information about the data they surround, whereas HTML tags mainly
indicate how to format the data so humans can read it.
Lots of companies have data they would like other people to use,
however often it is hard to exchange data between different applications.
XML tags should let diffrent computer systems read data and allow
programs to act on that data. You might think of it as the start of a universal
database. This should assist in searching for data, especially on the web, as it
should be easier to exclude irrelevant data that happens to include the terms
for which you are searching. It should make it easier to do "intelligent"
searches.
Like HTML, XML makes use of tags (words bracketed by '<' and '>')
and attributes (of the form name="value"). While HTML specifies what
each tag and attribute means, and often how the text between them will look
in a browser, XML uses the tags only to delimit pieces of data, and leaves
the interpretation of the data completely to the application that reads it. In
other words, if you see "<p>" in an XML file, do not assume it is a
paragraph. Depending on the context, it may be a price, a parameter, a
person, a p... (and who says it has to be a word with a "p"?).
Since XML is a text format and it uses tags to delimit the data, XML
files are nearly always larger than comparable binary formats. That was a
conscious decision by the designers of XML. The advantages of a text
format are evident (see point 3), and the disadvantages can usually be
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
21
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
XML 1.0 is the specification that defines what "tags" and "attributes"
are. Beyond XML 1.0, "the XML family" is a growing set of modules that
offer useful services to accomplish important and frequently demanded
tasks. XLink describes a standard way to add hyperlinks to an XML file.
XPointer is a syntax in development for pointing to parts of an XML
document. An XPointer is a bit like a URL, but instead of pointing to
documents on the Web, it points to pieces of data inside an XML file. CSS,
the style sheet language, is applicable to XML as it is to HTML. XSL is the
advanced language for expressing style sheets. It is based on XSLT a
transformation language used for rearranging, adding and deleting tags and
attributes. The DOM is a standard set of function calls for manipulating
XML (and HTML) files from a programming language. XML Schemas 1 and
2 help developers to precisely define the structures of their own XML-based
formats. There are several more modules and tools available or under
development. Keep an eye on W3C's technical reports page.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
22
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
8. XML is modular
By choosing XML as the basis for a project, you gain access to a large
and growing community of tools (one of which may already do what you
need!) and engineers experienced in the technology. Opting for XML is a bit
like choosing SQL for databases: you still have to build your own database
and your own programs and procedures that manipulate it, but there are
many tools available and many people who can help you. And since XML is
license-free, you can build your own software around it without paying
anybody anything. The large and growing support means that you are also
not tied to a single vendor. XML isn't always the best solution, but it is
always worth considering.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
24
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
UNIT-3
JDBC(JAVA Database Connectivity)
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
25
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
What is JDBC?
Definition
Java Database Connectivity in short called as JDBC. It is a java API which
enables the java programs to execute SQL statements. It is an application
programming interface that defines how a java programmer can access the
database in tabular format from Java code using a set of standard interfaces
and classes written in the Java programming language.
JDBC has been developed under the Java Community Process that allows
multiple implementations to exist and be used by the same application.
JDBC provides methods for querying and updating the data in Relational
Database Management system such as SQL, Oracle etc.
In short JDBC helps the programmers to write java applications that manage
these three programming activities:
Due to JDBC API technology, user can also access other tabular data sources
like spreadsheets or flat files even in the a heterogeneous environment.
JDBC application programmming interface is a part of the Java platform
that have included Java Standard Edition (Java SE ) and the Java Enterprise
Edition (Java EE) in itself.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
27
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
The JDBC Driver Manager is a very important class that defines objects
which connect Java applications to a JDBC driver. Usually Driver Manager
is the backbone of the JDBC architecture. It's very simple and small that is
used to provide a means of managing the different types of JDBC database
driver running on an application. The main responsibility of JDBC database
driver is to load all the drivers found in the system properly as well as to
select the most appropriate driver from opening a connection to a database.
The Driver Manager also helps to select the most appropriate driver from the
previously loaded drivers when a new open database is connected.
The function of JDBC driver test suite is to make ensure that the JDBC
drivers will run user's program or not . The test suite of JDBC application
program interface is very useful for testing a driver based on JDBC
technology during testing period. It ensures the requirement of Java
Platform Enterprise Edition (J2EE).
Now we can conclude this topic: This first two component of JDBC, the
JDBC API and the JDBC Driver Manager manages to connect to the
database and then build a java program that utilizes SQL commands to
communicate with any RDBMS. On the other hand, the last two components
are used to communicate with ODBC or to test web application in the
specialized environment.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
28
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
The primary function of the JDBC API is to provide a means for the
developer to issue SQL statements and process the results in a consistent,
database-independent manner. JDBC provides rich, object-oriented access
to databases by defining classes and interfaces that represent objects such
as:
1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Binary Large Objects (BLOBs)
7. Character Large Objects (CLOBs)
8. Callable statements
9. Database drivers
10.Driver manager
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
29
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Type 2 Java to Native API. Type 2 drivers use the Java Native Interface
(JNI) to make calls to a local database library API. This driver converts
the JDBC calls into a database specific call for databases such as SQL,
ORACLE etc. This driver communicates directly with the database server.
It requires some native code to connect to the database. Type 2 drivers are
usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers
require native database client libraries to be installed and configured on
the client machine. (See Figure 3.)
Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are
pure Java drivers that use a proprietary network protocol to communicate
with JDBC middleware on the server. The middleware then translates the
network protocol to database-specific function calls. Type 3 drivers are the
most flexible JDBC solution because they do not require native database
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
31
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
libraries on the client and can connect to many different databases on the
back end. Type 3 drivers can be deployed over the Internet without client
installation. (See Figure 4.)
Java-------> JDBC statements------> SQL statements ------> databases.
Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that
implement a proprietary database protocol (like Oracle's SQL*Net) to
communicate directly with the database. Like Type 3 drivers, they do not
require native database libraries and can be deployed over the Internet
without client installation. One drawback to Type 4 drivers is that they are
database specific. Unlike Type 3 drivers, if your back-end database
changes, you may save to purchase and deploy a new Type 4 driver (some
Type 4 drivers are available free of charge from the database
manufacturer). However, because Type drivers communicate directly with
the database engine rather than through middleware or a native library,
they are usually the fastest JDBC drivers available. This driver directly
converts the java statements to SQL statements.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
32
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
So, you may be asking yourself, "Which is the right type of driver for your
application?" Well, that depends on the requirements of your particular
project. If you do not have the opportunity or inclination to install and
configure software on each client, you can rule out Type 1 and Type 2
drivers.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
33
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
INTRODUCTION TO SERVLETS
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
34
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Java Servlet
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
35
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
* Priovide dynamic content like getting the results of a database query and
returning to the client.
* Process and/or store the data submitted by the HTML.
* Manage information about the state of a stateless HTTP. e.g. an online
shopping car manages request for multiple concurrent customers.
Important software required for running this server is Suns JDK (Java
Development Kit) and JRE (Java Runtime Environment). The current
version of JDK is 6.0. Like Tomcat, JDK is also free and is available for
download at www.java.sun.com.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
36
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Once the above pre-requisites are taken care, you can test as whether the
server is successfully installed as follows:
Step 1
OR
Step 2
Open your Browser (e.g. MS Internet Explorer) and type the following
URL :
OR
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
37
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Open your Browser (e.g. MS Internet Explorer) and type the following
URL :
In either case, you should get a page similar to the one in Figure-8 which
signifies that the Tomcat Server is successfully running on your machine.
webapps folder.
The third step is to create the WEB-INF folder. This folder should be created
under your web application folder that you created in the previous step.
Figure-10 shows the WEB-INF folder being placed under the demo-
examples folder.
The fourth step is to create the web.xml file and the classes folder. Ensure
that the web.xml and classes folder are created under the WEB-INF folder.
Figure-11 shows this file and folder being placed under the WEB-INF folder.
Note Instead of creating the web.xml file an easy way would be to copy an
existing web.xml file (e.g. C:\Program Files\Apache Software
Foundation\Tomcat 6.0\webapps\examples\WEB-INF) and paste it into this
folder. You can later edit this file and add relevant information to your web
application.
We need to copy the servlet class file to the classes folder in order to run the
servlet that we created. All you need to do is copy the servlet class file (the
file we obtained from Step 1) to this folder. Figure-12 shows the
servlet_lifecycle (refer section 1.2.3.) class being placed in the classes
folder.
This step involves two actions viz. including the servlets name and then
mentioning the url pattern. Let us first see as how to include the servlets
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
39
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
name in the web.xml file. Open the web.xml file and include the servlets
name as shown in Figure-13.
Note The servlet-name need not be the same as that of the class name.
You can give a different name (or alias) to the actual servlet. This is one of
the main reasons as why this tag is used for.
Note Please remember that the path given in the url-pattern is a relative
path. This means that this path is w.r.t. your web applications folder (demo-
examples in this case).
This step again involves two actions viz. running the Web Server and then
executing the servlet.
After ensuring that the web server is running successfully, you can run your
servlet. To do this, open your web browser and enter the url as specified in
the web.xml file. The complete url that needs to be entered in the browser is:
http://localhost/demo-examples/servlet_lifecycle
Heres the output of our first servlet. After a long and pain staking
effort, we finally got an output! As mentioned in Section 1.2.3. you can keep
refreshing the browser window and see for yourself as how i value is
incremented (a proof that the doGet is called every time you re-invoke a
servlet).
* Download and Install the tomcat server: Install the tomcat server in a
directory in which you want to install and set the classpath.for the variable
JAVA_HOME in the environment variable. To get details about the
installation process and setting the classpath click the link Tomcat
installation.
* Set the class for the jar file: Set the classpath of the servlet-api.jar file in
the variable CLASSPATH inside the environment variable by using the
following steps.
Go to Start->Control Panel->System->Advanced->Environment
Variables->New button and Set the values as
Variable Name: CLASSPATH
Variable Value: C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jar
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
41
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
We should start understanding the servlets from the beginning. Lets start by
making one program which will just print the "Hello World" on the browser.
Each time the user visits this page it will display "Hello World" to the user.
As we know that the our servlet extends the HttpServlet and overrides the
doGet() method which it inherits from the HttpServlet class. The server
invokes doGet() method whenever web server recieves the GET request
from the servlet. The doGet() method takes two arguments first is
HttpServletRequest object and the second one is HttpServletResponse object
and this method throws the ServletException.
Whenever the user sends the request to the server then server generates two
obects, first is HttpServletRequest object and the second one is
HttpServletResponse object. HttpServletRequest object represents the
client's request and the HttpServletResponse represents the servlet's
response.
Inside the doGet(() method our servlet has first used the setContentType()
method of the response object which sets the content type of the response to
text/html. It is the standard MIME content type for the Html pages. After
that it has used the method getWriter() of the response object to retrieve a
PrintWriter object. To display the output on the browser we use the println()
method of the PrintWriter class.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
42
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Example Program to maintain sessions using cookies
CookieExample.java
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
43
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Execution procedure:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
45
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Tomcat
Tomcat
6.0
6.0
Webapps
Webapps
dp ROOT
dp ROOT
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
WEB-INF 46
Classes WEB-INF
Classes
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
WEB-INF
WEB-INF
Web.xml
Web.xml
CookieE
CookieE
xample.
xample.
class
class
After generating class file create the web.xml file and the classes
folder.Ensure that the web.xml and classes folder are created under
the WEB-INF folder. The above figure shows this file and folder being
placed under the WEB-INF folder.
Web.xml
<web-app>
<servlet>
<servlet-name>CookieExample</servlet-name>
<servlet-class>CookieExample</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name> CookieExample </servlet-name>
<url-pattern>/ CookieExample </url-pattern>
</servlet-mapping>
</web-app>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
47
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
http://localhost:8080/dp/CookieExample
OUTPUT
http://localhost:8080/dp/CookieExample
http://localhost:8080/dp/CookieExample
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
48
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
49
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
UNIT-4
JAVA SERVER PAGES
So what are JavaServer Pages? Well, they combine markup (whether HTML
or XML) with nuggets of Java code to produce a dynamic web page. Each
page is automatically compiled to a servlet by the JSP engine, the first time
it is requested, and then executed. JSP provides a variety of ways to talk to
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
50
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Java classes, servlets, applets and the web server. With it, you can split the
functionality of your web applications into components with well-defined
public interfaces glued together by a simple page.
Architectural Overview
It should be no surprise, given the flexibility of the servlet model, that the
current reference implementation of the JSP engine is itself a servlet.
If you take a look in the source files for the javax.servlet.jsp package, you'll
find the following classes :
JSPPage
HttpJspPage
They define the interface for the compiled JSP page - namely that it must
have three methods. Not surprisingly they are :
jspInit()
jspDestroy()
_jspService(HttpServletRequest request, HttpServletResponse
response)
The first two methods can be defined by the JSP author (we'll see how in a
moment), but the third is the compiled version of the JSP page, and its
creation is the responsibility of the JSP engine.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
51
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
<html>
<head>
<title>Demo of a JSP page</title>
</head>
<body>
<%
}
%>
<br>
<%
}
%>
</body>
</html>
This page just outputs the alphabet 26 times and changes the starting letter.
The HTML is self-explanatory and written the way it should be, rather than
cluttering up methods of a servlet.
JSP Directives
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
53
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
A JSP directive is a statement that gives the JSP engine information for the
page that follows. The general syntax of a JSP directive is <%@ directive
{ attribute=value } %>, where the directive may have a number of
(optional) attributes. Each directive has an optional XML equivalent, but
these are intended for future JSP tools, so we won't consider them here.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
54
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
55
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
JSP Declarations
<%!
String var1 = "x";
int count = 0;
Note that you put semi-colons after each variable declaration, just as if you
were writing it in a class.
This is how you would define the optional jspInit() and jspDestroy()
methods that we mentioned earlier.
JSP Scriptlets
Scriptlets are defined as any block of valid Java code that resides between <
% and %> tags.
Implicit Description
Objects
request The client's request. This is usually a subclass of
HttpServletRequest. This has the parameter list if
there is one.
response The JSP page's response, a subclass of
HttpServletResponse.
pageContext Page attributes and implicit objects (essentially what
makes up the server environment in which the JSP
runs) need to be accessible through a uniform API, to
allow the JSP engine to compile pages. But each
server will have specific implementations of these
attributes and objects.
The solution to this problem is for the JSP engine to
compile in code that uses a factory class to return the
server's implementation of the PageContext class.
That PageContext class has been initialized with the
request and response objects and some of the
attributes from the page directive (errorpage, session,
buffer and autoflush) and provides the other implicit
objects for the page request. We'll see more on this in
a moment.
session The HTTP session object associated with the request.
application The servlet context returned by a call to
getServletConfig().getContext() (see Chapter 5).
out The object representing the output stream.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
58
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Implicit Description
Objects
config The ServletConfig object for the page.
page The page's way of referring to itself (as an
alternative to this in any Java code).
exception The uncaught subclass of Throwable that is passed to
the errorpage URL.
The following snippet shows both how to get a named parameter from the
request object, and how to pass a string to the output stream for the page.
<%
String var1 = request.getParameter("lname");
out.println(var1);
%>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
59
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
try {
// Body of translated JSP here...
} catch (Exception e)
{
out.clear();
pageContext.handlePageException(e);
} finally {
out.close();
factory.releasePageContext(pageContext);
}
}
JspFactory returns the pageContext implicit object, from which the other
implicit objects are obtained for the duration of the _jspService() method.
JSP Expressions
A JSP expression is a very nice tool for embedding values within your
HTML code. Anything between <%= and %> tags will be evaluated,
converted to a string, and then displayed. Conversion from a primitive type
to a string is handled automatically.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
60
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Something you'll want to note is that the expression doesn't end with a semi-
colon. That's because the JSP engine will put the expression within an
out.println() call for you.
A big advantage in developing a JavaServer Page is that you can code the
HTML without enclosing it in Java code, as you must do in a servlet. You
can then take advantage of HTML editors to develop your content.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
61
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
What is a JavaBean?
Public class.
Public constructor with no arguments.
Public set and get methods to simulate properties. The get method has
no arguments, unless it acts on an indexed property.
The JavaBeans architecture uses reflection to infer the public methods. But
you can provide a BeanInfo class, called BeanName BeanInfo to give more
explicit information.
A bean can also be serialized and saved for later use. It does this by
implementing the Serializable interface. When a bean component is
serialized, it saves its current state. The current state of a bean is defined by
the current values of its public properties.
Properties are always set and retrieved using a common naming convention.
For each property, two methods must exist, a getxxx() and setxxx() method
(where xxx is the name of the property).
Apart from that a bean is just like any other Java class. Typically, a bean
component is imported into a program, its properties are set and its methods
are called.
Most of the time beans are used to encapsulate visual and non-visual
elements of a GUI. There's some snazzy stuff to link beans up, to implement
drag-and-drop and to save the state of a bean between instances. The
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
62
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Because of this history, Beans don't sit obviously in JSP. Don't get me wrong
- they work well. But it's not what they were originally designed for. If we
think of them as components, simple encapsulations of Java code, then their
purpose is clearer. Beans mean that your page isn't clogged with code.
To show how to use a simple bean, we're going to develop the alphabet
example from earlier, and associate each letter with a color.
The presentation of the letters will remain the responsibility of the JSP page,
but the color mapping will be the bean's job.
package com.wrox.jspexamples;
import java.awt.Color;
import java.util.*;
float s = 0.9f;
float b = 0.9f;
public AlphabetCode()
{
this.map = new HashMap(ALPHABET_LENGTH);
htmlColor.append("\"");
return htmlColor.toString();
}
}
The bean things to note are the public class and constructor, and the set and
get methods. The class sets up the color of each character in the constructor,
and then returns the color of the current character as an HTML color.
<html>
<head>
<title>
Color demo I</title>
</head>
<body>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
65
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
66
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
The JSP page uses straight method calls ( setCharacter(), getCharacter() and
getColor()) to the bean. The only new syntax is <jsp:useBean ... />, so let's
look at that :
The jsp:useBean tag first searches for a bean instance that matches the scope
and class. If it can't find one it instantiates the named class, using its public,
no-args constructor. If there are any initialization time properties you need to
set, you can place the appropriate tags between <jsp:useBean> and
</jsp:useBean> - these are only executed when a new instance is created.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
67
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
In the JSP 1.0 reference implementation, the server looks for your packages
in the CLASSPATH environment variable (on my machine, startserver
includes jsp1.0/examples/WEB-INF/jsp/beans). Let's look at the attributes :
Scope Description
page This is the scope of the PageContext object we
saw earlier. It lasts until the page completes, and
there is no storage of state.
page wasn't implemented in the EA1 reference
version of JSP 1.0.
request The bean instance lasts for the client request.
The named bean instance is available as an
attribute of the ServletRequest object, so it
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
68
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
We're not finished in our tour of tags, though. With a couple of changes to
our JSP code, we can show you two more - jsp:getProperty and
jsp:setProperty :
<html>
<head>
<title>
Color demo
</title>
</head>
<body>
<!-- This page generates a series of rainbow colored letters -->
<!-- It uses the JSP property set and get tags -->
<%@ page language="java" %>
<%! char c = 0; %>
<jsp:useBean id="letterColor" scope="application"
class="com.wrox.jspexamples.AlphabetCode" />
<%
for (int i = 0; i < 26; i++)
{
for (int j = 0; j < 26; j++)
{
c = (char)(0x41 + (26 - i + j)%26);
Character thisChar = new Character(c);
%>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
69
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
...
The <jsp:setProperty ... /> needs the bean name, the property name and the
value with which to set the property. Note that the property name is the
setCharacter() method without the prefix. <jsp:getProperty ... /> is self-
explanatory.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
70
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
UNIT-5
PHP
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
71
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
PHP Tutorial
What is PHP
PHP Example
In this tutorial, you will get a lot of PHP examples to understand the topic
well. The PHP file must be save with .php extension. Let's see a simple PHP
example.
File: hello.php
1. <!DOCTYPE>
2. <html>
3. <body>
4. <?php
5. echo "<h2>Hello by PHP</h2>";
6. ?>
7. </body>
8. </html>
Output:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
72
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Hello by PHP
Web Development
PHP is widely used in web development now a days. Dynamic websites can
be easily developed by PHP. But you must have the basic the knowledge of
following technologies for web development as well.
o HTML
o CSS
o JavaScript
o AJAX
o XML and JSON
o JQuery
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
73
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
What is PHP
What is PHP
PHP Features
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
74
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Install PHP
To install PHP, we will suggest you to install AMP (Apache, MySQL, PHP)
software stack. It is available for all operating systems. There are many AMP
options available in the market that are given below:
PHP Echo
PHP echo is a language construct not a function, so you don't need to use
parenthesis with it. But if you want to use more than one parameters, it is
required to use parenthesis.
PHP echo statement can be used to print string, multi line strings, escaping
characters, variable, array etc
PHP Variables
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
75
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
1. $variablename=value;
PHP Data Types
PHP data types are used to hold different types of data or values. PHP
supports 8 primitive data types that can be categorized further in 3 types:
1. Scalar Types
2. Compound Types
3. Special Types
1. boolean
2. integer
3. float
4. string
1. array
2. object
1. resource
2. NULL
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
76
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
PHP Operators
In the above example, + is the binary + operator, 10 and 20 are operands and
$num is variable.
o Arithmetic Operators
o Comparison Operators
o Bitwise Operators
o Logical Operators
o String Operators
o Incrementing/Decrementing Operators
o Array Operators
o Type Operators
o Execution Operators
o Error Control Operators
o Assignment Operators
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
77
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
[ array()
** arithmetic
Instanceof types
! logical (negation)
*/% arithmetic
^ bitwise XOR
| bitwise OR
|| logical OR
?: ternary
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
78
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
And logical
Xor logical
Or logical
PHP Arrays
PHP array is an ordered map (contains value on the basis of key). It is used
to hold multiple values of similar type in a single variable.
Easy to traverse: By the help of single loop, we can traverse all the
elements of an array.
1. Indexed Array
2. Associative Array
3. Multidimensional Array
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
79
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
PHP Functions
PHP function is a piece of code that can be reused many times. It can take
input as argument list and return value. There are thousands of built-in
functions in PHP.
Code Reusability: PHP functions are defined only once and can be invoked
many times, like in other programming languages.
Less Code: It saves a lot of code because you don't need to write the logic
many times. By the use of function, you can write the logic only once and
reuse it.
We can declare and call user-defined functions easily. Let's see the syntax to
declare user-defined functions.
Syntax
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
80
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
1. function functionname(){
2. //code to be executed
3. }
Note: Function name must be start with letter and underscore only like
other labels in PHP. It can't be start with numbers or special
symbols.
Example
File: function1.php
1. <?php
2. function sayHello(){
3. echo "Hello PHP Function";
4. }
5. sayHello();//calling function
6. ?>
Output:
File: functionarg.php
1. <?php
2. function sayHello($name){
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
81
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Output:
Hello Sonoo
Hello Vimal
Hello John
File: functionarg2.php
1. <?php
2. function sayHello($name,$age){
3. echo "Hello $name, you are $age years old<br/>";
4. }
5. sayHello("Sonoo",27);
6. sayHello("Vimal",29);
7. sayHello("John",23);
8. ?>
Output:
Value passed to the function doesn't modify the actual value by default (call
by value). But we can do so by passing value as a reference.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
82
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
File: functionref.php
1. <?php
2. function adder(&$str2)
3. {
4. $str2 .= 'Call By Reference';
5. }
6. $str = 'Hello ';
7. adder($str);
8. echo $str;
9. ?>
Output:
File: functiondefaultarg.php
1. <?php
2. function sayHello($name="Sonoo"){
3. echo "Hello $name<br/>";
4. }
5. sayHello("Rajesh");
6. sayHello();//passing no value
7. sayHello("John");
8. ?>
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
83
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Output:
Hello Rajesh
Hello Sonoo
Hello John
File: functiondefaultarg.php
1. <?php
2. function cube($n){
3. return $n*$n*$n;
4. }
5. echo "Cube of 3 is: ".cube(3);
6. ?>
Output:
Cube of 3 is: 27
PHP Form Handling
We can create and use forms in PHP. To get form data, we need to use PHP
superglobals $_GET and $_POST.
The form request may be get or post. To retrieve data from get request, we
need to use $_GET, for post request $_POST.
Get request is the default form request. The data passed through get request
is visible on the URL browser so it is not secured. You can send limited
amount of data through get request.
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
84
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Let's see a simple example to receive data from get request in PHP.
File: form1.html
1. <form action="welcome.php" method="get">
2. Name: <input type="text" name="name"/>
3. <input type="submit" value="visit"/>
4. </form>
File: welcome.php
1. <?php
2. $name=$_GET["name"];//receiving name field value in $name variabl
e
3. echo "Welcome, $name";
4. ?>
Post request is widely used to submit form that have large amount of data
such as file upload, image upload, login form, registration form etc.
The data passed through post request is not visible on the URL browser so it
is secured. You can send large amount of data through post request.
Let's see a simple example to receive data from post request in PHP.
File: form1.html
1. <form action="login.php" method="post">
2. <table>
3. <tr><td>Name:</td><td> <input type="text" name="name"/></td></t
r>
4. <tr><td>Password:</td><td> <input type="password" name="passwo
rd"/></td></tr>
5. <tr><td colspan="2"><input type="submit" value="login"/> </td></t
r>
6. </table>
7. </form>
File: login.php
1. <?php
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
85
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Output:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
86
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
PHP Cookie
Cookie is created at server side and saved to client browser. Each time when
client sends request to the server, cookie is embedded with request. Such
way, cookie can be received at the server side.
PHP setcookie() function is used to set cookie with HTTP response. Once
cookie is set, you can access it by $_COOKIE superglobal variable.
Syntax
Example
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
87
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
PHP $_COOKIE
Example
File: cookie1.php
1. <?php
2. setcookie("user", "Sonoo");
3. ?>
4. <html>
5. <body>
6. <?php
7. if(!isset($_COOKIE["user"])) {
8. echo "Sorry, cookie is not found!";
9. } else {
10. echo "<br/>Cookie Value: " . $_COOKIE["user"];
11. }
12. ?>
13. </body>
14. </html>
Output:
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
88
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
Firstly cookie is not set. But, if you refresh the page, you will see cookie is
set now.
Output:
File: cookie1.php
1. <?php
2. setcookie ("CookieName", "", time() - 3600);// set the expiration date
to one hour ago
3. ?>
o mysqli_connect()
o PDO::__construct()
PHP mysqli_connect()
Syntax
1. resource mysqli_connect (server, username, password)
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
89
Gayatri Vidya Parishad College of Engineering (Autonomous)
Web Programming
PHP mysqli_close()
Syntax
1. bool mysqli_close(resource $resource_link)
Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_error());
9. }
10. echo 'Connected successfully';
11. mysqli_close($conn);
12. ?>
Output:
Connected successfully
Web Programming
Gayatri Vidya Parishad College of Engineering (Autonomous)
Computer Science And Engineering
90