Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 135

Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

PimpriChinchwad Education Trust’s


PIMPRI CHINCHWAD COLLEGE OF ENGINEERING AND
RESEARCH, RAVET
Department of Computer Engineering

Subject: Web Technology Lab (310256) Semester: VI


Class : TE Computer Practical /Week: 2Hrs/week

List of Assignments
Sr. Page
Name of Assignments
No. No.
Installation and Configuration of Web Application Servers Tomcat, 2
1 Apache, WebSphere, JBoss, GlassFish.

Design and develop any suitable web application using HTML, CSS and 8
2 XML in consultation of course instructor.

Perform validation of all fields in assignment no.1 by using Java 29


3 script/JQuery.

Add dynamic web application essence in assignment no. 2 using Servlet, 50


4 JSP and backend.

Add dynamic web application essence in assignment no. 2 using PHP, 69


5 MySQL database connectivity and AJAX controls.

Re-Design, develop and deploy assignment no. 3 of unit –III using Strut. 88
6
Re-Design, develop and deploy assignment no. 4 of unit –IV using Angular 107
7
JS.
Design, Develop and Deploy separate web application using 123
8
EJB/CMS/JSF/Spring/Bootstrap.

Subject Incharge H. O. D
Mr. Korade N.B. Mr. M. B. Salunke

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page1
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 1
Title: TOMCAT SERVER installation.
Objectives: Understand how to install tomcat server and set up environment
variables.
Problem Statement: Installation of TOMCAT Server and Configuration of it.
Outcome: Students will be able to:
1. Install TOMCAT Server and Configuration of it .
Software & Hardware Requirments:
1. Java 7 or Later
2. Apache Tomcat Server
Theory:
1. Introduction:
In a technical sense, a server is an instance of a computer program that
accepts and responds to requests made by another program, known as a client. Less
formally, any device that runs server software could be considered a server as well.
Servers are used to manage network resources. For example, a user may setup a
server to control access to a network, send/receive e-mail, manage print jobs, or host
a website.

1.1 Web server


Computer or collection of computers used to deliver web pages and other content to
multiple users. Below are some examples of web server software. It can respond to
the client request in either of the following two possible ways:
 Generating response by using the script and communicating with database.
 Sending file to the client associated with the requested URL.
The block diagram representation of Web Server is shown below:

 If the requested web page at the client side is not found, then web server will
sends the HTTP response: Error 404 Not found.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page2
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

 When the web server searching the requested page if requested page is found
then it will send to the client with an HTTP response.
 If the client requests some other resources then web server will contact to
application server and data is store for constructing the HTTP response.

1.2 Application server


The application server is a framework, an environment where applications can
run, no matter what they are or what functions they perform. An application server
can be used to develop and run web-based applications. There are a number of
different types of application servers, including Java, PHP and .NET Framework
application servers. Application servers provide a number of advantages. They
provide data and code integrity by allowing for a more centralized approach to
updates and upgrades to applications. They provide security by centralizing the
management of data access and the authentication process. Performance can be
improved for heavy usage applications by limiting network traffic performance-tier
traffic.
Application server contains Web and EJB containers. It can be used for servlet,
jsp, struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a
server centric architecture. It provides the middleware services for state maintenance
and security, along with persistence and data access. It is a type of server designed to
install, operate and host associated services and applications for the IT services, end
users and organizations.

2. Apache Tomcat
Apache Tomcat, often referred to as Tomcat Server, is an open-source Java
Servlet Container developed by the Apache Software Foundation (ASF). Tomcat
implements several Java EE specifications including Java Servlet, JavaServer Pages
(JSP), Java EL, and WebSocket, and provides a "pure Java" HTTP web server
environment in which Java code can run.

2.1 Setting Environment Variable on Windows7


Here we have considered Tomcat 7.0 and jdk1.8.0_162.
1. Download and install jdk, Download latest version of Tomcat from
https://tomcat.apache.org/
2. On Windows7, right-click on My Computer, select Properties, then Advanced,
then Environment Variables.
3. Under system variable select new or edit if already present and set following
variables.
Variable Value
JAVA_HOME C:\Program Files\Java\jdk1.8.0_162;
PATH C:\Program Files\Java\jdk1.8.0_162\bin
CATALINA_HOME C:\Program Files\Apache Software
Foundation\Tomcat 7.0;
CLASSPATH C:\Program Files\Apache Software
Foundation\Tomcat 7.0\lib\servlet-api;

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page3
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. Open Command Prompt and enter java to check Environment Variable are set
properly or not. The output is as below:

5. Now, you will see the Tomcat home page, which is provided by the Tomcat
Web server running on your computer. Open browser Mozilla or Google
Chrome and enter URL as : http://localhost:8080/

2.1.1 How to Run Tomcat


Following are the steps to check whether Tomcat has been installed successfully or
not-
1. Find start program in the Programs Menu. Look under Apache Tomcat and
select "Monitor Tomcat". Here you can start and stop tomcat.
2. Open any web browser and type in the given URL: http://localhost:8080/

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page4
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.2 Installing Tomcat on Ubuntu.

1. The first thing you will want to do is update your apt-get package lists:
$sudo apt-get update
2. Now you are ready to install Tomcat. Run the following command to start the
installation:
$sudo apt-get install tomcat7
3. Answer yes at the prompt to install tomcat. This will install Tomcat and its
dependencies, such as Java, and it will also create the tomcat7 user. It also starts
Tomcat with its default settings.
4. Let's make a quick change to the Java options that Tomcat uses when it starts.
Open the Tomcat7 parameters file:
$sudo nano /etc/default/tomcat7
5. Find the JAVA_OPTS line and replace it with the following. Feel free to change the
Xmx and MaxPermSize values—these settings affect how much memory Tomcat will
use:
/etc/default/tomcat7 — JAVA_OPTS

#JAVA_OPTS="-Djava.security.egd=file:/dev/./urandom -
Djava.awt.headless=true -Xmx512m -XX:MaxPermSize=256m -
XX:+UseConcMarkSweepGC"

6. Save and exit.


7. Now restart Tomcat with this command:
$sudo service tomcat7 restart
8. Tomcat is not completely set up yet, but you can access the default splash page by
going to your domain or IP address followed by :8080 in a web browser:
9. Open in web browser:
http://server_IP_address:8080
10. Configure Tomcat Web Management Interface
10.1 In order to use the manager webapp installed in Step 3, we must add a login to
our Tomcat server. We will do this by editing the tomcat-users.xml file:
$sudo nano /etc/tomcat7/tomcat-users.xml
10.2 This file is filled with comments which describe how to configure the file. You
may want to delete all the comments between the following two lines, or you may
leave them if you want to reference the examples:
tomcat-users.xml excerpt

<tomcat-users>
...
</tomcat-users>

10.3 You will want to add a user who can access the manager-gui and admin-gui (the
management interface that we installed in Step Three). You can do so by defining a
user similar to the example below. Be sure to change the username and password to
something secure:

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page5
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

tomcat-users.xml — Admin User

<tomcat-users>
<user username="admin" password="password" roles="manager-
gui,admin-gui"/>
</tomcat-users>

10.4 Save and quit the tomcat-users.xml file. To put our changes into effect, restart
the Tomcat service:
$sudo service tomcat7 restart

2.3 Tomcat's Directories


It contains the following sub-directories:
bin: It contains the binaries; startup script (startup.bat for Windows and startup.sh
for Unix and Mac OS), shutdown script (shutdown.bat for Windows and
shutdown.sh for Unix and Mac OS), as well as other binaries and scripts.
conf: It contains the system-wide configuration files such as server.xml, web.xml,
context.xml, and tomcat-users.xml.
lib: It contains the Tomcat's system-wide JAR files, which can be accessible by all
webapps. We can also place external JAR file (such as MySQL JDBC Driver).
logs: It contains log files of Tomcat. Also, you can check error messages here.
webapps: It contains the webapps to be deployed. You can also place the WAR
(Webapp Archive) file for deployment here.
work: Tomcat's working directory used by JSP, for JSP-to-Servlet conversion.
temp: Temporary files are stored in this directory.

Conclusion:
Hence, we have learned how to install and configure tomcat server.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page6
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:
1. What is Tomcat?
2. What is the tomcat default port?
3. What services are provided by Tomcat?
4. Explain directory structure of tomcat.
5. How to stop/start Apache Web Server?
6. How to check the version of running Apache Web Server?
7. How To We Can Change Tomcat Default Port?
8. Explain Directory Structure Of Tomcat?
9. Explain What Is Tomcat Valve?
10. Explain what is Jasper?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page7
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 2
Title: Web Development Using HTML, CSS, XML.
Objectives:
1. Understand about basic concepts of html
2. Understand the basic concepts of XML
3. Understand the basic concepts of CSS
Problem Statement: Design and develop any suitable web application using HTML, CSS
and XML in consultation of course instructor.
Outcome: Students will be able to:
1. Design static webpage using HTML.
2. Apply CSS to HTML pages.
3. Use XML for Data Storage
Software & Hardware Requirments:
1. Notepad/Notepad++
2. Browser(Google Chrome/Internet Explorer)
Theory:
1. HTML:
HTML stands for Hyper Text Markup Language, which is the most widely used language
on Web to develop web pages. HTML was created by Berners-Lee in late 1991 but "HTML
2.0" was the first standard HTML specification which was published in 1995. HTML 4.01
was a major version of HTML and it was published in late 1999. Though HTML 4.01 version
is widely used but currently we are having HTML-5 version which is an extension to HTML
4.01, and this version was published in 2012.
 Hypertext refers to the way in which Web pages (HTML documents) are linked
together. Thus, the link available on a webpage is called Hypertext.
 As its name suggests, HTML is a Markup Language which means you use HTML to
simply "mark-up" a text document with tags that tell a Web browser how to structure
it to display.
1.1 Basic HTML Document
<!DOCTYPE html>
<html>
<head>
<title>This is document
title</title>
</head>
<body>
<h1>This is a heading</h1>
<p>Document content goes
here.....</p>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page8
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Tag & Description

<!DOCTYPE...> This tag defines the document type and HTML version.

<html> This tag encloses the complete HTML document and mainly comprises of
document header which is represented by <head>...</head> and document body which is
represented by <body>...</body> tags.

<head> This tag represents the document's header which can keep other HTML tags like
<title>, <link> etc.

<title> The <title> tag is used inside the <head> tag to mention the document title.

<body> This tag represents the document's body which keeps other HTML tags like <h1>,
<div>, <p> etc.

<h1> This tag represents the heading.

<p> This tag represents a paragraph.


1.2 HTML - Basic Tags
1.2.1 Heading Tags
Any document starts with a heading. You can use different sizes for your headings. HTML
also has six levels of headings, which use the elements <h1>, <h2>, <h3>, <h4>,
<h5>, and <h6>. While displaying any heading, browser adds one line before and one line
after that heading.
<body> This is heading 1
<h1>This is heading 1</h1> This is heading 2
<h2>This is heading 2</h2> This is heading 3
<h3>This is heading 3</h3> This is heading 4
<h4>This is heading 4</h4> This is heading 5
<h5>This is heading 5</h5> This is heading 6
<h6>This is heading 6</h6>
</body>
1.2.2 Paragraph Tag
The <p> tag offers a way to structure your text into different paragraphs. Each paragraph of
text should go in between an opening <p> and a closing </p> tag as shown below in the
example −
<body>
<p>Here is a first paragraph of text.</p>
<p>Here is a second paragraph of text.</p>
<p>Here is a third paragraph of text.</p>
</body>
1.2.3 Line Break Tag
Whenever you use the <br /> element, anything following it starts from the next line. This
tag is an example of an emptyelement, where you do not need opening and closing tags, as
there is nothing to go in between them.
You delivered your assignment ontime.<br />

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page9
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.2.4 Centering Content


You can use <center> tag to put any content in the center of the page or any table cell.
<center>
<p>This text is in the center.</p>
</center>

1.2.5 Horizontal Lines


Horizontal lines are used to visually break-up sections of a document. The <hr> tag creates a
line from the current position in the document to the right margin and breaks the line
accordingly.
<body>
<p>This is paragraph one and should be on top</p>
<hr />
<p>This is paragraph two and should be at bottom</p>
</body>
1.3 HTML - Colors
Colors are very important to give a good look and feel to your website. You can specify
colors on page level using <body> tag or you can set colors for individual tags
using bgcolor attribute.
The <body> tag has following attributes which can be used to set different colors −
 bgcolor − sets a color for the background of the page.
 text − sets a color for the body text.
 alink − sets a color for active links or selected links.
 link − sets a color for linked text.
 vlink − sets a color for visited links − that is, for linked text that you have already
clicked on.

1.3.1 HTML Color Coding Methods


There are following three different methods to set colors in your web page.
 Color names − You can specify color names directly like green, blue or red.
 Hex codes − A six-digit code representing the amount of red, green, and blue that
makes up the color.
 Color decimal or percentage values − This value is specified using the rgb( )
property.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page10
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.3.2 Color Names


You can specify direct a color name to set text or background color. W3C has listed 16 basic
color names that will validate with an HTML validator but there are over 200 different color
names supported by major browsers.
<body text = "blue" bgcolor = "green">
<p>Use different color names for for body and table and see the
result.</p>
<table bgcolor = "black">
<tr>
<td>
<font color = "white">This text will appear white on black
background.</font>
</td>
</tr>
</table>
</body>

1.3.4 Hex Codes


A hexadecimal is a 6 digit representation of a color. The first two digits(RR) represent a red
value, the next two are a green value(GG), and the last are the blue value(BB).
<body text = "#0000FF" bgcolor = "#00FF00">
<p>Use different color hexa for body and table and see the result.</p>
<table bgcolor = "#000000">
<tr>
<td>
<font color = "#FFFFFF">This text will appear white on
black background.</font>
</td>
</tr>
</table>
</body>

1.3.5 RGB Values


This color value is specified using the rgb( ) property. This property takes three values, one
each for red, green, and blue. The value can be an integer between 0 and 255 or a percentage.
<body text = "rgb(0,0,255)" bgcolor = "rgb(0,255,0)">
<p>Use different color code for for body and table and see the
result.</p>
<table bgcolor = "rgb(0,0,0)">
<tr>
<td>
<font color = "rgb(255,255,255)">This text will appear
white on black background.</font>
</td>
</tr>
</table>
</body>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page11
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.4 Fonts
The font tag is having three attributes called size, color, and face to customize your fonts. To
change any of the font attributes at any time within your webpage, simply use the <font> tag.
The text that follows will remain changed until you close with the </font> tag. You can
change one or all of the font attributes within one <font> tag.

1.4.1 Set Font Size


You can set content font size using size attribute. The range of accepted values is from
1(smallest) to 7(largest). The default size of a font is 3.
<body>
<font size = "1">Font size = "1"</font><br />
<font size = "2">Font size = "2"</font><br />
<font size = "3">Font size = "3"</font><br />
<font size = "4">Font size = "4"</font><br />
<font size = "5">Font size = "5"</font><br />
<font size = "6">Font size = "6"</font><br />
<font size = "7">Font size = "7"</font>
</body>

1.4.2 Relative Font Size


You can specify how many sizes larger or how many sizes smaller than the preset font size
should be. You can specify it like <font size = "+n"> or <font size = "−n">
<body>
<font size = "-1">Font size = "-1"</font><br />
<font size = "+1">Font size = "+1"</font><br />
<font size = "+2">Font size = "+2"</font><br />
<font size = "+3">Font size = "+3"</font><br />
<font size = "+4">Font size = "+4"</font>
</body>

1.4.3 Setting Font Face


You can set font face using face attribute but be aware that if the user viewing the page
doesn't have the font installed, they will not be able to see it. Instead user will see the default
font face applicable to the user's computer.
<body>
<font face = "Times New Roman" size = "5">Times New Roman</font><br
/>
<font face = "Verdana" size = "5">Verdana</font><br />
<font face = "Comic sans MS" size =" 5">Comic Sans MS</font><br />
<font face = "WildWest" size = "5">WildWest</font><br />
<font face = "Bedrock" size = "5">Bedrock</font><br />
</body>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page12
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2. CSS
2.1 What is CSS?
 CSS stands for Cascading Style Sheets
 CSS describes how HTML elements are to be displayed on screen, paper, or in
other media
 CSS saves a lot of work. It can control the layout of multiple web pages all at once
 External stylesheets are stored in CSS files
 CSS is used to define styles for your web pages, including the design, layout and
variations in display for different devices and screen sizes.

2.2 CSS Syntax:


A CSS rule-set consists of a selector and a declaration block:

 The selector points to the HTML element you want to style.


 The declaration block contains one or more declarations separated by semicolons.
 Each declaration includes a CSS property name and a value, separated by a colon.
 A CSS declaration always ends with a semicolon, and declaration blocks are
surrounded by curly braces.

2.3 CSS Selectors:


CSS selectors are used to "find" (or select) HTML elements based on their element name, id,
class, attribute, and more.

2.3.1 The element Selector


The element selector selects elements based on the element name. You can select all <p>
elements on a page like this (in this case, all <p> elements will be center-aligned, with a red
text color):
<!DOCTYPE html>
<html><head>
<style>
p {
color: red;
text-align: center;
}
</style>
</head>
<body>
<p>Hello World!</p>
<p>This paragraph is styled with
CSS.</p>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page13
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.3.2 The id Selector


The id selector uses the id attribute of an HTML element to select a specific element.
The id of an element should be unique within a page, so the id selector is used to select one
unique element!
To select an element with a specific id, write a hash (#) character, followed by the id of the
element.
The style rule below will be applied to the HTML element with id="para1".

<!DOCTYPE html>
<html>
<head>
<style>
#para1 {
text-align: center;
color: red;
}
</style>
</head>
<body>
<p id="para1">Hello World!</p>
<p>This paragraph is not affected
by the style.</p>
</body>
</html>

2.3.3 The class Selector:


The class selector selects elements with a specific class attribute.
To select elements with a specific class, write a period (.) character, followed by the name of
the class.
In the example below, all HTML elements with class="center" will be red and center-aligned.

<!DOCTYPE html>
<html><head>
<style>
.center {
text-align: center;
color: red;
}
</style>
</head>
<body>
<h1 class="center">Red and center-
aligned heading</h1>
<p class="center">Red and center-
aligned paragraph.</p>
</body></html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page14
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.4 Types:
2.4.1 External Style Sheet:
With an external style sheet, you can change the look of an entire website by changing just
one file. An external style sheet can be written in any text editor. The file should not contain
any html tags. The style sheet file must be saved with a .css extension. Each page must
include a reference to the external style sheet file inside the <link> element. The <link>
element goes inside the <head> section:
mystyle.css
body {
background-color:
lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}

<html>
<head>
<link rel="stylesheet"
type="text/css" href="mystyle.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

2.4.2 Internal Style Sheet:


An internal style sheet may be used if one single page has a unique style. Internal styles are
defined within the <style> element, inside the <head> section of an HTML page:
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: linen;
}
h1 {
color: maroon;
margin-left: 40px;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body></html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page15
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.4.3 Inline Styles:


An inline style may be used to apply a unique style for a single element.
To use inline styles, add the style attribute to the relevant element. The style attribute can
contain any CSS property.
The example below shows how to change the color and the left margin of a <h1> element:
<!DOCTYPE html>
<html>
<body>
<h1 style="color:blue; margin-
left:30px;"> This is a heading.
</h1>
<p>This is a paragraph.</p>
</body>
</html>

3. XML
XML stands for Extensible Markup Language and is a text-based markup language
derived from Standard Generalized Markup Language (SGML).
 XML is extensible − XML allows you to create your own self-descriptive tags, or
language, that suits your application.
 XML carries the data, does not present it − XML allows you to store the data
irrespective of how it will be presented.
 XML is a public standard − XML was developed by an organization called the
World Wide Web Consortium (W3C) and is available as an open standard.

3.1 Difference Between XML and HTML


XML and HTML were designed with different goals:
 XML was designed to carry data - with focus on what data is
 HTML was designed to display data - with focus on how data looks
 XML is often used to separate data from presentation.
 XML tags are not predefined like HTML tags are

3.2 XML Syntax Rules


1. XML Documents Must Have a Root Element: XML documents must contain
one root element that is the parent of all other elements
<root>
<child>
<subchild>.....</subchild>
</child>
</root>
2. XML Declaration: The XML document can optionally have an XML declaration. It
is written as follows
<?xml version = "1.0" encoding = "UTF-8"?>
Syntax Rules for XML Declaration
 The XML declaration is case sensitive and must begin with "<?xml>" where
"xml" is written in lower-case.
 If document contains XML declaration, then it strictly needs to be the first
statement of the XML document.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page16
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

 The XML declaration strictly needs be the first statement in the XML
document.
 An HTTP protocol can override the value of encoding that you put in the XML
declaration.

3. All XML Elements Must Have a Closing Tag :In HTML, some elements might
work well, even with a missing closing tag, In XML, it is illegal to omit the closing
tag. All elements must have a closing tag.

4. XML Tags are Case Sensitive : XML tags are case sensitive. The tag <Letter> is
different from the tag <letter>. Opening and closing tags must be written with
the same case

5. XML Elements Must be Properly Nested: In HTML, you might see improperly
nested elements:
<b><i>This text is bold and
italic</b></i>
XML Elements Must be Properly Nested.
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this
weekend!</body>
</note>

6. XML Attribute Values Must be Quoted :XML elements can have attributes in
name/value pairs just like in HTML. In XML, the attribute values must always be
quoted.
<note date="12/11/2007">
<to>Tove</to>
<from>Jani</from>
</note>

7. Entity References : Some characters have a special meaning in XML. If you place a
character like "<" inside an XML element, it will generate an error because the parser
interprets it as the start of a new element.
<message>salary &lt; 1000</message>
There are 5 pre-defined entity references in XML:
&lt; < less than

&gt; > greater than

&amp; & ampersand

&apos; ' apostrophe

&quot; " quotation mark

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page17
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

8. Comments in XML : The syntax for writing comments in XML is similar to that of
HTML.
<!-- This is a comment -->

9. White-space is Preserved in XML : XML does not truncate multiple white-spaces


(HTML truncates multiple white-spaces to one single white-space).

Conclusion:
Hence, we have designed static web pages using HTML, CSS and CSS.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page18
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program
1. style.css
body
{
background-image: url("img.jpeg");
background-repeat: no-repeat;
background-size: cover;
}
a
{
margin: 100px 0 0 36px;
}
.login
{
border: 2px solid;
border-radius: 5px;
height: 200px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
.register
{
border: 2px solid;
border-radius: 5px;
height: 350px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
input[type="password"], input[type="text"]
{
border:1px solid;
background-color:rgba(0,0,0,0.0);
height: 33px;
width:240px;
margin: 2px 0 0 36px;
padding-left: 10px;
}

input[type="submit"]
{
background-color: #4CAF50;
color: white;
height: 42px;
margin: 10px 0 0 36px;
width: 250px;
padding-left: 10px;
}
input[type="submit"]:hover
{
background-image: linear-gradient(#4ec7c0,#31aba3)
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page19
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

input[type="submit"]:active
{
background-image: linear-gradient(#319d91, #3db0a6);
padding: 0;
}

2. login.html
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div class="login">
<form action="" name="myform" onsubmit="loadDoc()" method="post">
<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<input type="submit" value="Login">
<a href="register.html"> Register Yourself</a>
</form>
</div>

<script>
function loadDoc()
{
//document.write("2");
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
myFunction(this);
}
};
xhttp.open("GET", "database.xml", true);
xhttp.send();
}
function myFunction(xml)
{
//document.write("1");
var i;
var flag=0;
var xmlDoc = xml.responseXML;
var username = document.getElementById("username").value;
var userpass = document.getElementById("password").value;
//document.write("Username "+username+" password "+userpass+"
");

var x = xmlDoc.getElementsByTagName("account");

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page20
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

// document.write(x.length);
for (i = 0; i <x.length; i++)
{
var
name=x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var
pass=x[i].getElementsByTagName("pass")[0].childNodes[0].nodeValue;

document.write("<br>"+name+" "+pass+" ");


if(username.localeCompare(name))
{

}
else
{
flag=1;
}
}

if(flag==1)
{
window.location="home.html";
}
else
{
document.write(" <a href=\"login.html\"> Login again </a>
Username password wrong....");
}
}
</script>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page21
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. home.html
<!DOCTYPE html>
<html>
<body>
<center><h2> <font color="red">Welcome to Course Consultation
Website</h2></font>
<table border="1">
<tr>
<th>Qualification</th>
<th>Intrest</th>
<th>Course Suggestion</th>
</tr>
<tr>
<td>12th</td>
<td>Programming</td>
<td>C,C++</td>
</tr>
<tr>
<td>12th</td>
<td>Web Design</td>
<td>HTML,CSS,JavaScript</td>
</tr>
<tr>
<td>12th</td>
<td>Car Design</td>
<td>AutoCAD, CATIA</td>
</tr>
<tr>
<td>12th</td>
<td>Robotics</td>
<td>Artificial Intelligence and Robotics</td>
</tr>
</table>
</center>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page22
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. register.html
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>

<body>
<div class="register">
<form action="addentry.php" name="myform" method="post">
<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<label><b>Mobile Number</b></label>
<input type="text" name="mobile" id="mobile" placeholder= "Mobile
Number" required="required" onfocus="this.value = '';">
<label><b>E-Mail Address</b></label>
<input type="text" name="email" id="email" placeholder= "E-Mail
Address" required="required" onfocus="this.value = '';">
<label><b>Age</b></label>
<input type="text" name="age" id="age" placeholder= "Age"
required="required" onfocus="this.value = '';">

<input type="submit" value="Register">

</form>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page23
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. addentry.php
<?php
$xmldoc = new DomDocument( '1.0' );
$xmldoc->preserveWhiteSpace = false;
$xmldoc->formatOutput = true;

$name = $_POST['username'];
$pass = $_POST['password'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$age = $_POST['age'];

if( $xml = file_get_contents( 'database.xml') ) {


$xmldoc->loadXML( $xml, LIBXML_NOBLANKS );

// find the headercontent tag


$root = $xmldoc->getElementsByTagName('profile')->item(0);

// create the <product> tag


$account = $xmldoc->createElement('account');

// add the product tag before the first element in the


<headercontent> tag
$root->insertBefore( $account, $root->lastChild );

// create other elements and add it to the <product> tag.


$nameElement = $xmldoc->createElement('name');
$account->appendChild($nameElement);
$nameText = $xmldoc->createTextNode($name);
$nameElement->appendChild($nameText);

$passElement = $xmldoc->createElement('pass');
$account->appendChild($passElement);
$passText = $xmldoc->createTextNode($pass);
$passElement->appendChild($passText);

$emailElement = $xmldoc->createElement('email');
$account->appendChild($emailElement);
$emailText = $xmldoc->createTextNode($email);
$emailElement->appendChild($emailText);

$mobileElement = $xmldoc->createElement('mobile');
$account->appendChild($mobileElement);
$mobileText = $xmldoc->createTextNode($mobile);
$mobileElement->appendChild($mobileText);

$ageElement = $xmldoc->createElement('age');
$account->appendChild($ageElement);
$ageText = $xmldoc->createTextNode($age);
$ageElement->appendChild($ageText);

$xmldoc->save('database.xml');
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page24
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

?>

<html>
<body>
<h2>You are Successfully Register please<a href="login.html">go to
Login page</a></h2>
</body>
</html>

6. database.xml
<?xml version="1.0"?>
<users>
<profile>
<account>
<name>nilesh</name>
<pass>nilesh</pass>
<email>nil@gmail.com</email>
<mobile>8989898989</mobile>
<age>27</age>
</account>
<account>
<name>vivek</name>
<pass>vivek</pass>
<email>viv@gmail.com</email>
<mobile>9090909090</mobile>
<age>21</age>
</account>
</profile>
</users>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page25
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

OutPut:
1. Login

2. Home Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page26
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Registration Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page27
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:
1. What is the difference between HTML and HTML5?
2. What is the difference between html elements and tags?
3. What is marquee?
4. What is the use of span tag? Give an example?
5. What is the use of ‘required ’attribute in HTML5?
6. What is External stylesheet? What are the advantages and disadvantages?
7. What is CSS selector?
8. What are the components of CSS style?
9. What is browser safe color?
10. Explain difference between HTML and XML?
11. What is XML DOM?
12. Explain difference between CDATA and PCDATA?
13. What is mean by simple element and complex element?
14. What is XPATH?
15. Explain XSL and XSLT?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page28
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 3
Title: Validation using JavaScript.
Objectives:
1. Understand about basic concepts of JavaScript.
2. Use JavaScript for validation of data.
Problem Statement: Perform validation of all fields in Assignment no.1 by using Java
script/JQuery.
Outcome: Students will be able to:
1. Design static webpage using HTML,CSS.
2. Apply JavaScript to HTML pages for validation of data.
Software & Hardware Requirments:
1. Notepad/Notepad++
2. Browser(Google Chrome)
Theory:
1. JavaScript
1. 1. History
JavaScript is a lightweight, interpreted programming language. It is designed for
creating network-centric applications. It is complimentary to and integrated with Java.
JavaScript is very easy to implement because it is integrated with HTML. It is open and
cross-platform.
JavaScript is a dynamic computer programming language. It is lightweight and most
commonly used as a part of web pages, whose implementations allow client-side script to
interact with the user and make dynamic pages. It is an interpreted programming language
with object-oriented capabilities.
JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript made its
first appearance in Netscape 2.0 in 1995 with the name LiveScript.
The general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.
JavaScript is a lightweight, interpreted programming language.
Designed for creating network-centric applications.
Complementary to and integrated with Java.
Complementary to and integrated with HTML.
Open and cross-platform

1. 2. Limitations
Client-side JavaScript does not allow the reading or writing of files. This has been
kept for security reason.
JavaScript cannot be used for networking applications because there is no such
support available.
JavaScript doesn't have any multithreading or multiprocessor capabilities.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page29
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.3. </script>
JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within
you web page, but it is normally recommended that you should keep it within the
<head> tags.

The script tag takes two important attributes −


Language − This attribute specifies what scripting language you are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.

Type − This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript"

<script language="javascript" type="text/javascript">


JavaScript code
</script>

1.4. Example
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write("Hello World!")
//-->
</script>
</body>
</html>

The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we
add that to prevent a browser from reading the end of the HTML comment as a piece of
JavaScript code. Next, we call a function document.write which writes a string into our
HTML document.
This function can be used to write text, HTML, or both.

1.5. Whitespace and Line Breaks


JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs. You
can use spaces, tabs, and newlines freely in your program and you are free to format and
indent your programs in a neat and consistent way that makes the code easy to read and
understand.

1.6. Semicolons are Optional


Simple statements in JavaScript are generally followed by a semicolon character, just
as they are in C, C++, and Java. JavaScript, however, allows you to omit this semicolon if
each of your statements are placed on a separate line.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page30
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<script language="javascript" But when formatted in a single line as


type="text/javascript"> follows, you must use semicolons
<!-- <script language="javascript"
var1 = 10 type="text/javascript">
var2 = 20 <!--
//--> var1 = 10; var2 = 20;
</script> //-->
</script>

1.7. Case Sensitivity


JavaScript is a case-sensitive language. This means that the language keywords,
variables, function names, and any other identifiers must always be typed with a consistent
capitalization of letters.

1. 8. Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
Any text between a // and the end of a line is treated as a comment and is ignored by
JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
The HTML comment closing sequence --> is not recognized by JavaScript so it
should be written as //-->.

<script language="javascript" type="text/javascript">


<!--
// This is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>

1.9 Using JS in an HTML


There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows −
 Script in <head>...</head> section.
 Script in <body>...</body> section.
 Script in <body>...</body> and <head>...</head> sections.
 Script in an external file and then include in <head>...</head> section.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page31
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.9.1 JavaScript in <head>...</head> section


If you want to have a script run on some event, such as when a user clicks somewhere, then
you will place that script in the head as follows
<html>
<head>
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>
<body>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>

1.9.2 JavaScript in <body>...</body> section


If you need a script to run as the page loads so that the script generates content in the page,
then the script goes in the <body> portion of the document. In this case, you would not have
any function defined using JavaScript.
<html>
<head> </head>
<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>
<p>This is web page body </p>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page32
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.9.3 JavaScript in <body> and <head> Sections


<html>
<head>
<script type="text/javascript">
<!--
function sayHello()
{
alert("Hello World")
}
//-->
</script>
</head>

<body>
<script type="text/javascript">
<!--
document.write("Hello World")
//-->
</script>

<input type="button" onclick="sayHello()" value="Say Hello" />

</body>
</html>

1.9.4 JavaScript in External File


To use JavaScript from an external file source, you need to write all your JavaScript source
code in a simple text file with the extension ".js" and then include that file as shown above.

function sayHello()
{
alert("Hello World") //filename.js
}
<html>

<head>
<script type="text/javascript" src="filename.js" ></script>
</head>

<body>
< input type="button" onclick="sayHello()" value="Say Hello" /> </body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page33
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.10 Variables
One of the most fundamental characteristics of a programming language is the set of
data types it supports. These are the type of values that can be represented and manipulated in
a programming language.
JavaScript allows you to work with three primitive data types −
Numbers, eg. 123, 120.50 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.

Note − Java does not make a distinction between integer values and floating-point values. All
numbers in JavaScript are represented as floating-point values.

1.10.1 JavaScript Variables


Like many other programming languages, JavaScript has variables. Variables can be
thought of as named containers. You can place data into these containers and then refer to the
data simply by naming the container.
Before you use a variable in a JavaScript program, you must declare it. Variables are
declared with the var keyword as follows.
<script type="text/javascript">
<!--
var money;
var name;
//-->
</script>

You can also declare multiple variables with the same var keyword as follows −
<script type="text/javascript">
<!--
var money, name;
//-->
</script>

Storing a value in a variable is called variable initialization. You can do variable


initialization at the time of variable creation or at a later point in time when you need that
variable.
For instance, you might create a variable named money and assign the value 2000.50
to it later. For another variable, you can assign a value at the time of initialization as follows.
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
Note − Use the var keyword only for declaration or initialization, once for the life of any
variable name in a document. You should not re-declare same variable twice.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page34
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

JavaScript is untyped language. This means that a JavaScript variable can hold a
value of any data type. Unlike many other languages, you don't have to tell JavaScript during
variable declaration what type of value the variable will hold. The value type of a variable
can change during the execution of a program and JavaScript takes care of it automatically.

1.10.2 JavaScript Variable Scope


The scope of a variable is the region of your program in which it is defined.
JavaScript variables have only two scopes.
Global Variables − A global variable has global scope which means it can be defined
anywhere in your JavaScript code.
Local Variables − A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global variable with
the same name. If you declare a local variable or function parameter with the same name as a
global variable, you effectively hide the global variable. Take a look into the following
example.
<html>
<body onload = checkscope();>
<script type = "text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( )
{
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
</body>
</html>

1.10.3 JavaScript Variable Names


While naming your variables in JavaScript, keep the following rules in mind.
 You should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For example, break
or boolean variable names are not valid.
 JavaScript variable names should not start with a numeral (0-9). They must
begin with a letter or an underscore character. For example, 123test is an
invalid variable name but _123test is a valid one.
 JavaScript variable names are case-sensitive. For example, Name and name
are two different variables.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page35
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.11 Functions
Before we use a function, we need to define it. The most common way to define a function in
JavaScript is by using the function keyword, followed by a unique function name, a list of
parameters (that might be empty), and a statement block surrounded by curly braces.
<html>
<head>

<script type="text/javascript">
function sayHello()
{
document.write ("Hello there!");
}
</script>

</head>
<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>

<p>Use different text in write method and then try...</p>


</body>
</html>

<html>
<head>

<script type="text/javascript">
function concatenate(first, last)
{
var full;
full = first + last;
return full;
}

function secondFunction()
{
var result;
result = concatenate('Zara', 'Ali');
document.write (result );
}
</script>

</head>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page36
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<body>
<p>Click the following button to call the function</p>

<form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>

<p>Use different parameters inside the function and then try...</p>

</body>
</html>

1.12 Events
JavaScript's interaction with HTML is handled through events that occur when the user or the
browser manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an
event. Other examples include events like pressing any key, closing a window, resizing a
window, etc.
<html>
<head>
<script type="text/javascript">
function sayHello()
{
alert("Hello World")
}
</script>
</head>
<body>
<p>Click the following button and see result</p>
<form>
<input type="button" onclick="sayHello()" value="Say Hello" />
</form>
</body>
</html>

Conclusion:
Hence, we have learned how to use JavaScript for validation.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page37
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program
1. style.css
body
{
background-image: url("img.jpeg");
background-repeat: no-repeat;
background-size: cover;
}
a
{
margin: 100px 0 0 36px;
}
.login
{
border: 2px solid;
border-radius: 5px;
height: 200px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
.register
{
border: 2px solid;
border-radius: 5px;
height: 350px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
input[type="password"], input[type="text"]
{
border:1px solid;
background-color:rgba(0,0,0,0.0);
height: 33px;
width:240px;
margin: 2px 0 0 36px;
padding-left: 10px;
}

input[type="submit"]
{
background-color: #4CAF50;
color: white;
height: 42px;
margin: 10px 0 0 36px;
width: 250px;
padding-left: 10px;
}
input[type="submit"]:hover
{
background-image: linear-gradient(#4ec7c0,#31aba3)
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page38
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

input[type="submit"]:active
{
background-image: linear-gradient(#319d91, #3db0a6);
padding: 0;
}

2. login.html
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div class="login">
<form action="" name="myform" onsubmit="loadDoc()" method="post">
<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<input type="submit" value="Login">
<a href="register.html"> Register Yourself</a>
</form>
</div>

<script>
function loadDoc()
{
//document.write("2");
var xhttp = new XMLHttpRequest();

xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
myFunction(this);
}
};
xhttp.open("GET", "database.xml", true);
xhttp.send();
}
function myFunction(xml)
{
//document.write("1");
var i;
var flag=0;
var xmlDoc = xml.responseXML;
var username = document.getElementById("username").value;
var userpass = document.getElementById("password").value;
//document.write("Username "+username+" password "+userpass+"
");

var x = xmlDoc.getElementsByTagName("account");

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page39
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

// document.write(x.length);
for (i = 0; i <x.length; i++)
{
var
name=x[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
var
pass=x[i].getElementsByTagName("pass")[0].childNodes[0].nodeValue;

document.write("<br>"+name+" "+pass+" ");


if(username.localeCompare(name))
{

}
else
{
flag=1;
}
}

if(flag==1)
{
window.location="home.html";
}
else
{
document.write(" <a href=\"login.html\"> Login again </a>
Username password wrong....");
}
}
</script>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page40
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. home.html
<!DOCTYPE html>
<html>
<body>
<center><h2> <font color="red">Welcome to Course Consultation
Website</h2></font>
<table border="1">
<tr>
<th>Qualification</th>
<th>Intrest</th>
<th>Course Suggestion</th>
</tr>
<tr>
<td>12th</td>
<td>Programming</td>
<td>C,C++</td>
</tr>
<tr>
<td>12th</td>
<td>Web Design</td>
<td>HTML,CSS,JavaScript</td>
</tr>
<tr>
<td>12th</td>
<td>Car Design</td>
<td>AutoCAD, CATIA</td>
</tr>
<tr>
<td>12th</td>
<td>Robotics</td>
<td>Artificial Intelligence and Robotics</td>
</tr>
</table>
</center>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page41
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. register.html
<!DOCTYPE html>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
<script type="text/javascript">
function validateform()
{

var pass=document.myform.password.value;
if(pass.length<4)
{
alert("Enter Password At Least 4 Charactor");
return false;
}

var mobile=document.myform.mobile.value;
if(isNaN(mobile))
{
alert("Enter Digit Only in Mobile Number");
return false;
}

else if (mobile.length<10||mobile.length>10)
{
alert("Enter Mobile Number 10 Digit Only");
return false;
}
var email = document.myform.email.value;
var atpos = email.indexOf("@");
var dotpos = email.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
var age=document.myform.age.value;
if(isNaN(age))
{
alert("Enter Digit Only in Age");
return false;
}
return true;
}
</script>
</head>

<body>
<div class="register">
<form action="addentry.php" name="myform" onsubmit="return
validateform()" method="post">
<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page42
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<input type="password" name="password" id="password"


placeholder="password" required="required" onfocus="this.value =
'';">
<label><b>Mobile Number</b></label>
<input type="text" name="mobile" id="mobile" placeholder= "Mobile
Number" required="required" onfocus="this.value = '';">
<label><b>E-Mail Address</b></label>
<input type="text" name="email" id="email" placeholder= "E-Mail
Address" required="required" onfocus="this.value = '';">
<label><b>Age</b></label>
<input type="text" name="age" id="age" placeholder= "Age"
required="required" onfocus="this.value = '';">

<input type="submit" value="Register">

</form>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page43
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. addentry.php
<?php
$xmldoc = new DomDocument( '1.0' );
$xmldoc->preserveWhiteSpace = false;
$xmldoc->formatOutput = true;

$name = $_POST['username'];
$pass = $_POST['password'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$age = $_POST['age'];

if( $xml = file_get_contents( 'database.xml') ) {


$xmldoc->loadXML( $xml, LIBXML_NOBLANKS );

// find the headercontent tag


$root = $xmldoc->getElementsByTagName('profile')->item(0);

// create the <product> tag


$account = $xmldoc->createElement('account');

// add the product tag before the first element in the


<headercontent> tag
$root->insertBefore( $account, $root->lastChild );

// create other elements and add it to the <product> tag.


$nameElement = $xmldoc->createElement('name');
$account->appendChild($nameElement);
$nameText = $xmldoc->createTextNode($name);
$nameElement->appendChild($nameText);

$passElement = $xmldoc->createElement('pass');
$account->appendChild($passElement);
$passText = $xmldoc->createTextNode($pass);
$passElement->appendChild($passText);

$emailElement = $xmldoc->createElement('email');
$account->appendChild($emailElement);
$emailText = $xmldoc->createTextNode($email);
$emailElement->appendChild($emailText);

$mobileElement = $xmldoc->createElement('mobile');
$account->appendChild($mobileElement);
$mobileText = $xmldoc->createTextNode($mobile);
$mobileElement->appendChild($mobileText);

$ageElement = $xmldoc->createElement('age');
$account->appendChild($ageElement);
$ageText = $xmldoc->createTextNode($age);
$ageElement->appendChild($ageText);

$xmldoc->save('database.xml');
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page44
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

?>

<html>
<body>
<h2>You are Successfully Register please<a href="login.html">go to
Login page</a></h2>
</body>
</html>

6. database.xml
<?xml version="1.0"?>
<users>
<profile>
<account>
<name>nilesh</name>
<pass>nilesh</pass>
<email>nil@gmail.com</email>
<mobile>8989898989</mobile>
<age>27</age>
</account>
<account>
<name>vivek</name>
<pass>vivek</pass>
<email>viv@gmail.com</email>
<mobile>9090909090</mobile>
<age>21</age>
</account>
</profile>
</users>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page45
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

OutPut:
1. login

2. Home Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page46
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Registration

4. Validation using JavaScript

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page47
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:
1. Explain feature of JavaScript?
2. Explain how to define JavaScript in external file?
3. Explain how to define function in JavaScript?
4. What are the default objects available in JavaScript?
5. Explain advantages and limitation of JavaScript?
6. What is event in JavaScript? Explain with example?
7. Which dialog boxes available in JavaScript?
8. How to find HTML Elements using JavaScript?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page48
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 4
Title: Web Development using JSP, Servlet and MySQL(Backend).
Objectives:
1. Understand about basic concepts of Servlet & JSP
2. Having the knowledge of SQL query to create the database
Problem Statement: Add dynamic web application essence in assignment no. 2 using
Servlet, JSP and backend.

Outcome: Students will be able to,


1. Develop a dynamic webpage using JSP, HTML and Servlet.
2. Write a server side java application called Servlet to catch the data sent
from client, process it and store it on database (MySQL).
3. Write a server side java application called JSP to catch form data sent from
client and store it on database (MySQL).

Software & Hardware Requirments:


1. Ubuntu Operating System
2. JDK 7 or later
3. Editors: Eclipse
4. Web browser
5. Tomcat 7 or later

Theory:
1. Servlet
Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a request coming from a Web browser or other HTTP client and
databases or applications on the HTTP server. Using Servlets, you can collect input from
users through web page forms, present records from a database or another source, and create
web pages dynamically. Java Servlets often serve the same purpose as programs implemented
using the Common Gateway Interface (CGI).

1.1 Advantages in comparison with the CGI.


 Performance is significantly better.
 Servlets execute within the address space of a Web server. It is not necessary
to create a separate process to handle each client request.
 Servlets are platform-independent because they are written in Java.
 Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
 The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and
RMI mechanisms that you have seen already.

1.2 . Servlets - Life Cycle


The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
Department of Computer Engineering
PCET’s PCCOER, Pune-412101 Page49
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. service method is invoked.


5. destroy method is invoked.

The init() method :


The init method is designed to be called only once. It is called when the servlet is first
created, and not called again for each user request. So, it is used for one-time initializations,
just as with the init method of applets.
When a user invokes a servlet, a single instance of each servlet gets created, with each
user request resulting in a new thread that is handed off to doGet or doPost as appropriate.
The init() method simply creates or loads some data that will be used throughout the life of
the servlet.
The init method definition looks like this:
public void init() throws ServletException
{
// Initialization code...
}

The service() method :


The service() method is the main method to perform the actual task. The servlet
container (i.e. web server) calls the service() method to handle requests coming from the
client( browsers) and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread
and calls service. The service() method checks the HTTP request type (GET, POST, PUT,
DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
public void service(ServletRequest request, ServletResponse response)throws
ServletException, IOException
{
}

The destroy() method :


The destroy() method is called only once at the end of the life cycle of a servlet. This
method gives your servlet a chance to close database connections, halt background threads,
write cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage
collection.
public void destroy() \
{
// Finalization code...
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page50
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.3 Examples
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet
{
private String message;

public void init() throws ServletException


{
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy()


{
// do nothing.
}
}

2. JavaServer Pages.
JavaServer Pages (JSP) is a technology for developing web pages that support
dynamic content which helps developers insert java code in HTML pages by making use of
special JSP tags, most of which start with <% and end with %>.
A JavaServer Pages component is a type of Java servlet that is designed to fulfill the
role of a user interface for a Java web application. Web developers write JSPs as text files
that combine HTML or XHTML code, XML elements, and embedded JSP actions and
commands.
Using JSP, you can collect input from users through web page forms, present records
from a database or another source, and create web pages dynamically.
JSP tags can be used for a variety of purposes, such as retrieving information from a
database or registering user preferences, accessing JavaBeans components, passing control
between pages and sharing information between requests, pages etc.

2.1 Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the
CGI.
 Performance is significantly better because JSP allows embedding Dynamic Elements
in HTML Pages itself instead of having a separate CGI files.
Department of Computer Engineering
PCET’s PCCOER, Pune-412101 Page51
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

 JSP are always compiled before it's processed by the server unlike CGI/Perl which
requires the server to load an interpreter and the target script each time the page is
requested.
 JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also
has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB,
JAXP etc.
 JSP pages can be used in combination with servlets that handle the business logic, the
model supported by Java servlet template engines.
 Finally, JSP is an integral part of Java EE, a complete platform for enterprise class
applications. This means that JSP can play a part in the simplest applications to the
most complex and demanding.

2.2 Advantages of JSP:


Following is the list of other advantages of using JSP over other technologies:
 vs. Active Server Pages (ASP): The advantages of JSP are twofold. First, the
dynamic part is written in Java, not Visual Basic or other MS specific language, so it
is more powerful and easier to use. Second, it is portable to other operating systems
and non-Microsoft Web servers.
 vs. Pure Servlets: It is more convenient to write (and to modify!) regular HTML than
to have plenty of println statements that generate the HTML.
 vs. Server-Side Includes (SSI): SSI is really only intended for simple inclusions, not
for "real" programs that use form data, make database connections, and the like.
 vs. JavaScript: JavaScript can generate HTML dynamically on the client but can
hardly interact with the web server to perform complex tasks like database access and
image processing etc.
 vs. Static HTML: Regular HTML, of course, cannot contain dynamic information.

2.3 JSP - Architecture


The web server needs a JSP engine ie. container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes use of
Apache which has built-in JSP container to support JSP pages development.
A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that are part of
JSPs.
Following diagram shows the position of JSP container and JSP files in a Web Application.

JSP Processing:
The following steps explain how the web server creates the web page using JSP:
 As with a normal page, your browser sends an HTTP request to the web server.
 The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
 The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code that implements the
corresponding dynamic behavior of the page.
 The JSP engine compiles the servlet into an executable class and forwards the original
request to a servlet engine.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page52
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

 A part of the web server called the servlet engine loads the Servlet class and executes
it. During execution, the servlet produces an output in HTML format, which the
servlet engine passes to the web server inside an HTTP response.
 The web server forwards the HTTP response to your browser in terms of static HTML
content.
 Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
 All the above mentioned steps can be shown below in the following diagram:

2.4. JSP Compilation:


When a browser asks for a JSP, the JSP engine first checks to see whether it needs to
compile the page. If the page has never been compiled, or if the JSP has been modified since
it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
 Parsing the JSP.
 Turning the JSP into a servlet.
 Compiling the servlet.

2.4.1 JSP Initialization:


When a container loads a JSP it invokes the jspInit() method before servicing any
requests. If you need to perform JSP-specific initialization, override the jspInit() method:

public void jspInit()


{
// Initialization code...
}

Typically initialization is performed only once and as with the servlet init method,
you generally initialize database connections, open files, and create lookup tables in the
jspInit method.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page53
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.4.2 JSP Execution:


This phase of the JSP life cycle represents all interactions with requests until the JSP
is destroyed. Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:

void _jspService(HttpServletRequest request,


HttpServletResponse response)
{
// Service handling code...
}

The _jspService() method of a JSP is invoked once per a request and is responsible
for generating the response for that request and this method is also responsible for generating
responses to all seven of the HTTP methods ie. GET, POST, DELETE etc.

2.4.3 JSP Cleanup:


The destruction phase of the JSP life cycle represents when a JSP is being removed
from use by a container. The jspDestroy() method is the JSP equivalent of the destroy
method for servlets. Override jspDestroy when you need to perform any cleanup, such as
releasing database connections or closing open files.
The jspDestroy() method has the following form:

public void jspDestroy()


{
// Your cleanup code goes here.
}

2.5. JSP – Syntax


2.5.1 The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method
declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet:
<% code fragment %>

You can write XML equivalent of the above syntax as follows:


<jsp:scriptlet>
code fragment
</jsp:scriptlet>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page54
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Any text, HTML tags, or JSP elements you write must be outside the scriptlet.
Following is the simple and first example for JSP:
<html>
<head><title>Hello World</title></head>
<body>
Hello World!<br/>
<%
out.println("Your IP address is " + request.getRemoteAddr());
%>
</body>
</html>

2.5.2 JSP Declarations:


A declaration declares one or more variables or methods that you can use in Java code
later in the JSP file. You must declare the variable or method before you use it in the JSP file.
Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>
You can write XML equivalent of the above syntax as follows:
<jsp:declaration>
code fragment
</jsp:declaration>

Following is the simple example for JSP Declarations:


<%! int i = 0; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

2.5.3 JSP Expression:


A JSP expression element contains a scripting language expression that is evaluated,
converted to a String, and inserted where the expression appears in the JSP file.
Because the value of an expression is converted to a String, you can use an expression
within a line of text, whether or not it is tagged with HTML, in a JSP file.
The expression element can contain any expression that is valid according to the Java
Language Specification but you cannot use a semicolon to end an expression.
Following is the syntax of JSP Expression:
<%= expression %>
You can write XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>

Following is the simple example for JSP Expression:


<html>
<head><title>A Comment Test</title></head>
<body>
<p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page55
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.5.4 JSP Comments:


JSP comment marks text or statements that the JSP container should ignore. A JSP comment
is useful when you want to hide or "comment out" part of your JSP page.
Following is the syntax of JSP comments:
<%-- This is JSP comment --%>

Following is the simple example for JSP Comments:

2.6. JSP Directives:


A JSP directive affects the overall structure of the servlet class. It usually has the
following form:
<%@ directive attribute="value" %>

There are three types of directive tag:


Directive Description
Defines page-dependent attributes, such as scripting language,
<%@ page ... %>
error page, and buffering requirements.
<%@ include ... %> Includes a file during the translation phase.
Declares a tag library, containing custom actions, used in the
<%@ taglib ... %>
page

2.7. JSP Implicit Objects:


JSP supports nine automatically defined variables, which are also called implicit
objects. These variables are:
Objects Description
This is the HttpServletRequest object associated with the
request
request.
This is the HttpServletResponse object associated with the
response
response to the client.
out This is the PrintWriter object used to send output to the client.
session This is the HttpSession object associated with the request.
This is the ServletContext object associated with application
application
context.
config This is the ServletConfig object associated with the page.
This encapsulates use of server-specific features like higher
pageContext
performance JspWriters.
This is simply a synonym for this, and is used to call the
page
methods defined by the translated servlet class.
The Exception object allows the exception data to be accessed
Exception
by designated JSP.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page56
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Conclusion:
Hence, we have developed the dynamic web application using JSP, Servlet and MySQL.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page57
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program:
Project Structure

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page58
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1. style.css
body
{
background-image: url("img.jpeg");
background-repeat: no-repeat;
background-size: cover;
}
a
{
margin: 100px 0 0 36px;
}
.login
{
border: 2px solid;
border-radius: 5px;
height: 200px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
.register
{
border: 2px solid;
border-radius: 5px;
height: 350px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
input[type="password"], input[type="text"]
{
border:1px solid;
background-color:rgba(0,0,0,0.0);
height: 33px;
width:240px;
margin: 2px 0 0 36px;
padding-left: 10px;
}
input[type="submit"]
{
background-color: #4CAF50;
color: white;
height: 42px;
margin: 10px 0 0 36px;
width: 250px;
padding-left: 10px;
}
input[type="submit"]:hover
{
background-image: linear-gradient(#4ec7c0,#31aba3)
}

input[type="submit"]:active

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page59
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

{
background-image: linear-gradient(#319d91, #3db0a6);
padding: 0;
}

2. index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div class="login">
<form action="LoginValidate" name="myform" method="post">

<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<input type="submit" value="Login">
<a href="register.jsp"> Register Yourself</a>
</form>
</div>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page60
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. DBConnection.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class DBConnection
{
public boolean verify(String user,String pass)
{
boolean flag=false;
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/tecomp","roo
t","root");
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from
login");
while(rs.next())
{
String Dname= rs.getString("username");
String Dpass=rs.getString("password");
if(user.equals(Dname) && pass.equals(Dpass))
{
flag=true;
break;
}
}
con.close();
}
catch (Exception e)
{
e.printStackTrace();
}
if(flag==true)
return true;
else
return false;
}
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page61
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. LoginValidate.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/LoginValidate")
public class LoginValidate extends HttpServlet
{

protected void doPost(HttpServletRequest request,


HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();

String UserName=request.getParameter("username");
String Password=request.getParameter("password");
//out.println("Username :"+UserName);
//out.println("<br>Pass:"+Password);
DBConnection d=new DBConnection();
if(d.verify(UserName, Password))
{
RequestDispatcher
rd=request.getRequestDispatcher("Home.jsp");
rd.forward(request, response);
}
else
{
out.println("<b><center>Username or Password is
Wrong Please Retry</center></b>");
RequestDispatcher
rd=request.getRequestDispatcher("index.html");
rd.include(request, response);
}
}
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page62
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. Home.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center><h2> <font color="red">Welcome to Course Consultation
Website</h2></font>
<table border="1">
<tr>
<th>Qualification</th>
<th>Intrest</th>
<th>Course Suggestion</th>
</tr>
<tr>
<td>12th</td>
<td>Programming</td>
<td>C,C++</td>
</tr>
<tr>
<td>12th</td>
<td>Web Design</td>
<td>HTML,CSS,JavaScript</td>
</tr>
<tr>
<td>12th</td>
<td>Car Design</td>
<td>AutoCAD, CATIA</td>
</tr>
<tr>
<td>12th</td>
<td>Robotics</td>
<td>Artificial Intelligence and Robotics</td>
</tr>
</table>
</center>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page63
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

6. Register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>

<div class="register">
<form action="addDataTodatabase.jsp" name="myform" onsubmit="return
validateform()" method="post">

<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">

<br> <label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">

<br><label><b>Mobile Number</b></label>
<input type="text" name="mobile" id="mobile" placeholder= "Mobile
Number" required="required" onfocus="this.value = '';">

<br><label><b>E-Mail Address</b></label>
<input type="text" name="email" id="email" placeholder= "E-Mail
Address" required="required" onfocus="this.value = '';">

<br><label><b>Age</b></label>
<input type="text" name="age" id="age" placeholder= "Age"
required="required" onfocus="this.value = '';">

<br><input type="submit" value="Register">

</form>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page64
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

7. addDataTodatabase.jsp
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<%
boolean flag=false;
String username =request.getParameter("username");
String password =request.getParameter("password");
String mobile =request.getParameter("mobile");
String email =request.getParameter("email");
String age =request.getParameter("age");

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost/tecomp","roo
t","root");
Statement stmt=con.createStatement();
int i=stmt.executeUpdate("insert into login
values('"+username+"','"+password+"','"+mobile+"','"+email+"','"+age
+"')");

if(i>0)
{
//out.println("<b><font color=\"Red\"> You Have Register
Successfully <a href=\"index.html\">goto Login Page");
response.sendRedirect("index.html");
}
%>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page65
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Output:
1. Login Page

2. Home Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page66
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Registration Page

4. Database

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page67
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:
1. What is JSP?
2. What is Servlet?
3. What is the purpose of MySQL?
4. What is database?
5. What is the syntax of JSP?
6. How do we connect JSP file to database?
7. Explain life cycle of servlet?
8. What is session management?
9. Explain advantages of JSP over Servlet?
10. Explain Scriptlet, Expression, Declaration tag in JSP?
11. List default object in JSP?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page68
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 5
Title: web application using PHP, AJAX and MySQL.
Objectives To understand the principles and methodologies of web based applications
development process.
Problem Statement: Add dynamic web application essence in assignment no. 2 using PHP,
MySQL database connectivity and AJAX controls.
Outcome: Students should be able to,
1. Develop web based application using suitable client side and server side web
technologies.
2. Develop solution to complex problems using appropriate method, technologies,
frameworks, web services and content management.

Software & Hardware Requirments:


Software (Minimum Requirement):
1. Ubuntu 64 bit / Windows XP.
2. XAMPP Server
Hardware (Minimum Requirement):
1. Intel p4 Machine with 1GB ARM and 32GB HDD.

Theory:
1. PHP
The PHP Hypertext Preprocessor (PHP) is a programming language that allows web
developers to create dynamic content that interacts with databases. PHP is basically used for
developing web based software applications.
1.1 Introduction
 PHP started out as a small open source project that evolved as more and more people
found out how useful it was. Rasmus Lerdorf unleashed the first version of PHP way
back in 1994.
 PHP is a recursive acronym for "PHP: Hypertext Preprocessor".
 PHP is a server side scripting language that is embedded in HTML. It is used to
manage dynamic content, databases, session tracking, even build entire e-commerce
sites.
 It is integrated with a number of popular databases, including MySQL, PostgreSQL,
Oracle, Sybase, Informix, and Microsoft SQL Server.
 PHP supports a large number of major protocols such as POP3, IMAP, and LDAP.
PHP4 added support for Java and distributed object architectures (COM and
CORBA), making n-tier development a possibility for the first time.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page69
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.2 Features
 PHP Syntax is C-Like.
 PHP runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
 PHP is compatible with almost all servers used today (Apache, IIS, etc.)
 PHP supports a wide range of databases
 PHP is free. Download it from the official PHP resource: www.php.net
 PHP is easy to learn and runs efficiently on the server side
 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data
 PHP can send and receive cookies
 PHP can add, delete, modify data in your database
 PHP can be used to control user-access
 PHP can encrypt data

1.3 Sample code


<html>
<head> <title>First Program</title> </head>
<body>
<?php echo "Nilesh Korade!";?>
</body>
</html>

1.4 PHP - Syntax


1.4.1 Escaping to PHP
The PHP parsing engine needs a way to differentiate PHP code from other elements in the
page. The mechanism for doing so is known as 'escaping to PHP'. There are four ways to do
this:
Canonical PHP tags <?php...?>
<?...?>
Short-open tags <%...%>
<script language = "PHP">...</script>
ASP-style tags

HTML script tags

1.4.2 Commenting PHP Code


Single-line comments − They are generally used for short explanations or notes relevant to
the local code. Here are the examples of single line comments.
<?
# This is a comment, and
# This is the second line of the comment

// This is a comment too. Each style comments only


print "An example with single line comments";
?>
Multi-lines comments
/* This is a comment with multiline
Author : Nilesh Korade
Subject: PHP
*/

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page70
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.4.5 PHP – Variable


Here are the most important things to know about variables in PHP.
 All variables in PHP are denoted with a leading dollar sign ($).
 The value of a variable is the value of its most recent assignment.
 Variables are assigned with the = operator, with the variable on the left-hand side and
the expression to be evaluated on the right.
 Variables can, but do not need, to be declared before assignment.
 PHP does a good job of automatically converting types from one to another when
necessary.

PHP has a total of eight data types which we use to construct our variables −
Integers − are whole numbers, without a decimal point, like 4195.
Doubles − are floating-point numbers, like 3.14159 or 49.1.
Booleans − have only two possible values either true or false.
NULL − is a special type that only has one value: NULL.
Strings − are sequences of characters, like 'PHP supports string operations.'
Arrays − are named and indexed collections of other values.
Objects − are instances of programmer-defined classes, which can package up both
other kinds of values and functions that are specific to the class.
Resources − are special variables that hold references to resources external to PHP
(such as database connections).

<?php
$many = 2.2888800;
$many_2 = 2.2111200;
$few = $many + $many_2;
print("$many + $many_2 = $few <br>");
?>

1.4.5 PHP – constant


A constant is a name or an identifier for a simple value. A constant value cannot change
during the execution of the script.
 There is no need to write a dollar sign ($) before a constant, where as in Variable one
has to write a dollar sign.
 Constants cannot be defined by simple assignment, they may only be defined using
the define() function.
 Constants may be defined and accessed anywhere without regard to variable scoping
rules.
 Once the Constants have been set, may not be redefined or undefined.
<?php
define("MINSIZE", 50);

echo MINSIZE;
echo constant("MINSIZE"); // same thing as the previous line
?>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page71
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.5 PHP - Decision Making & Loops


1.5.1 The If...Else Statement
If you want to execute some code if a condition is true and another code if a condition
is false, use the if....else statement.
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
}
elseif ($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
1.5.2 PHP switch Statement
Use the switch statement to select one of many blocks of code to be executed.
<?php
$favcolor = "red";
switch ($favcolor)
{
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>

1.5.3 PHP while Loop


The while loop executes a block of code as long as the specified condition is true.
<?php
$x = 1;
while($x <= 5)
{
echo "The number is: $x <br>";
$x++;
}
?>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page72
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.5.4 PHP for Loop


The for loop is used when you know in advance how many times the script should
run.
<?php
for ($x = 0; $x <= 10; $x++)
{
echo "The number is: $x <br>";
}
?>

1.5.5 PHP foreach Loop


<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value)


{
echo "$value <br>";
}
?>

1.6 PhP Function


while creating a function its name should start with keyword function and all the PHP code
should be put inside { and } braces
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
function addFunction($num1, $num2)
{
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>

</body>
</html>

PHP Functions - Returning values :To let a function return a value, use the return
statement.
<?php
function sum($x, $y)
{
$z = $x + $y;
return $z;
}

echo "5 + 10 = " . sum(5, 10) . "<br>";


echo "7 + 13 = " . sum(7, 13) . "<br>";
echo "2 + 4 = " . sum(2, 4);
?>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page73
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.7. Using MySQL with PHP


PHP provides mysql_connect function to open a database connection. This function takes
five parameters and returns a MySQL link identifier on success, or FALSE on failure.
connection mysql_connect(server,user,passwd,new_link,client_flag);

Closing Database Connection:Its simplest function mysql_close PHP provides to close a


database connection.
bool mysql_close ( resource $link_identifier );

<?php
$dbhost = 'localhost:3036';
$dbuser = 'guest';
$dbpass = 'guest123';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($conn);
?>
Data can be entered into MySQL tables by executing SQL INSERT statement through PHP
function mysql_query.
<?php
$dbhost = 'localhost:3036';
$dbuser = 'root';
$dbpass = 'rootpassword';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'INSERT INTO employee '.
'(emp_name,emp_address, emp_salary, join_date) '.
'VALUES ( "guest", "XYZ", 2000, NOW() )';
mysql_select_db('test_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
?>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page74
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2. AJAX
AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating
better, faster, and more interactive web applications with the help of XML, HTML, CSS, and
Java Script.
 Ajax uses XHTML for content, CSS for presentation, along with Document Object
Model and JavaScript for dynamic content display.
 Conventional web applications transmit information to and from the sever using
synchronous requests. It means you fill out a form, hit submit, and get directed to a
new page with new information from the server.
 With AJAX, when you hit submit, JavaScript will make a request to the server,
interpret the results, and update the current screen. In the purest sense, the user would
never know that anything was even transmitted to the server.
 XML is commonly used as the format for receiving server data, although any format,
including plain text, can be used.
 AJAX is a web browser technology independent of web server software.
 A user can continue to use the application while the client program requests
information from the server in the background.
 Intuitive and natural user interaction. Clicking is not required, mouse movement is a
sufficient event trigger.
 Data-driven as opposed to page-driven.

AJAX is Based on Open Standards


AJAX is based on the following open standards −
 Browser-based presentation using HTML and Cascading Style Sheets (CSS).
 Data is stored in XML format and fetched from the server.
 Behind-the-scenes data fetches using XMLHttpRequest objects in the browser.
 JavaScript to make everything happen.

2.1 Steps of AJAX operation.


Steps of AJAX Operation
 A client event occurs.
 An XMLHttpRequest object is created.
 The XMLHttpRequest object is configured.
 The XMLHttpRequest object makes an asynchronous request to the Webserver.
 The Webserver returns the result containing XML document.
 The XMLHttpRequest object calls the callback() function and processes the result.
 The HTML DOM is updated.
Let us take these steps one by one.

The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object. The XMLHttpRequest object can
be used to exchange data with a server behind the scenes. This means that it is possible to
update parts of a web page, without reloading the whole page.
var xhttp = new XMLHttpRequest();
Department of Computer Engineering
PCET’s PCCOER, Pune-412101 Page75
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Send a Request To a Server


To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

AJAX - Server Response


The onreadystatechange Property
The readyState property holds the status of the XMLHttpRequest.
The onreadystatechange property defines a function to be executed when the readyState
changes.
The status property and the statusText property holds the status of the XMLHttpRequest
object.
Property Description

onreadystatechange Defines a function to be called when the readyState property changes

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

Conclusion:
Hence, we have studied how to design and develop small web application using PHP,
javascript, ajax, XAMPP server with apache server and MySQL as backend.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page76
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program
1. style.css
body
{
background-image: url("img.jpeg");
background-repeat: no-repeat;
background-size: cover;
}
a
{
margin: 100px 0 0 36px;
}
.login
{
border: 2px solid;
border-radius: 5px;
height: 200px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
.register
{
border: 2px solid;
border-radius: 5px;
height: 350px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
input[type="password"], input[type="text"]
{
border:1px solid;
background-color:rgba(0,0,0,0.0);
height: 33px;
width:240px;
margin: 2px 0 0 36px;
padding-left: 10px;
}

input[type="submit"]
{
background-color: #4CAF50;
color: white;
height: 42px;
margin: 10px 0 0 36px;
width: 250px;
padding-left: 10px;
}
input[type="submit"]:hover
{
background-image: linear-gradient(#4ec7c0,#31aba3)
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page77
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

input[type="submit"]:active
{
background-image: linear-gradient(#319d91, #3db0a6);
padding: 0;
}

2. index.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$username = $_POST['username'];
$password = $_POST['password'];
$dbusername =NULL;
$dbpassword=NULL;

$db_name = 'tecomp';
$db_user = 'root';
$db_pass = 'root';
$db_host = 'localhost';

$conn = mysql_connect($db_host, $db_user, $db_pass);


mysql_select_db('tecomp');

if (!$conn )
{
die('Could not connect: ' . mysql_error());
}
else
{
$query = "SELECT * FROM login WHERE username =
'$username' AND password = '$password'";
$retval = mysql_query( $query, $conn );

if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
else
{
while($row = mysql_fetch_array($retval,
MYSQL_ASSOC))
{
$dbusername =$row['username'];
$password=$row['password'];
}
if(!(strcmp($dbusername,$username)or
strcmp($dbusername,$username)) )
{
$_SESSION['id'] = session_id();
header('Location: Home.php');
}
else
{
echo"<center><font color=\"red\">Wrong
UserName Or Password Please Try Again!!</font></center>";

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page78
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

}
}
}
mysql_close($conn);
}
?>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>

<body>

<div class="login">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" name="myform"
method="post">

<label><b>Username</b></label>
<input type="text" name="username" id="username" placeholder=
"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<input type="submit" value="Login">
<a href="Register.php"> Register Yourself</a>
</form>
</div>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page79
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Home.php
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.j
s"></script>
<script type="text/javascript">
function GetCourse()
{
var qual = document.getElementById("qual");
var quali= qual.options[qual.selectedIndex].value;

//alert(quali);
$.ajax({
type: 'GET',
url: "SearchCourse.php",
data: {qualification: quali},
success: function(data)
{
$("p").html(data);
}
});
}
</script>
</head>
<body>
<center>
<h2> <font color="red">Welcome to Course Consultation
Website</h2></font>
</center>

<br><b>Select Qualification :</b><br>


<select id="qual" name="qual" onchange="GetCourse()"required
style="-webkit-appearance: menulist-button;height:30;width:400;">
<option selected></option>
<option value="ssc">SSC</option>
<option value="hsc">HSC</option>
<option value="diploma">Diploma</option>
<option value="be">BE</option>
</select>
<p></p>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page80
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. SearchCourse.php
<?php
$qual = $_GET['qualification'];
if(strcmp('ssc',$qual)==0)
{

echo "<table border=\"1\"><tr><td>Course


Name</td><td>Duration</td></tr><tr><td>MSCIT</td><td>2
Month</td></tr><tr><td>Tally</td><td>3 Months</td></tr></table>";
}
elseif(strcmp('hsc',$qual)==0)
{

echo "<table border=\"1\"><tr><td>Course


Name</td><td>Duration</td></tr><tr><td>HTML</td><td>2
Month</td></tr><tr><td>javaScript</td><td>3
Months</td></tr></table>";
}
elseif(strcmp('diploma',$qual)==0)
{

echo "<table border=\"1\"><tr><td>Course


Name</td><td>Duration</td></tr><tr><td>OCJP</td><td>3
Month</td></tr><tr><td>Oracle</td><td>3 Months</td></tr></table>";
}
elseif(strcmp('be',$qual)==0)
{

echo "<table border=\"1\"><tr><td>Course


Name</td><td>Duration</td></tr><tr><td>Software
Development</td><td>6 Month</td></tr><tr><td>Software
testing</td><td>6 Months</td></tr></table>";
}
else
{
echo "No Match Found";
}
?>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page81
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. Register.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$username = $_POST['username'];
$password = $_POST['password'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$age = $_POST['age'];

$db_name = 'tecomp';
$db_user = 'root';
$db_pass = 'root';
$db_host = 'localhost';

$conn = mysql_connect($db_host, $db_user, $db_pass);


mysql_select_db('tecomp');

if (!$conn )
{
die('Could not connect: ' . mysql_error());
}
else
{
$query = "insert into login
values('$username','$password','$mobile','$email','$age')";
$retval = mysql_query( $query, $conn );
if(! $retval )
{
die('Could not get data: ' . mysql_error());
}
else
{
header('Location: index.php');
}
}
mysql_close($conn);
}
?>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>

<body>
<div class="register">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" name="myform"
method="post">

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page82
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<label><b>Username</b></label>
<input type="text" name="username" id="username"
placeholder= "Username" required="required" onfocus="this.value =
'';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<label><b>Mobile Number</b></label>
<input type="text" name="mobile" id="mobile" placeholder=
"Mobile Number" required="required" onfocus="this.value = '';">
<label><b>E-Mail Address</b></label>
<input type="text" name="email" id="email" placeholder=
"E-Mail Address" required="required" onfocus="this.value = '';">
<label><b>Age</b></label>
<input type="text" name="age" id="age" placeholder= "Age"
required="required" onfocus="this.value = '';">

<input type="submit" value="Register">


</form>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page83
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Output:
1. Login Page

2. Home Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page84
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Home Page

4. Registration Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page85
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. Database

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page86
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:
1. What is AJAX?
2. What is jQuery?
3. How many TRIGGERS allows per table in mysql?
4. What is difference between COMMIT and ROLLBACK?
5. What is Ajax?
6. Whether jQuery HTML work for both HTML and XML documents?
7. What is the use of jQuery.ajax method ()?
8. What are Ajax applications?
9. How to control the duration of an Ajax request?
10. What are the advantages and disadvantages of Ajax?
11. Which are the two methods used for cross domain Ajax calls?
12. What are all the technologies used by Ajax?
13. What is JSON in Ajax?
14. What are the difference between AJAX and Javascript?
15. How Ajax objects can be created?
16. What is the use of "echo" in php?
17. How to include a file to a php page?
18. Differences between GET and POST methods ?
19. What is the use of 'print' in php?
20. What is the difference between Session and Cookie?
21. What are the different errors in PHP?
22. How to print current date and time?
23. What is the difference between sql and Mysql?
24. Why do we use GROUP BY and ORDER BY function in mysql?
25. What is JOIN in MySQL? What are the different types of join?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page87
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 6
Title: Design and develop any web application using Struts framework.
Objectives:
1. To impart the efficient and available client side and server side technologies.
2. To implement the communication between computing nodes using client side and
server side technologies.
3. To design and implement the web services with content management.
Problem Statement: Re-Design, develop and deploy assignment no. 3 of unit –III using
Strut.
Outcome: Students should be able to,
1. Implement the effective client side and server side technologies using struts
framework.
2. Solve the complex problem of development using MVC framework.

Software & Hardware Requirments:


Java 1.7 or Higher, Apache Tomcat 7 or higher, Struts API’s, Eclipse IDE.

Theory:
Struts 2
1. Introduction
The struts 2 framework is used to develop MVC-based web application. The Struts 2
framework is used to develop MVC (Model View Controller) based web applications. Struts
2 is the combination of webwork framework of opensymphony and struts 1.
Struts 2 provides many features that were not in struts 1. The important features of struts 2
framework are as follows:
1. Configurable MVC components
2. POJO based actions
3. AJAX support
4. Integration support
5. Various Result Types
6. Various Tag support
7. Theme and Template support

1.1 Model 2 (MVC) Architecture


Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design
pattern consists of three modules model, view and controller.
Model The model represents the state (data) and business logic of the application.
View The view module is responsible to display data i.e. it represents the presentation.
Controller The controller module acts as an interface between view and model. It intercepts
all the requests i.e. receives input and commands to Model / View to change accordingly.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page88
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Fig1. MVC Architecture

1.3 Directory structure


The directory structure of struts 2 is same as servlet/JSP. Here, struts.xml file must be located
in the classes folder.

Fig 2. Directory structure

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page89
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2. Components
2.1 web.xml
web.xml file Provide the entry of Controller. In struts
2, StrutsPrepareAndExecuteFilter class works as the controller. As we know well, struts 2
uses filter for the controller. It is implicitly provided by the struts framework.
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app>
3. <filter>
4. <filter-name>struts2</filter-name>
5. <filter-class>
6. org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter

7. </filter-class>
8. </filter>
9.
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

2.2 struts.xml
It is the important file from where struts framework gets information about the action and
decides which result to be invoked. Here, we have used many elements such as struts,
package, action and result.
struts element is the root elements of this file. It represents an application.
package element is the sub element of struts. It represents a module of the
application. It generally extends the struts-default package where many interceptors
and result types are defined.
action element is the sub element of package. It represents an action to be invoked for
the incoming request. It has name, class and method attributes. If you don't specify
name attribute by default execute() method will be invoked for the specified action
class.
result element is the sub element of action. It represents an view (result) that will be
invoked. Struts framework checks the string returned by the action class, if it returns
success, result page for the action is invoked whose name is success or has no name.
It has name and type attributes. Both are optional. If you don't specify the result
name, by default success is assumed as the result name. If you don't specify the type
attribute, by default dispatcher is considered as the default result type. We will learn
about result types later.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page90
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1. <?xml version="1.0" encoding="UTF-8" ?>


2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6. <action name="product" class="nilesh.korade.Product">
7. <result name="success">welcome.jsp</result>
8. </action>
</package>
</struts>

2.3 view components


It is the view component the displays information of the action. Here, we are using struts tags
to get the information. The s:property tag returns the value for the given name, stored in the
action object.
1. <%@ taglib uri="/struts-tags" prefix="s" %>
2. Product Id:<s:property value="id"/><br/>
3. Product Name:<s:property value="name"/><br/>
4. Product Price:<s:property value="price"/><br/>

2.4 Action class

This is simple bean class. In struts 2, action is POJO (Plain Old Java Object). It has one extra
method execute i.e. invoked by struts framework by default.

2.5 StrutsPrepareAndExecuteFilter
Handles both the preparation and execution phases of the Struts dispatching process. This
filter is better to use when you don't have another filter that needs access to action context
information, such as Sitemesh.
StrutsPrepareAndExecuteFilter belongs to org.apache.struts2.dispatcher.ng.filter
package. StrutsPrepareAndExecuteFilter can also be understood by its name.
StrutsPrepareAndExecuteFilter has the responsibility to prepare and execute all phases of
struts. The question is when we shouldz use StrutsPrepareAndExecuteFilter filter. Struts 2
apache documentation says that when there is no other filter being used that can access action
context information, better to use StrutsPrepareAndExecuteFilter filter.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page91
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2.6 Struts 2 Action


In struts 2, action class is POJO (Plain Old Java Object). POJO means you are not forced to
implement any interface or extend any class. Generally, execute method should be specified
that represents the business logic. The simple action class may look like:
1. package com.javatpoint;
2. public class Welcome
3. {
4. public String execute()
5. {
6. return "success";
7. }
8. }

2.6.1 Action Interface


A convenient approach is to implement the com.opensymphony.xwork2.Action interface
that defines 5 constants and one execute method.
Five Constants of Action Interface
Action interface provides 5 constants that can be returned form the action class. They are:
1. SUCCESS indicates that action execution is successful and a success result should be
shown to the user.
2. ERROR indicates that action execution is failed and a error result should be shown to
the user.
3. LOGIN indicates that user is not logged-in and a login result should be shown to the
user.
4. INPUT indicates that validation is failed and a input result should be shown to the
user again.
5. NONE indicates that action execution is successful but no result should be shown to
the user.
Action interface contains only one method execute that should be implemented overridden by
the action class even if you are not forced.
public String execute();

2.6.2 ActionSupport class


It is a convenient class that implements many interfaces such as Action, Validateable,
ValidationAware, TextProvider, LocaleProvider and Serializable . So it is mostly used
instead of Action.
Struts ActionSupport class provides the default implementation of the most common actions.
It provides a collection of methods. Some of the common methods are-
execute() - This method executed automatically when action is called. This is default
implemented method subclasses should implement this method by proving their business
logic.
validate() - This method is default implemented method subclasses should override this
method to provide validation.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page92
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

clearErrors() - This method can be used when you want to continue execution, and want to
clear the state of the action.

Conclusion:
Hence, we have studied how to design and develop small web application using Struts, with
apache server and MySQL as backend.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page93
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program

Project Structure:

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page94
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">

<display-name>Assignment7</display-name>

<welcome-file-list>
<welcome-file>Login.jsp</welcome-file>
</welcome-file-list>

<filter>
<filter-name>Struts2</filter-name>
<filter-
class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilte
r</filter-class>
</filter>

<filter-mapping>
<filter-name>Struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

2. style.css

body
{
background-image: url("img.jpeg");
background-repeat: no-repeat;
background-size: cover;
}
a
{
margin: 100px 0 0 36px;
}
.login
{

border: 2px solid;


border-radius: 5px;
height: 200px;
margin: 150px 0 auto 400px;
width: 410px;
border-color:#3498DB;
padding-top: 20px;
}
.register
{

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page95
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

border: 2px solid;


border-radius: 5px;
height: 350px;
margin: 150px 0 auto 400px;
width: 410px;
border-color:#3498DB;
padding-top: 20px;
}
input[type="password"], input[type="text"]
{
border:1px solid;
background-color:rgba(0,0,0,0.0);
height: 33px;
width:240px;
margin: 2px 0 0 36px;
padding-left: 10px;
}
input[type="submit"]
{
background-color: #4CAF50;
color: white;
height: 42px;
margin: 10px 0 0 36px;
width: 250px;
padding-left: 10px;
}
input[type="submit"]:hover
{
background-image: linear-gradient(#4ec7c0,#31aba3)
}
input[type="submit"]:active
{
background-image: linear-gradient(#319d91, #3db0a6);
padding: 0;
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page96
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div class="login">
<s:form action="login" method="post">
<s:textfield name="username" label="UName " />
<s:password name="password" label="Password " />
<s:submit label="Login"/>
<s:actionerror/>
</s:form>
<s:a href="Register.jsp">Not Registered? Register Here</s:a>
</div>
</body>
</html>

4. Error.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
Error...
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page97
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. Welcome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"


pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<center><h2> <font color="red">Welcome to Course Consultation
Website</h2></font>
<table border="1">
<tr>
<th>Qualification</th>
<th>Intrest</th>
<th>Course Suggestion</th>
</tr>
<tr>
<td>12th</td>
<td>Programming</td>
<td>C,C++</td>
</tr>
<tr>
<td>12th</td>
<td>Web Design</td>
<td>HTML,CSS,JavaScript</td>
</tr>
<tr>
<td>12th</td>
<td>Car Design</td>
<td>AutoCAD, CATIA</td>
</tr>
<tr>
<td>12th</td>
<td>Robotics</td>
<td>Artificial Intelligence and Robotics</td>
</tr>
</table>
</center>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page98
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

6. Register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Registration</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>

<div class="register">
<s:form action="Register" method="post">

<s:textfield label="Username " key="username"


required="true"/>
<s:password label="Password " key="password"
required="true"/>
<s:textfield label="Mobile No " key="mobile"
required="true"/>
<s:textfield label="Email Id " key="email"
required="true"/>
<s:textfield label="Age " key="age" required="true"/>
<s:submit label="Register" />
<s:actionerror/>

</s:form>

<s:a href="Login.jsp">Already Registered? Login Here</s:a>

</div>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page99
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

7. struts.xml

<?xml version="1.0" encoding="UTF-8"?>


<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
<package name="Login" namespace="/" extends="struts-default">

<action name="login"
class="nilesh.korade.LoginValidate">
<result name="login">/Welcome.jsp</result>
<result name="error">/Login.jsp</result>

</action>
</package>

<package name="Register" namespace="/" extends="struts-


default">
<action name="Register"
class="nilesh.korade.RegisterUser">
<result name="success">/Login.jsp</result>
<result name="failure">/Error.jsp</result>

</action>
</package>

</struts>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page100
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

8. DBCon.java

package nilesh.korade;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DBCon {

public ResultSet conn() throws Exception


{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/tecomp", "root",
"root");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from login");

return rs;
}

public boolean reg(String username,String password,String


mobile,String email,String age) throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost/tecomp", "root",
"root");
Statement st = con.createStatement();
int id = st.executeUpdate("insert into login
values('"+username+"','"+password+"','"+mobile+"','"+email+"','"+age+"')")
;

if(id>0)
return true;
else
return false;
}
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page101
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

8. LoginValidate.java

package nilesh.korade;
import java.sql.ResultSet;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginValidate extends ActionSupport implements Action
{
private static final long serialVersionUID = 1L;
private String username;
private String password;
public String FailMsg = "Please Enter Valid Credentials ...";

public String execute() throws Exception


{
int fl = 0;
DBCon db = new DBCon();
ResultSet rs = db.conn();
while(rs.next())
{
if(username.equals(rs.getString("username")) &&
password.equals(rs.getString("password")))
fl=1;

if(fl!=1)
{
return ERROR;
}
return LOGIN;
}

public String getUsername() {


return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page102
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

9. RegisterUser.java

package nilesh.korade;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterUser extends ActionSupport
{
private String username;
private String password;
private String mobile;
private String email;
private String age;

public String execute() throws Exception


{
DBCon db = new DBCon();
if(db.reg(username,password,mobile,email,age))
return "success";
else
return "failure";
}
public String getUsername() { return username;}
public void setUsername(String username) {this.username = username;}
public String getPassword() { return password; }
public void setPassword(String password) {this.password = password;}
public String getMobile() { return mobile;}
public void setMobile(String mobile) {this.mobile = mobile;}
public String getEmail() {return email;}
public void setEmail(String email) {this.email = email;}
public String getAge() {return age; }
public void setAge(String age) {this.age = age; }

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page103
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Output:
1. Login Page

2. Home Page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page104
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Registration Page

4. Database

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page105
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:

1. What are the components of Struts Framework?


2. Which file is used by controller to get mapping information for request routing?
3. What’s the role of Action Class in Struts?
4. What’s the purpose of Execute method of action class?
5. What are the benefits of Struts framework?
6. What is Struts2?
7. What are the differences between Struts1 and Struts2 or how Struts2 is better than Struts1?
8. What is the difference in using Action interface and ActionSupport class for our action
classes, which one you would prefer?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page106
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 7
Title: Design and develop any web application using AngularJS.
Objectives:
1. Understand the design of single-page applications and how AngularJS facilitates their
development
2. Write AngularJS directives
Problem Statement: Re-Design, develop and deploy assignment no. 4 of unit –IV using
Angular JS.
Outcome: Students should be able to,
1. Develop web based application using suitable client side and server side web
technologies with AngularJS.

Software & Hardware Requirments:


Java 1.7 or Higher, Apache Tomcat 7 or higher, Eclipse IDE.

Theory:
AngularJS
1. Introduction
AngularJS is an open-source web application framework. It was initially created in 2009 by
MiskoHevery and Adam Abrons. It is presently kept up by Google. Its most recent adaptation
is 1.2.21. "AngularJS is an auxiliary system for dynamic web applications. It gives you a
chance to utilize HTML as your layout dialect and gives you a chance to stretch out HTML's
linguistic structure to express your application parts plainly and compactly. Its information
official and reliance infusion take out a significant part of the code you as of now need to
compose. Also, everything occurs inside the program, making it a perfect band together with
any server innovation".
General Features
AngularJS is a productive system that can make Rich Internet Applications (RIA).
AngularJS gives designers a choices to compose customer side applications utilizing
JavaScript in a spotless Model View Controller (MVC) way.
Applications written in AngularJS are cross-program agreeable. AngularJS
consequently handles JavaScript code reasonable for every program.
AngularJS is open source, totally free, and utilized by a great many engineers the
world over. It is authorized under the Apache permit version2.0.
By and large, AngularJS is a system to assemble expansive scale, elite, and simple
to keep up web applications.

AngularJS is a JavaScript framework. It can be added to an HTML page with a <script> tag.
AngularJS extends HTML attributes with Directives, and binds data to HTML with
Expressions.

<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul
ar.min.js"></script>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page107
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

AngularJS extends HTML with ng-directives.


The ng-app directive defines an AngularJS application.
The ng-model directive binds the value of HTML controls (input, select, textarea) to
application data.
The ng-bind directive binds application data to the HTML view.
<!DOCTYPE html>
<html>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul
ar.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p ng-bind="name"></p>
</div>
</body>
</html>

AngularJS starts automatically when the web page has loaded.


The ng-app directive tells AngularJS that the <div> element is the "owner" of an
AngularJS application.
The ng-model directive binds the value of the input field to the application
variable name.
The ng-bind directive binds the innerHTML of the <p> element to the application
variable name.

1.1. AngularJS Directives


As you have already seen, AngularJS directives are HTML attributes with
an ng prefix.
The ng-init directive initializes AngularJS application variables.
<div ng-app="" ng-init="firstName='John'">
<p>The name is <span ng-bind="firstName"></span></p>
</div>

1.2. AngularJS Expressions


AngularJS expressions are written inside double braces: {{ expression }}.
AngularJS will "output" data exactly where the expression is written.
<!DOCTYPE html>
<html>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul
ar.min.js"></script>
<body>

<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page108
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

AngularJS expressions bind AngularJS data to HTML the same way as the ng-binddirective.
<!DOCTYPE html>
<html>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul
ar.min.js"></script>
<body>
<div ng-app="">
<p>Name: <input type="text" ng-model="name"></p>
<p>{{name}}</p>
</div>
</body>
</html>

1.3. AngularJS Applications


AngularJS modules define AngularJS applications.
AngularJS controllers control AngularJS applications.
The ng-app directive defines the application, the ng-controller directive defines the
controller.
<div ng-app="myApp" ng-controller="myCtrl">
First Name: <input type="text" ng-model="firstName"><br>
Last Name: <input type="text" ng-model="lastName"><br>
<br>Full Name: {{firstName + " " + lastName}}
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.firstName= "John";
$scope.lastName= "Doe";
});
</script>

2. AngularJS Expressions
Expressions are used to bind application data to html. Expressions are written inside double
braces like {{ expression}}. Expressions behaves in same way as ng-bind directives.
AngularJS application expressions are pure javascript expressions and outputs the data where
they are used.
<!DOCTYPE html>
<html>
<scriptsrc="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angul
ar.min.js"></script>
<body>
<div ng-app="">
<p>My first expression: {{ 5 + 5 }}</p>
</div>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page109
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

If you remove the ng-app directive, HTML will display the expression as it is, without
solving it.
You can write expressions wherever you like, AngularJS will simply resolve the expression
and return the result.
Example: Let AngularJS change the value of CSS properties. Change the color of the input
box below, by changing its value.
<div ng-app="" ng-init="myCol='lightblue'">
<input style="background-color:{{myCol}}" ng-model=
"myCol" value="{{myCol}}">
</div>

2.1 AngularJS Numbers


AngularJS numbers are like JavaScript numbers.
<div ng-app="" ng-init="quantity=1;cost=5">
<p>Total in dollar: {{ quantity * cost }}</p>
</div>

2.2 AngularJS Strings


AngularJS strings are like JavaScript strings
<div ng-app="" ng-init="firstName='John';lastName='Doe'">
<p>The name is {{ firstName + " " + lastName }}</p>
</div>

2.3 AngularJS Objects


AngularJS objects are like JavaScript objects
<div ng-app="" ng-init="person={firstName:'John',lastName:'Doe'}">
<p>The name is {{ person.lastName }}</p>
</div>

2.4 AngularJS Arrays


AngularJS arrays are like JavaScript arrays
<div ng-app="" ng-init="points=[1,15,19,2,40]">
<p>The third result is {{ points[2] }}</p>
</div>

2.5 AngularJS Expressions vs. JavaScript Expressions


Like JavaScript expressions, AngularJS expressions can contain literals, operators, and
variables.
Unlike JavaScript expressions, AngularJS expressions can be written inside HTML.
AngularJS expressions do not support conditionals, loops, and exceptions, while JavaScript
expressions do.
AngularJS expressions support filters, while JavaScript expressions do not.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page110
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. AngularJS Modules
An AngularJS module defines an application.
The module is a container for the different parts of an application.
The module is a container for the application controllers.
Controllers always belong to a module.

3.1 Creating a Module


A module is created by using the AngularJS function angular.module.
<div ng-app="myApp">...</div>
<script>
var app = angular.module("myApp", []);
</script>
The "myApp" parameter refers to an HTML element in which the application will run. Now
you can add controllers, directives, filters, and more, to your AngularJS application.

3.2 Adding a Controller


Add a controller to your application, and refer to the controller with the ng-
controllerdirective.
<!DOCTYPE html>
<html>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"
></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl">


{{ firstName + " " + lastName }}
</div>

<script>
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.firstName = "John";
$scope.lastName = "Doe";
});
</script>

</body>
</html>

4. AngularJS Controllers
AngularJS application mainly relies on controllers to control the flow of data in the
application. A controller is defined using ng-controller directive. A controller is a JavaScript
object ontaining attributes/properties and functions. Each controller accepts $scope as a
parameter which refers to the application/module that controller is to control.
<html>
<head>
<title>Angular JS Controller</title>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page111
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<script src =
"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js">
</script>
</head>
<body>
<h2>AngularJS Sample Application</h2>

<div ng-app = "mainApp" ng-controller = "studentController">


Enter first name: <input type = "text" ng-model =
"student.firstName"><br><br>
Enter last name: <input type = "text" ng-model =
"student.lastName"><br>
<br>
You are entering: {{student.fullName()}}
</div>
<script>
var mainApp = angular.module("mainApp", []);
mainApp.controller('studentController', function($scope) {
$scope.student = {
firstName: "Mahesh",
lastName: "Parashar",

fullName: function() {
var studentObject;
studentObject = $scope.student;
return studentObject.firstName + " " +
studentObject.lastName;
}
};
});
</script>
</body>
</html>
 studentController defined as a JavaScript object with $scope as argument.
 $scope refers to application which is to use the studentController object.
 $scope.student is property of studentController object.
 firstName and lastName are two properties of $scope.student object. We've passed the
default values to them.
 fullName is the function of $scope.student object whose task is to return the combined
name.
 In fullName function we're getting the student object and then return the combined
name.
 As a note, we can also define the controller object in separate JS file and refer that file
in the html page.
 We've bounded student.firstName and student.lastname to two input boxes.
 We've bounded student.fullName() to HTML.
 Now whenever you type anything in first name and last name input boxes, you can
see the full name getting updated automatically.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page112
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Conclusion:
Hence, we have studied how to design and develop web application using JSP, Servlet,
AngularJS with apache server and MySQL as backend.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page113
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program
1. style.css
body
{
background-image: url("img.jpeg");
background-repeat: no-repeat;
background-size: cover;
}
a
{
margin: 100px 0 0 36px;
}
.login
{
border: 2px solid;
border-radius: 5px;
height: 200px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
.register
{
border: 2px solid;
border-radius: 5px;
height: 350px;
margin: 150px 0 auto 400px;
width: 310px;
border-color:#3498DB;
padding-top: 20px;
}
input[type="password"], input[type="text"]
{
border:1px solid;
background-color:rgba(0,0,0,0.0);
height: 33px;
width:240px;
margin: 2px 0 0 36px;
padding-left: 10px;
}

input[type="submit"]
{
background-color: #4CAF50;
color: white;
height: 42px;
margin: 10px 0 0 36px;
width: 250px;
padding-left: 10px;
}
input[type="submit"]:hover
{
background-image: linear-gradient(#4ec7c0,#31aba3)
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page114
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

input[type="submit"]:active
{
background-image: linear-gradient(#319d91, #3db0a6);
padding: 0;
}

2. index.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$username = $_POST['username'];
$password = $_POST['password'];
$dbusername =NULL;
$dbpassword=NULL;

$db_name = 'tecomp';
$db_user = 'root';
$db_pass = 'root';
$db_host = 'localhost';
$conn = mysqli_connect($db_host, $db_user, $db_pass,$db_name);

if (!$conn)
{
die('Could not connect: ' . mysqli_error());
}
else
{
$query = "SELECT * FROM login WHERE username =
'$username' AND password = '$password'";
$result = $conn->query($query);

if($result->num_rows < 0)
{
echo"<center><font color=\"red\">Wrong UserName Or
Password Please Try Again!!</font></center>";
}
else
{
$_SESSION['id'] = session_id();
header('Location: Userhome.html');
}
}
$conn->close();
}
?>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>
<div class="login">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" name="myform"
method="post">

<label><b>Username</b></label>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page115
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<input type="text" name="username" id="username" placeholder=


"Username" required="required" onfocus="this.value = '';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<input type="submit" value="Login">
<a href="Register.php"> Register Yourself</a>
</form>
</div>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page116
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Userhome.html
<!DOCTYPE html>
<html>
<style>
table, th , td
{
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
align: center;
}
table tr:nth-child(odd)
{
background-color: #f1f1f1;
}
table tr:nth-child(even)
{
background-color: #ffffff;
}
</style>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.m
in.js"></script>
<body>

<div ng-app="myApp" ng-controller="courseCtrl">


<center><h3><font color="red"> {{welcome}}</font></h1>
<table>
<tr>
<th>Qualification</th>
<th>Course</th>
<th>Duration</th>
</tr>
<tr ng-repeat="x in names">
<td>{{ x.qual }}</td>
<td>{{ x.course }}</td>
<td>{{ x.duration }}</td>
</tr>
</table>

</div>
</center>
<script>
var app = angular.module('myApp', []);
app.controller('courseCtrl', function($scope, $http)
{
$scope.welcome = "Welcome in Course Counceling Website";
$http.get("course.php")
.then(function (response)
{$scope.names = response.data.records;});
});
</script>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page117
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. course.php
{ "records":[
{"qual":"SSC","course":"MSCIT","duration":"3 months"},
{"qual":"SSC","course":"DTP","duration":"3 months"},
{"qual":"HSC","course":"HTML","duration":"1 months"},
{"qual":"HSC","course":"C Programming","duration":"3 months"},
{"qual":"Diploma","course":"OCJP","duration":"3 months"},
{"qual":"Diploma","course":"CCNA","duration":"3 months"},
{"qual":"BE","course":"Software Development","duration":"6 months"},
{"qual":"BE","course":"Software Testing","duration":"6 months"}
] }

5. Register.php
<?php
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$username = $_POST['username'];
$password = $_POST['password'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
$age = $_POST['age'];

$db_name = 'tecomp';
$db_user = 'root';
$db_pass = 'root';
$db_host = 'localhost';

$conn = mysqli_connect($db_host, $db_user, $db_pass,$db_name);


if (!$conn)
{
die('Could not connect: ' . mysqli_error());
}
else
{
$query = "insert into login
values('$username','$password','$mobile','$email','$age')";
// $retval = mysqli_query( $query);

if($conn->query($query) === FALSE )


{
echo "Error:" . $conn->error;
}
else
{
header('Location: index.php');
}
}
$conn->close();
}
?>
<html>
<head>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page118
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

<body>
<div class="register">
<form action="<?php echo $_SERVER['PHP_SELF'];?>" name="myform"
method="post">
<label><b>Username</b></label>
<input type="text" name="username" id="username"
placeholder= "Username" required="required" onfocus="this.value =
'';">
<label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">
<label><b>Mobile Number</b></label>
<input type="text" name="mobile" id="mobile" placeholder=
"Mobile Number" required="required" onfocus="this.value = '';">
<label><b>E-Mail Address</b></label>
<input type="text" name="email" id="email" placeholder=
"E-Mail Address" required="required" onfocus="this.value = '';">
<label><b>Age</b></label>
<input type="text" name="age" id="age" placeholder= "Age"
required="required" onfocus="this.value = '';">

<input type="submit" value="Register">

</form>

</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page119
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Output:
1. Login Page

2. Userhome page

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page120
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. Registration page

4. Database

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page121
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQs:
1. What is AngularJS and what are some of its advantages?
2. What is the Model View Controller (MVC)?
3. What is data binding in AngularJS? How does it relate to the MVC architecture?
4. Explain the concept of scope. How does scope inheritance work in AngularJS?
5. Explain the difference between a factory and a service in AngularJS?
6. Explain why there are two “destroy” events associated with the termination of a scope in
AngularJS?
7. What is dependency injection and how does it work?
8. What are directives? Can you explain the functions of the following directives?
9. Explain the role of $routeProvider in AngularJS?

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page122
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Assignment No: 8
Title: Web application using Spring.
Objectives: Understand how to develop a dynamic webpage using Spring Framework,
HTML and JSP.
Problem Statement: Design, Develop and Deploy separate web application using
EJB/CMS/JSF/Spring/Bootstrap..
Outcome: Students will be able to:
1. Understand about basic concepts of Spring, Spring MVC Architecture.
2. How to use Jsp, Servlet inside Spring Framework.
Software & Hardware Requirments:
1. Java 7 or Later
2. Apache Tomcat Server
3. Spring Library
Theory:
1. Introduction:
Spring is a lightweight framework. It can be thought of as a framework of
frameworks because it provides support to various frameworks such as Struts, Hibernate,
Tapestry, EJB, JSF etc. The framework, in broader sense, can be defined as a structure where
we find solution of the various technical problems.

1.1 Inversion Of Control (IOC) and Dependency Injection


These are the design patterns that are used to remove dependency from the
programming code. They make the code easier to test and maintain. Let's understand this
with the following code:
1. class Employee
2. {
3. Address address;
4. Employee()
5. {
6. address=new Address();
7. }
8. }
In such case, there is dependency between the Employee and Address (tight coupling). In the
Inversion of Control scenario, we do this something like this:
1. class Employee
2. {
3. Address address;
4. Employee(Address address)
5. {
6. this.address=address;
7. }
8. }

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page123
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Thus, IOC makes the code loosely coupled. In such case, there is no need to modify the code
if our logic is moved to new environment. In Spring framework, IOC container is responsible
to inject the dependency. We provide metadata to the IOC container either by XML file or
annotation.
1.2 Spring MVC
MVC says we can separate view(UI) and Business Logic(code that generate data by
applying logic).
The Model encapsulates the application data and in general they will consist of POJO.
The View is responsible for rendering the model data and in general it generates
HTML output that the client's browser can interpret.
The Controller is responsible for processing user requests and building appropriate
model and passes it to the view for rendering.
In Java systems, the model is typically a loose JavaBean, or Plain Old Java Object
(POJO) that has getters and setters to manipulate its contents. It can be a very simple object
or a very complicated one with dozens of subobjects, but it's just an object nonetheless.
The view is usually a JSP page, but countless other technologies and templating
languages can be used, such as FreeMarker, Velocity, XML/XSLT, JasperReports, and so on.
After the business logic is complete and the model has been generated, the controller passes
the model to the view to be presented to the user.
The controller is typically implemented by a servlet that calls into business services to
perform some action. The controller usually hosts additional logic such as authentication and
authorization: it controls which actions a user can execute. For example, you might not allow
a user who hasn't first logged in to post a message to a message board. If the controller
notices that the user is trying to access the "post" page, it redirects the user to a login page
first.

Fig. flow of Spring Web MVC


Here client will enter url in browser. The front controller accept the request and send
to HandlerMapping. HandlerMapping knows the address of guy that can generate data. Then
it send the information to front controller. The front controller call to Data Generator Guy
who prepare data and send it to front controller. It is also called as controller. The front
controller make contact to View Resolver who tell the address of view who can represent

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page124
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

data. Then Front controller make contact to View who generate UI for data and pass it to
Front controller and then to client.

Fig. flow of Spring Web MVC


As displayed in the figure, all the incoming request is intercepted by the DispatcherServlet
that works as the front controller. The DispatcherServlet gets entry of handler mapping from
the xml file and forwards the request to the controller. The controller returns an object of
ModelAndView. The DispatcherServlet checks the entry of view resolver in the xml file and
invokes the specified view component.

1.3 Spring Web MVC Framework Example

Fig. Directory Structure

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page125
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.3.1 Provide the entry of controller in the web.xml file


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">

<display-name>FirstMVCExample</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
</servlet>

<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
In this xml file, we are specifying the servlet class DispatcherServlet that acts as the front
controller in Spring Web MVC. All the incoming request for the html file will be forwarded
to the DispatcherServlet.
Consider client make request by using following URL

The DispatcherServlet is Front controller which spring has provided which look
up spring-dispatcher-servlet.xml
The front controller need to determine which controller class need to call with the
help of HandlerMapping class provided by spring MVC framework.

1.3.2 Define the bean in the xml file(spring-dispatcher-servlet.xml)


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="HandlerMapping"
class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>

<bean name="/welcome.html" class="nilesh.korade.HelloController"/>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page126
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

This is the important configuration file where we need to specify the ViewResolver
and View components.
Here, the InternalResourceViewResolver class is used for the ViewResolver.
The prefix+string returned by controller+suffix page will be invoked for the view
component. This xml file should be located inside the WEB-INF directory.
BeanNameUrlHandlerMapping:- Handler-Mapping class provided by spring
framework with the help of this class spring framework call to Controller
class(nilesh.korade.HelloController)
Handler-Mapping class matches url pattern with the bean name of the controller class. The
url is /welcome.html and controller is nilesh.korade.HelloController. The it suggest to front
controller to make a call to respected controller.
<bean name="/welcome.html" class="nilesh.korade.HelloController"/>

1.3.3 Create the controller class(HelloController.java)


package nilesh.korade;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class HelloController extends AbstractController
{ @Override
protected ModelAndView handleRequestInternal(HttpServletRequest
arg0,HttpServletResponse arg1) throws Exception
{
ModelAndView mv=new ModelAndView("HelloPage");
mv.addObject("WelcomeMessage","Hi this is our first example");
return mv;
}
}
Here we simply set the data and view name and returning the object to the Front Controller.
Each controller class has to extends from base controller class here we are extending
AbstractController.
Then Front Controller need to identify exact location of view in object return by
controller class. It done this by using ViewResolver class. The view Resolver
(org.springframework.web.servlet.view.InternalResourceViewResolver) will prepare exact
location of view using suffix and prefix mentioned there. For example “WEB-
INF/HelloPage.jsp” and make call to view.

1.3.4 Display the message in the JSP page(HelloPage.jsp)


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>${WelcomeMessage}</h2>
</body>
</html>
Here we add data send by Controller and the UI together and send back to FrontController
and it will send back to client.
Department of Computer Engineering
PCET’s PCCOER, Pune-412101 Page127
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

1.4 Annotation
1.4.1 @Controller: Define Controller
1.4.2 @Request Mapping: Define for which request controller should get executed
1.4.3 @PathVariable: When there is dynamic path mean whose value may change(e.g
/path/country/username). Here username may vary in that case we need to use{}. For
example(/path/country/{username}).
1.4.4 @RequestParam : It is used ti get parameter from form it work same as
“request.getParameter(“name”)” in jsp.
1.4.5 @ModelAttribute:While sending data to jsp we need to create ModelAndView Object,
then we add attribute to ModelAndView Object. But using This annotation we can set
attribute for multiple jsp. The method below @ModelAttribute always get executed before
sending data to particular jsp in Controller class.

Conclusion:
Hence, we have studied how to design and develop small web application using Spring
Framework.

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page128
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Program:

Project Structure

1. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID"
version="3.0">
<display-name>StudentRegistration</display-name>
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-
class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
</servlet>

<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page129
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

2. spring-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-
context.xsd"
xmlns:context="http://www.springframework.org/schema/context">
<mvc:annotation-driven/>
<context:annotation-config/>
<context:component-scan base-package="nilesh.korade"/>

<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewReso
lver">
<property name="prefix">
<value>/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page130
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

3. StudentAdmissionController.java

package nilesh.korade;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class StudentAdmissionController
{
@RequestMapping(value="/admissionForm",
method=RequestMethod.GET)
protected ModelAndView myMethod1()
{
ModelAndView mv=new ModelAndView("AdmissionForm");
return mv;
}

@RequestMapping(value="/submitAdmissionForm",
method=RequestMethod.POST)
protected ModelAndView myMethod2(
@RequestParam("studentname") String name,
@RequestParam("password") String password,
@RequestParam("mobile") String mobile,
@RequestParam("email") String email,
@RequestParam("age") String age)
{
ModelAndView mv=new ModelAndView("AdmissionSuccess");
mv.addObject("WelcomeMessage","Details are : <br>Name
:"+name+"<br>Password: "+password+"<br>Mobile No : "
+mobile + "<br>E-Mail : "+email+"<br>Age : "+age);
return mv;
}
}

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page131
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

4. AdmissionForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
<link rel = "stylesheet" type = "text/css" href = "style.css" />
</head>
<body>

<center><h1>Student Admission Form</h1></center>


<form action="/StudentRegistration/submitAdmissionForm"
method="post">

<label><b>Username</b></label>
<input type="text" name="studentname" placeholder= "Username"
required="required" onfocus="this.value = '';">

<br> <label><b>Password</b></label>
<input type="password" name="password" id="password"
placeholder="password" required="required" onfocus="this.value =
'';">

<br><label><b>Mobile Number</b></label>
<input type="text" name="mobile" id="mobile" placeholder= "Mobile
Number" required="required" onfocus="this.value = '';">

<br><label><b>E-Mail Address</b></label>
<input type="text" name="email" id="email" placeholder= "E-Mail
Address" required="required" onfocus="this.value = '';">

<br><label><b>Age</b></label>
<input type="text" name="age" id="age" placeholder= "Age"
required="required" onfocus="this.value = '';">

<br><input type="submit" value="Register">

</form>
</body>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page132
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

5. AdmissionSuccess.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"


pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-
8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>${WelcomeMessage}</h2>
</body>
</html>

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page133
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

Output:

1. Student Registration

2. Registration Successful

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page134
Subject Name- Web Technology Lab Class/Branch: TE (A ) Computer Engineering

FAQ’s:
1. What is Spring?
2. What are benefits of Spring Framework?
3. Explain the Spring MVC module
4. What is Spring IoC container?
5. What is the difference between Bean Factory and ApplicationContext?
6. What is Dependency Injection in Spring?
7. What are Spring beans?
8. How do you define the scope of a bean?
9. What is Spring Java-Based Configuration? Give some annotation example.
10. What is @Required annotation

Department of Computer Engineering


PCET’s PCCOER, Pune-412101 Page135

You might also like