You are on page 1of 68

WTL Lab (2019 Course)

ASSIGNMENT NO: 1
Title of Assignment:Case study.

Problem Statement: students should visit different websites (Min. 5) for the different client projects and
note down the evaluation results for these websites, either good website or bad website

Objectives: From the evaluation, students should learn and conclude different website design issues, which
should be considered while developing a website.

Theory:-Top 10 things every website needs:

1. An easy-to-update CMS:One of the first problems people run into is that it’s difficult to update
their website. Either they’re unable to do it themselves or they’ve hired out website management
and maintenance, which is fine, except that when a change is needed it sometimes takes a
considerable amount of time for it to actually happen. There are a number of intuitive, easy-to-use
and update Content Management Systems (CMS) that are customizable and widely known to
developers, like WordPress, Joomla, Drupal, Expression Engine and many others.

2. Responsive design: A responsive website is a website designed to change its look based on the
device it’s viewed on. For instance, if a customer views your website on their desktop, and then
switches to their phone, the site won’t just appear desktop-sized on the smaller screen – that would
look cramped and chaotic. A responsive design simplifies your site and makes it easy to read on a
smaller device. This component of a website is critical because more and more people browse the
internet, shop and socialize on their phones and tablets, and your website must allow them to easily
switch devices without losing them.

3. Helpful navigation: Once your visitors get to your website, they should be able to find where they
want to go within seconds. A drop-down navigation bar at the top of your site is a common and
very simple way to organize the pages and links on your website. Plan out your site map in a logical
way, then make sure that each link goes to the appropriate page. Broken links or links that misdirect
visitors will cause them to lose interest in your site or become frustrated and ultimately leave.

4. Strong brand identity: Before you begin a site redesign, think carefully about how you want your
brand portrayed. Consider color scheme, font, the type of graphics and photos, how much content
and empty space you’ll use, the tone of voice and message of your brand… All of these things go
into creating a cohesive identity that will subtly inform your visitor of who you are and what you do.
A confused brand identity will leave your visitors unsure of and unable to relate to your company.

5. High-quality content: Every page on your website should have well-written, keyword-rich content.
Search engines crawl sites looking for content that is readable, valuable and updated often and then
serve those sites up higher in results than those that don’t. So whatever page – be it service listings,
pricing, history, testimonials – make sure that you have engaging, useful and informative content on
it.
6. A blog: As mentioned earlier, search engines favor sites with high-quality content that’s updated
regularly. The very best way to ensure your site has this key feature is to start a business blog. To

T.E. Computer Engineering AY 2023-24 Semester-II Page 1


WTL Lab (2019 Course)

make search engines happy, post on a regular basis, keeping your website updated with fresh
content, and post informative content that positions your business as a thought leader – that’s some
high-quality stuff!

7. Clear calls-to-action: Being clear about what you want your site visitors to do helps direct them
and alleviate confusion. Throughout your site, be specific – whether you want them to subscribe to
your blog, fill in a contact form, download content, etc. Use powerful, active and urgent language
(Buy/Donate/Register/Subscribe/Download Now!) and position a call-to-action on every page
above the fold.

8. Contact information: Have your business’s address, phone number and email listed in a footer that
appears on every page – that way no matter where your visitors go on your site, they’ll know how
to get a hold of you. You can also create a “Contact Us” page in addition to your footer, making it
obvious that you value feedback, questions and customer interaction.

9. Social media buttons: A website without the support of social media is missing a huge opportunity
to connect with potential customers. Almost everyone who uses the Internet also has a social media
profile on some network. So include links to your business’s social profiles and add “share” buttons
to your content. If you haven’t already, consider creating business pages on Twitter, Facebook,
LinkedIn, Google+, YouTube and Pinterest.

10. Security features: This is something that’s most important to websites where visitors may enter
credit card or other sensitive information. Chances are your site is secure, but visitors will trust you
even more when you install further security features on your site and show them through a graphic
that says “secured by…” Even if you don’t sell things through your website, let people know that
any information they provide (name, email, address, etc.) to download content or subscribe to a
newsletter or blog is safe with you and that you won’t sell it or use it for other than the intended
purpose.

Parameters to check a Website Quality:


1. Site Purpose
2. Target Audience
3. Responsive/ Mobile Friendly
4. Fresh Content or Outdated Content
5. Using understandable language on the web pages
6. Visual Design/ Quality of Images
7. Look and feel
8. Engaging Content(Making the site interesting)
9. Navigation(Making the site easy to use)
10. Slow upload speed
11. Contents Representation (Font Size/Style)

Challenges in creating a responsive website


The process of creating a responsive website is a major challenge for designers as it involves a wide array
of devices, code frameworks, scripts, and of course, the constant needs to work in an innovative way with
clients to effectively manage the process.

T.E. Computer Engineering AY 2023-24 Semester-II Page 2


WTL Lab (2019 Course)

Here are some of the major issues faced by web designers while building a responsive website:
 When compared to a desktop site, building a responsive website takes a significant amount of time.
 In responsive websites, the content should be prioritized for mobile use. For smaller screens, the
designer must know precisely what matters, the devices that people use, their circumstances, and
their unique goals.
 Interactions in desktop sites and mobile devices are different.
 Responsive websites recognize media queries to assess the screen size of every visitor and then
display the layout accurately. The issue here is that old browsers, particularly Internet Explorer
version 8 and older, do not recognize media queries.
 In responsive design, scaled images instantly lose details, and hence their meaning. This is because
scaling mainly happens depending on the size of the screen and not on context.
 On smaller devices, designing intuitive navigation menus becomes a real a challenge due to the
limited screen size.

Web Development challenges:


• Setting Goals
• Designing and UI (User Interface)
• Speed and Performance
• Working Frame and Knowledge Required
• Growth and Scalability
• Safety and Security

Conclusion:-

T.E. Computer Engineering AY 2023-24 Semester-II Page 3


WTL Lab (2019 Course)

ASSIGNMENT NO: 2
Title of Assignment:
Designawebpageindex.htmforanyclientwebsite.

Problem Statement:Implementawebpageindex.htmforanyclientwebsite.
a. HTMLsyntax:headingtags,basictagsandattributes,frames,tables,images,lists,linksfortext andimages,
forms etc.
b. UseofInternal CSS,Inline CSS,External CSS.
c. Use at least 2 pages on your website

Objectives:Learn how to use CSS with HTML.

 Theory:HTML is an acronym which stands for Hyper Text Markup Language which is used for
creating web pages and web applications. Let's see what is meant by Hypertext Markup Language, and
Web page.
 Hyper Text: Hypertext simply means "Text within Text." A text has a link within it, is a hypertext.
Whenever you click on a link which brings you to a new webpage, you have clicked on a hypertext.
Hypertext is a way to link two or more web pages (HTML documents) with each other.
 Markup language: A markup language is a computer language that is used to apply layout and
formatting conventions to a text document. Markup language makes text more interactive and dynamic.
It can turn text into images, tables, links, etc.
 Web Page: A web page is a document which is commonly written in HTML and translated by a web
browser. A web page can be identified by entering an URL. A Web page can be of the static or
dynamic type. With the help of HTML only, we can create static web pages.
 HTML is a markup language which is used for creating attractive web pages with the help of styling,
and which looks in a nice format on a web browser. An HTML document is made of many HTML tags
and each HTML tag contains different content.

1. <!DOCTYPE>
2. <html>
3. <head>
4. <title>Web page title</title>
5. </head>
6. <body>
7. <h1>Write Your First Heading</h1>
8. <p>Write Your First Paragraph.</p>
9. </body>
10. </html>

 HTML Tags are like keywords which define that how web browser will format and display the
content. With the help of tags, a web browser can distinguish between an HTML content and a simple
content. When a web browser reads an HTML document, browser reads it from top to bottom and left
to right. HTML tags are used to create HTML documents and render their properties. Each HTML
tags have different properties.

T.E. Computer Engineering AY 2023-24 Semester-II Page 4


WTL Lab (2019 Course)

 HTML Attribute: HTML attributes are special words which provide additional information about the
elements or attributes are the modifier of the HTML element.Each element or tag can have attributes,
which defines the behavior of that element.The Attribute should always be applied with its name and
value pair.

 A HTML heading or HTML h tag can be defined as a title or a subtitle which you want to
display on the webpage. When you place the text within the heading tags <h1>.........</h1>. It is
displayed on the browser in the bold format and size of the text depends on the number of
heading. There are six different HTML headings which are defined with the <h1> to <h6> tags,
from highest level h1 (main heading) to the least level h6 (least important heading).
 The HTML anchor tag defines a hyperlink that links one page to another page. It can create
hyperlink to other web page as well as files, location, or any URL. The "href" attribute is the
most important attribute of the HTML a tag. This links to destination page or URL. The href
attribute is used to define the address of the file to be linked. In other words, it points out the
destination page.
 The syntax of HTML anchor tag is given below. <a href = "..........."> Link Text
</a><a href="https://www.google.com/"> this-link </a>
 Style attributes setting the style of an HTML element, can be done with the style attribute. The
HTML style attribute has the syntax :<tagname style="property:value;">
 HTML Formatting Elements were designed to display special types of text:
 <b> - Bold text
 <strong> - Important text
 <i> - Italic text
 <em> - Emphasized text
 <mark> - Marked text
 <small> - Smaller text
 <del> - Deleted text
 <ins> - Inserted text
 <sub> - Subscript text
 <sup> - Superscript text

 You can add comments to your HTML source by using the following syntax:
<!-- This is a comment -->

<p>This is a paragraph.</p>

<!-- Remember to add more information here -->

 CSS stands for Cascading Style Sheets.


CSS saves a lot of work. It can control the layout of multiple web pages all at once.With CSS, you can
control the color, font, the size of text, the spacing between elements, how elements are positioned and laid
out, what background images or background colors are to be used, different displays for different devices
and screen sizes, and much more!

CSS can be added to HTML documents in 3 ways:

T.E. Computer Engineering AY 2023-24 Semester-II Page 5


WTL Lab (2019 Course)

 Inline - by using the style attribute inside HTML elements


 Internal - by using a <style> element in the <head> section
 External - by using a <link> element to link to an external CSS file

Inline CSS: - An inline CSS is used to apply a unique style to a single HTML element.
An inline CSS uses the style attribute of an HTML element.
The following example sets the text color of the <h1> element to blue, and the text color of
the <p> element to red:
<h1 style="color:blue;">A Blue Heading</h1>
<p style="color:red;">A red paragraph.</p>

Internal CSS:-An internal CSS is used to define a style for a single HTML page.
An internal CSS is defined in the <head> section of an HTML page, within a <style> element.
The following example sets the text color of ALL the <h1> elements (on that page) to blue, and the text
color of ALL the <p> elements to red. In addition, the page will be displayed with a "powderblue"
background color:
<!DOCTYPE html>
<html>
<head>
<style>
body {background-color: powderblue;}
h1 {color: blue;}
p {color: red;}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

External CSS:-An external style sheet is used to define the style for many HTML pages.
To use an external style sheet, add a link to it in the <head> section of each HTML page:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
</body>
</html>

Conclusion:

ASSIGNMENT NO: 3

T.E. Computer Engineering AY 2023-24 Semester-II Page 6


WTL Lab (2019 Course)

Title of Assignment:
XML,DTD and CSS/XSL.

Problem Statement: Design the XML document to store the information of the employees of any business
organization and demonstrate the use of:
a) DTD
b) XML Schema
And display the content in (e.g., tabular format) by using CSS/XSL.

Objectives:Students will be able to,


1. Design static webpage using XML.
2. Apply DTD to XML pages.
3. Apply CSS/XSLT to XML pages
Theory:
XML stands for Extensible Markup Language. It is nothing but the text-based markup
language which is derived from Standard Generalized Markup Language (SGML). XML tags
identify the data and are used to store and organize the data, rather than specifying how to
display it like HTML tags, which are used to display the data. XML is not going to replace
HTML in the near future, but it introduces new possibilities by adopting many successful
features of HTML.

There are three important characteristics of XML that make it useful in a variety of systems and
Solutions:
1. XML is extensible − XML allows you to create your own self-descriptive tags, or language, that
suits your application.
2. XML carries the data, does not present it − XML allows you to store the data irrespective of
how it will be presented.
3. 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.

Tools and Technology:-The XML document have an XML declaration, but it is optional, and it is
written as−<? xml version = "1.0" encoding = "UTF-8"?>
Where version is nothing but the version of an XML document and UTF specifies thecharacter-
encoding used in the document. Each XML-element needs to be closed eitherwith start or with end
elements −<element>.........</element>
An XML document can have only one root element.

XML Attributes:
Using a name/value pair, an attribute specifies a single property for an element. AnXML- element
can have one or more attributes. For example −
<a href = "http://www.google.com/">XMLTutorial</a>
Here href is the attribute name and http://www.google.com/ is attribute value.
 DTD:- What is a DTD?
DTD stands for Document Type Definition.

T.E. Computer Engineering AY 2023-24 Semester-II Page 7


WTL Lab (2019 Course)

The purpose of a DTD is to define the structure and the legal elements and attributes of an XML
document:
 When to Use a DTD?
With a DTD, independent groups of people can agree to use a standard DTD for interchanging data.
With a DTD, you can verify that the data you receive from the outside world is valid.
You can also use a DTD to verify your own data.
 When NOT to Use a DTD?
XML does not require a DTD.
When you are experimenting with XML, or when you are working with small XML files, creating
DTDs may be a waste of time.
If you develop applications, wait until the specification is stable before you add a DTD. Otherwise,
your software might stop working because of validation errors.

 XML Schema: An XML Schema describes the structure of an XML document, just like a DTD.
An XML document with correct syntax is called "Well Formed".
An XML document validated against an XML Schema is both "Well Formed" and "Valid".

HTML XML
1. It was written in 1993. It was released in 1996.
2. HTML stands for Hyper Text Markup XML stands for Extensible Markup Language.
Language.
3. HTML is static in nature. XML is dynamic in nature.
4. It was developed by WHATWG. It was developed by Worldwide Web
Consortium.
5. It is termed as a presentation language. It is neither termed as a presentation nor a
programming language.
6. HTML is a markup language. XML provides a framework to define markup
languages.
7. HTML can ignore small errors. XML does not allow errors.
8. It has an extension of .html and .htm It has an extension of .xml
9. HTML is not Case sensitive. XML is Case sensitive.
10. HTML tags are predefined tags. XML tags are user-defined tags.
11. There are limited numbers of tags in XML tags are extensible.
HTML.
12. HTML does not preserve white spaces. White space can be preserved in XML.
13. HTML tags are used for displaying the XML tags are used for describing the data not
data. for displaying.
14. In HTML, closing tags are not necessary. In XML, closing tags are necessary.
15. HTML is used to display the data. XML is used to store data.
16. HTML does not carry data it just displays XML carries the data to and from the database.
it.
17. HTML offers native object support. IN XML, the objects are expressed by
conventions using attributes.

T.E. Computer Engineering AY 2023-24 Semester-II Page 8


WTL Lab (2019 Course)

18. HTML document size is relatively small. XML document size is relatively large as the
approach of formatting and the codes both are
lengthy.
19. An additional application is not required DOM(Document Object Model) is required for
for parsing of JavaScript code into the parsing JavaScript codes and mapping of text.
20. Some of the tools used for HTML are: Some of the tools used for XML are:
Visual Studio Code
  Oxygen XML
How DTD Works in XML?
DTD is also the schema language preferred in markup language. The general Syntax is given below:
<!DOCTYPE root element name
[
declaration1
declaration2
<!ELEMENT><ATTLIST><!ENTITY><!NOTATION>
]>

In the above syntax, the DTD name is the root element name and followed by options which say about the
schemas and types. The keyword! DOCTYPE should be uppercase. Let’s see Element declarations.
The working of DTD is performed by the following steps:
 First, create a DTD file for the respective XML Document.
 Next outline the structure of the document.
 Initiate with the root node which is the same as DOCTYPE. You can create DTD either internal or
external references.
 Include all the elements, attributes, entities for the file. The parser eliminates empty elements.

Element Declarations:-The element specifications with the sequence of its elements are stated as
<!ELEMENT name (seq of elements)> Also, the element specifies the number of occurrences of the child
elements using (+, *,? ).
 + sign indicates two or more frequency, *indicates the element can appear more number of times.
 ? Indicates elements can occur only once.
 The following declaration is <!ELEMENT pizza (onion? Cheese*((veg|noveg) + |topping))>
 The above statement implies that the pizza element can have one onion elements followed by one or
more cheese and so on.
<pizza>
<onion> fried </onion>
<cheese> thin </cheese>
<cheese> thick </cheese>
<topping>oregano </topping>
</pizza>
 Attribute Declarations
The attributes for a given element is designed by the following rule:
<!ATTLIST element name attribute names 1 attribute type restriction/Default >

T.E. Computer Engineering AY 2023-24 Semester-II Page 9


WTL Lab (2019 Course)

here attribute is specified using the keyword ATTLIST, the element name is included for the
respective attributes unless they are optional. The attribute types include PCDATA, tokens, entity,
notation. Last is restriction/default they are placed based on the occurrences of the values. The
attribute default includes #IMPLIED, #REQUIRED, #FIXED. The implied specifies the attribute
value doesn’t appear and required implies the attribute value is present and fixed denotes a constant
value.
 Defining Entities
Entity is used to specify special characters. The entity declaration is
<!ENTITY entity_name SYSTEM "URL path">
Ex:
<!ENTITY SYSTEM "http://www. ckjd.com/pot.dtd">
As DTD is model of the XML document it talks about the elements, attributes being used which are
essential and optional as they are easy to validate the document and there are two types of DTDs
namely,
 Internal DTD
 External DTD

Conclusion:-

ASSIGNMENT NO: 4
T.E. Computer Engineering AY 2023-24 Semester-II Page 10
WTL Lab (2019 Course)

Title of Assignment:Implement a Scientific Calculator application using JavaScript

Problem Statement:
DesignandimplementasimplecalculatorusingJavaScriptforoperationslikeaddition,multiplication,subtraction,
division, square of number etc.
1. Design calculator interface like text field for input and output, buttons for numbers and operators etc.
2. Validate input values
3. Prompt/alerts for invalid values etc.

Objectives: Learn how to validate input in java script.Working with alert massage.

Theory: JavaScript is a light-weight object-oriented programming language that is used by several


websites for scripting the webpages. It is an interpreted, full-fledged programming language. JavaScript
enables dynamic interactivity on websites when it is applied to an HTML document.

JavaScript helps the users to build modern web applications to interact directly without reloading the page
every time. JavaScript is commonly used to dynamically modify HTML and CSS to update a user interface
by the DOM API. It is mainly used in web applications.

 Use of JavaScript.
o Client-side validation.
o Displaying date and time.
o To validate the user input before submission of the form.
o Open and close new windows.
o To display dialog boxes and pop-up windows.
o To change the appearance of HTML documents.
o To create the forms that respond to user input without accessing the server.

T.E. Computer Engineering AY 2023-24 Semester-II Page 11


WTL Lab (2019 Course)

 Difference between Java and Java Script

Sr.no. Java language Java Script

1 It is a Programming language. It is a scripting language.

2. Java is a pure Object Oriented JavaScript is Object-Based Language.


Programming Language.

3. Java is a Standalone language. JavaScript is not a standalone language, as it needs


to be integrated into an HTML program for
execution.

4. Java is a strongly typed language, JavaScript is a loosely typed language, which means
which means that the user has to decide that the user does not have to worry about the data-
the data type of the variable before type of the variable before and after the declaration.
declaring and using it. Example "var a", the "a" variable can store the value
Example "int a", the variable "a" can of any data-type.
store the value of integer type only.

5. Java program should be compiled JavaScript needs to be integrated into the HTML
before execution. program for the execution.

6. The web-browser is not required to run The web-browser is essential to run the JavaScript
java programs. programs.

7. It is one of the complex languages to It one of the easy languages to learn.


learn.

8. In Java, by utilizing the Multi- In JavaScript, user is not able to perform


threading, users can perform complicated tasks.
complicated tasks.

9. It requires a large amount of memory. It does not require that amount of memory.

10. Java programming language was JavaScript programming language was developed by
developed by the "Sun Microsystems." the "Netscape."

11. In Java programming language, On the other hand, programs in JavaScript are saved
programs are saved with the ".java" with the ".js" extension.
extension.

12. Java is stored on the host machine as JavaScript is stored on the Host machine (client
the "Byte" code. Machine) as the "source" text.

Validation:
When a client enters all the necessary data and presses the submit button, form
validation is done at server side If data entered by a client is incorrect or missing, the server

T.E. Computer Engineering AY 2023-24 Semester-II Page 12


WTL Lab (2019 Course)

needs to send all data back to the client and request for resubmission of form with correct
information. This is really a lengthy process which puts a lot of load(burden) on the server.

So, JavaScript provides a way to validate form's data on the client's side itself before sending
it to the web server. Form validation performs two functions-

o Basic Validation –First of all the form must be checked to make sure all the mandatory
fields are filled in. It would require just a loop through each field in the form and
check for the data.
o Data Format Validation − Secondly, the data that is entered must be checked for
correctFormat and its value. The code must include appropriate logic to test correctness of
data.
Following steps are used to Create and Execute web applications,

1. Write a code in notepad/Notepad++/Sublime editor and save with .html extension.


2. Design UI of application using HTML, CSS etc.
3. Include Javascript validation
4. Use of prompt and alert window using Javascripte.g., Design and implement a simple
calculator using Javascript for operations like addition, Multiplication, subtraction, division,
square of number etc.
5. Design calculator interface like text field for input and output, buttons for numbers
andOperators etc.
6. Validate input values
7. Prompt/alerts for invalid values etc
8. Open HTML page in the browser.

Manual testing is used to check following validations


o Input should be numbers and operations only.
o If instead of numbers some other input-like text is filled by the user then code must
validate the same and an alert message should be printed.

The alert () method in JavaScript is used to display a virtual alert box. It is mostly used to give a warning
message to the users. It displays an alert dialog box that consists of some specified message (which is
optional) and an OK button. When the dialog box pops up, we have to click "OK" to proceed.

The alert dialog box takes the focus and forces the user to read the specified message. So, we should avoid
overusing this method because it stops the user from accessing the other parts of the webpage until the box
is closed.

We can understand the usefulness of the alert method using an example. Suppose we have to fill a form for
an identity card. It asks about the date of birth for the eligibility criteria of the identity card. If the age is 18
years or above, then the process will continue. Otherwise, it will show a warning message that the age is
below 18 years. This warning message is the 'Alert Box'.

T.E. Computer Engineering AY 2023-24 Semester-II Page 13


WTL Lab (2019 Course)

Another example is suppose a user is required to fill the form in which some mandatory fields are required
to enter some text, but the user forgets to provide the input. As the part of the validation, we can use the
alert dialog box to show a warning message related to fill the textfield.

<html>
<head> <script type = "text/javascript">
function fun() {
alert (" Hello World \n Welcome to the javaTpoint.com \n This is an alert dialog box ");
}
</script> </head>
<body>
<p> Click the following button to see the effect </p>
<form>
<input type = "button" value = "Click me" onclick = "fun();" />
</form>
</body>
</html>

JavaScript is used in several ways in web pages such as generate warning messages, build image galleries,
DOM manipulation, form validation, and more. Method to add JavaScript.
1. Embedding code
2. Inline code
3. External file

I. Embedding code:-
To add the JavaScript code into the HTML pages, we can use the <script>.....</script> tag of the HTML
that wrap around JavaScript code inside the HTML program. Users can also define JavaScript code in
the <body> tag (or we can say body section) or <head> tag because it completely depends on the structure
of the web page that the users use.
<!DOCTYPE html >
<html>
<head>
<title> page title</title>
<script>
document.write("Welcome to Javatpoint");
</script>
</head>
<body>
<p>Inthis example we saw how to add JavaScript in the head section </p>

T.E. Computer Engineering AY 2023-24 Semester-II Page 14


WTL Lab (2019 Course)

</body>
</html>
Output:-

II. Inline code:-Generally, this method is used when we have to call a function in the HTML event
attributes. There are many cases (or events) in which we have to add JavaScript code directly eg., OnMover
event, OnClick, etc.

<!DOCTYPE html >


<html>
<head>
<title> page title</title>
</head>
<body>
<p>
<a href="#" onClick="alert('Welcome !');">Click Me</a>
</p>
<p> in this example we saw how to use inline JavaScript or directly in an HTML tag. </p>
</body>
</html>
Output:-

T.E. Computer Engineering AY 2023-24 Semester-II Page 15


WTL Lab (2019 Course)

III. External file:- We can also create a separate file to hold the code of JavaScript with the (.js) extension
and later incorporate/include it into our HTML document using the src attribute of the <script> tag. It
becomes very helpful if we want to use the same code in multiple HTML documents. It also saves us from
the task of writing the same code over and over again and makes it easier to maintain web pages.

<html>
<head>
<meta charset="utf-8">
<title>Including a External JavaScript File</title>
</head>
<body>
<form>
<input type="button" value="Result" onclick="display()"/>
</form>
<script src="hello.js">
</script>
</body>
</html>
//!---Hello.js
function display() {
alert("Hello World!");

T.E. Computer Engineering AY 2023-24 Semester-II Page 16


WTL Lab (2019 Course)

Output:-

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 17


WTL Lab (2019 Course)

ASSIGNMENT NO: 5
Title of Assignment:ImplementthesampleprogramdemonstratingtheuseofServlet.

Problem Statement: Students createadatabasetableeBook


shop(book_id,book_title,book_author,book_price,quantity) using database like Oracle/MySQL etc. and
display (use SQL select query) the tablecontentusing Servlet.

Objectives:

Software Needed:
1. Any Operating System
2. JDK 7or later
3. Editors:Netbeans/Eclipse
4. Web browser
5. Tomcat 7 or later

Theory:
Servlet: What is Servlet?

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the incoming requests.
It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.

T.E. Computer Engineering AY 2023-24 Semester-II Page 18


WTL Lab (2019 Course)

Figure.2: life cycle of Servlet

1. Loading a Servlet: The first stage of the Servlet lifecycle involves loading and initializing the
Servlet by the Servlet container. The Web container or Servlet Container can load the Servlet
at either of the following two stages :
Initializing the context, on configuring the Servlet with a zero or positive integer value.
If the Servlet is not preceding stage, it may delay the loading process until the Web container
determines that this Servlet is needed to service a request.
The Servlet container performs two operations in this stage :
a. Loading : Loads the Servlet class.
b. Instantiation : Creates an instance of the Servlet. To create a new instance of the
Servlet, the container uses the no-argument constructor.

2. Initializing a Servlet: After the Servlet is instantiated successfully, the Servlet container
initializes the instantiated Servlet object. The container initializes the Servlet object by
invoking the Servlet.init(ServletConfig) method which accepts ServletConfig object reference
as parameter.
The Servlet container invokes the Servlet.init(ServletConfig) method only once, immediately
after the Servlet.init(ServletConfig) object is instantiated successfully. This method is used to
initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing
the ServletException or UnavailableException.

3. Handling request: After initialization, the Servlet instance is ready to serve the client requests.
The Servlet container performs the following operations when the Servlet instance is located
to service a request :

T.E. Computer Engineering AY 2023-24 Semester-II Page 19


WTL Lab (2019 Course)

a. It creates the ServletRequest and ServletResponse objects. In this case, if this is a


HTTP request, then the Web container
creates HttpServletRequest and HttpServletResponse objects which are subtypes of
the ServletRequest and ServletResponse objects respectively.
b. After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the request and
response objects.
The service() method while processing the request may throw
the ServletException or UnavailableException or IOException.
4. Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the
following operations,
a. It allows all the threads currently running in the service method of the Servlet instance to
complete their jobs and get released.
b. After currently running threads have completed their jobs, the Servlet container calls
the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the references of this Servlet
instance so that it becomes eligible for garbage collection

Servlet Advantage
1. Servlets provide a way to generate dynamic documents that is both easier to write and faster to run.
2. provide all the powerfull features of JAVA, such as Exception handling and garbage collection.
3. Servlet enables easy portability across Web Servers.
4. Servlet can communicate with different servlet and servers.
5. Since all web applications are stateless protocol, servlet uses its own API to maintain session

Servlet Disadvantage
1. Designing in servlet is difficult and slows down the application.
2. Writing complex business logic makes the application difficult to understand.
3. You need a Java Runtime Environment on the server to run servlets. CGI is a completely language
independent protocol, so you can write CGIs in whatever languages you have available (including Java
if you want to).

Technology/Tool In Brief
1. JSP and Servlets
2. IDE: NetBeans 7.0 or Later
3. Databases: MySQL

NetBeans: NetBeans is an IDE, used for quickly and easily developing java desktop, mobile,and web
applications, as well as HTML5 applications with HTML, JavaScript, and CSS. Also provides a huge set of
tools for PHP and C/C++ developers. It is free and open source tool and has a great community of users
and developers around the world.
MySQL: MySQL is a freely available open source Relational Database Management System(RDBMS). It
uses the Structured Query Language (SQL).

T.E. Computer Engineering AY 2023-24 Semester-II Page 20


WTL Lab (2019 Course)

SQL is the most popular language for adding, accessing and managing data in a database. It is most noted
for its quick processing, proven reliability, ease and flexibility of use. MySQL is an essential part of almost
every open source PHP application. Good examples for PHP & MySQL-based scripts are WordPress,
Joomla, Magento and Drupal.

How to configure tomcat server in Eclipse IDE


If you are using Eclipse IDE first time, you need to configure the tomcat server First. For configuring the
tomcat server in eclipse IDE, click on servers tab at the bottom side of the IDE -> right click on blank area
-> New -> Servers -> choose tomcat then its version -> next -> click on Browse button -> select the apache
tomcat root folder previous to bin -> next ->addAll -> Finish.

T.E. Computer Engineering AY 2023-24 Semester-II Page 21


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 22


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 23


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 24


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 25


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 26


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 27


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 28


WTL Lab (2019 Course)

Now tomcat7 server has been configured in eclipse IDE.

T.E. Computer Engineering AY 2023-24 Semester-II Page 29


WTL Lab (2019 Course)

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 30


WTL Lab (2019 Course)

ASSIGNMENT NO: 6
Title of Assignment:Implement theprogramdemonstratingtheuseofJSP.

Problem Statement: Create a database table students_info (stud_id, stud_name, class, division, city) using
database like Oracle/MySQL etc. and display (use SQL select query) the table content using JSP.

Objectives: Understand about basic concepts of html, CSS


1. Understand the basic functionalities of JSP
2. Having the knowledge of SQL query to create the database

Software Needed:
1. Any Operating System
2. JDK 7or later
3. Editors: Netbeans/Eclipse
4. Web browser
5. Tomcat 7 or later

Theory:
Java Server Pages (JSP): It is a server side programming technology that is used to createdynamic web-
based applications. JSP have right to use the complete Java APIs, including the JDBC API to access the
databases.
It is a technology that helps software developers to create dynamic web pages based on HTML, XML and
other document types. It was released in 1999 by Sun Microsystems. It is just like a PHP and ASP, but it
uses the Java programming language.
A JSP element is a type of java servlet that is designed to accomplish 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 rooted JSP actions and commands.
Using JSP, you can collect input from users through webpage forms, current records from a database or
another source and create web pages dynamically.
JSP tags can be used for different 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.
Why we need JSP?
JSP is used for the design of dynamic web page and servlet is used to code the logic that is present i.e. in
the MVC (Model-View-Controller) architecture, the servlet is the controller and the JSP is the view.
Architecture of JSP
1. The request / response part of a JSP is defined in below architecture
2. The client initiated request for a JSP file using browser
3. Webs server (i.e, JSP Engine) invokes the JSP file and interpret the JSP file produce a java code.
The created java code will be a Servlet.

T.E. Computer Engineering AY 2023-24 Semester-II Page 31


WTL Lab (2019 Course)

4. Once Servlet is created, JSP engine compiles the servlet. Compilation errors will be detected in this
phase.
5. Now servlet class is loaded by the container and executes it.
6. Engine sends the response back to the client.

Figure.1: Architecture of JSP


Syntax of JSP:
JSP declarations is used to declare variables and methods as shown below,
<%text %>
Following is the simple and first example for JSP:
//Hello.jsp
<html>
<head>
<title> JSP File</title>
</head>
<body>
<%
out.println("Welcome to JSP Class");
%>
</body>
</html>
Output:
Welcome to JSP Class
Servlet:
A Servlet is a server side program and written in Java. Servlet is a web component that is deployed on the
server for creating the dynamic web pages. A Java servlet is a Java program that extends the capabilities of

T.E. Computer Engineering AY 2023-24 Semester-II Page 32


WTL Lab (2019 Course)

a server. Although servlets can respond to any types of requests, they most commonly execute applications
hosted on Web servers.

Figure.2: Functions of Servlet


Technology/Tool In Brief
 JSP and Servlets
 IDE: NetBeans 7.0 or Later
 Databases: MySQL

NetBeans: NetBeans is an IDE, used for quickly and easily developing java desktop, mobile,and web
applications, as well as HTML5 applications with HTML, JavaScript, and CSS. Also provides a huge set of
tools for PHP and C/C++ developers. It is free and open source tool and has a great community of users
and developers around the world.
MySQL: MySQL is a freely available open source Relational Database Management System(RDBMS). It
uses the Structured Query Language (SQL).
SQL is the most popular language for adding, accessing and managing data in a database. It is most noted
for its quick processing, proven reliability, ease and flexibility of use. MySQL is an essential part of almost
every open source PHP application. Good examples for PHP & MySQL-based scripts are WordPress,
Joomla, Magento and Drupal.
Design / Execution Steps
Following steps are used to Create and Execute web applications,
1. Design html and jsp files with an extension of.html and .jsp
2. Write database connection page using servlet
3. Set MySQL username, password and database name in database connection page
4. Start the Tomcat Server with port number
5. Open the browser and type localhost:8084

Test Cases
Manual testing is used to validate the fields like username, password, mobile number and email id’s of
the users entered by user with the database.

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 33


WTL Lab (2019 Course)

ASSIGNMENT NO: 7
Title of Assignment:Buildadynamic webapplication usingPHPand MySQL.

Problem Statement: CreatedatabasetablesinMySQL andcreate connectionwithPHP.


Create add, update, delete and retrieve functions in the PHP web app interacting with MySQL database.

Objectives:
Theory:
What is PHP?
 PHP is an acronym for "PHP: Hypertext Preprocessor"
 PHP is a widely-used, open source scripting language
 PHP scripts are executed on the server
 PHP is free to download and use

What Can PHP Do?


 PHP can generate dynamic page content
 PHP can create, open, read, write, delete, and close files on the server
 PHP can collect form data, 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

PHP supports the following data types:


 String,Integer
 Float (floating point numbers - also called double)
 Boolean
 Array
 Object
 NULL
 Resource

<!DOCTYPE html>
<html><body>

<?php
$x = "Hello world!";
$y = 'Hello world!';
$x = 5985;
$cars = array("Volvo","BMW","Toyota");

echo $x;
echo "<br>";
echo $y;
echo "<br>";
echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
?>
</body></html>

T.E. Computer Engineering AY 2023-24 Semester-II Page 34


WTL Lab (2019 Course)

With PHP you are not limited to output HTML. You can output images or PDF files. You can also output
any text, such as XHTML and XML.

Creating a Database
To create and delete a database you should have admin privilege. Its very easy to create a new MySQL
database. PHP uses mysql_query function to create a MySQL database. This function takes two
parameters and returns TRUE on success or FALSE on failure.
Syntax: bool mysql_query( sql, connection );
Sr.No Parameter & Description

1 Sql
Required - SQL query to create a database

2 Connection
Optional - if not specified then last opend connection by mysql_connect will be used.
Example
Try out following example to create a database −
<?php
$dbhost='localhost:3036';
$dbuser='root';
$dbpass='rootpassword';
$conn =mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ){
die('Could not connect: '.mysql_error());
}

echo 'Connected successfully';

$sql='CREATE Database test_db';


$retval=mysql_query( $sql, $conn );

if(! $retval){
die('Could not create database: '.mysql_error());
}

echo "Database test_db created successfully\n";


mysql_close($conn);
?>

Selecting a Database
Once you establish a connection with a database server then it is required to select a particular database
where your all the tables are associated.
This is required because there may be multiple databases residing on a single server and you can do work
with a single database at a time.

T.E. Computer Engineering AY 2023-24 Semester-II Page 35


WTL Lab (2019 Course)

PHP provides function mysql_select_db to select a database.It returns TRUE on success or FALSE on
failure.
Syntax: bool mysql_select_db( db_name, connection );
Sr.No Parameter & Description

1 db_name
Required - Database name to be selected

2 Connection
Optional - if not specified then last opend connection by mysql_connect will be used.
Example
Here is the example showing you how to select a database.
<?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_select_db('test_db');
mysql_close($conn);

?>

Creating Database Tables


To create tables in the new database you need to do the same thing as creating the database. First create the
SQL query to create the tables then execute the query using mysql_query() function.
Example
Try out following example to create a table −
<?php

$dbhost='localhost:3036';
$dbuser='root';
$dbpass='rootpassword';
$conn =mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ){
die('Could not connect: '.mysql_error());
}

T.E. Computer Engineering AY 2023-24 Semester-II Page 36


WTL Lab (2019 Course)

echo 'Connected successfully';

$sql='CREATE TABLE employee( '.


'emp_id INT NOT NULL AUTO_INCREMENT, '.
'emp_nameVARCHAR(20) NOT NULL, '.
'emp_address VARCHAR(20) NOT NULL, '.
'emp_salary INT NOT NULL, '.
'join_datetimestamp(14) NOT NULL, '.
'primary key ( emp_id ))';
mysql_select_db('test_db');
$retval=mysql_query( $sql, $conn );

if(! $retval){
die('Could not create table: '.mysql_error());
}

echo "Table employee created successfully\n";

mysql_close($conn);
?>
In case you need to create many tables then its better to create a text file first and put all the SQL
commands in that text file and then load that file into $sql variable and excute those commands.
Consider the following content in sql_query.txt file
CREATE TABLE employee(
emp_id INT NOT NULL AUTO_INCREMENT,
emp_nameVARCHAR(20) NOT NULL,
emp_address VARCHAR(20) NOT NULL,
emp_salary INT NOT NULL,
join_datetimestamp(14) NOT NULL,
primary key ( emp_id ));
<?php
$dbhost='localhost:3036';
$dbuser='root';
$dbpass='rootpassword';
$conn =mysql_connect($dbhost, $dbuser, $dbpass);

if(! $conn ){
die('Could not connect: '.mysql_error());
}

$query_file='sql_query.txt';

$fp=fopen($query_file,'r');
$sql=fread($fp,filesize($query_file));
fclose($fp);

mysql_select_db('test_db');

T.E. Computer Engineering AY 2023-24 Semester-II Page 37


WTL Lab (2019 Course)

$retval=mysql_query( $sql, $conn );

if(! $retval){
die('Could not create table: '.mysql_error());
}

echo "Table employee created successfully\n";


mysql_close($conn);
?>

What is CRUD
CRUD is an acronym for Create, Read, Update, and Delete. CRUD operations are basic data manipulation
for database. We've already learned how to perform create (i.e. insert), read (i.e. select), update and delete
operations in previous chapters. In this tutorial we'll create a simple PHP application to perform all these
operations on a MySQL database table at one place.

Creating the Database Table:-Execute the following SQL query to create a table named employees inside
your MySQL database. We will use this table for all of our future operations.

CREATETABLE employees (
id INTNOTNULLPRIMARYKEYAUTO_INCREMENT,
name VARCHAR(100)NOTNULL,
address VARCHAR(255)NOTNULL,
salary INT(10)NOTNULL
);

Creating the Config File


After creating the table, we need create a PHP script in order to connect to the MySQL database server.
Let's create a file named "config.php" and put the following code inside it.
We'll later include this config file in other pages using the PHP require_once() function.
<?php
/* Database credentials. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
define('DB_SERVER','localhost');
define('DB_USERNAME','root');
define('DB_PASSWORD','');
define('DB_NAME','demo');

/* Attempt to connect to MySQL database */


$link=mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME);
// Check connection
if($link===false){
die("ERROR: Could not connect. ".mysqli_connect_error());
}
?>
If you've downloaded the Object Oriented or PDO code examples using the download button, please
remove the text "-oo-format" or "-pdo-format" from file names before testing the code.

T.E. Computer Engineering AY 2023-24 Semester-II Page 38


WTL Lab (2019 Course)

Creating the Landing Page:-First we will create a landing page for our CRUD application that contains a
data grid showing the records from the employees database table. It also has action icons for each record
displayed in the grid that you may choose to view its details, update it, or delete it.
We'll also add a create button on the top of the data grid that can be used for creating new records in
the employees table. Create a file named "index.php" and put the following code in it:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Dashboard</title>
<link rel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<link rel="stylesheet"href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-
awesome.min.css">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<style>
.wrapper{
width: 600px;
margin: 0 auto;}
table tr td:last-child{
width: 120px;}
</style>
<script>
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip();
});
</script>
</head>
<body>
<div class="wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<div class="mt-5 mb-3 clearfix">
<h2 class="pull-left">Employees Details</h2>
<a href="create.php"class="btnbtn-success pull-right"><iclass="fa fa-plus"></i> Add New Employee</a>
</div>
<?php
// Include config file
require_once"config.php";

// Attempt select query execution


$sql="SELECT * FROM employees";
if($result=mysqli_query($link,$sql)){
if(mysqli_num_rows($result)>0){
echo'<table class="table table-bordered table-striped">';
echo"<thead>";

T.E. Computer Engineering AY 2023-24 Semester-II Page 39


WTL Lab (2019 Course)

echo"<tr>";
echo"<th>#</th>";
echo"<th>Name</th>";
echo"<th>Address</th>";
echo"<th>Salary</th>";
echo"<th>Action</th>";
echo"</tr>";
echo"</thead>";
echo"<tbody>";
while($row=mysqli_fetch_array($result)){
echo"<tr>";
echo"<td>".$row['id']."</td>";
echo"<td>".$row['name']."</td>";
echo"<td>".$row['address']."</td>";
echo"<td>".$row['salary']."</td>";
echo"<td>";
echo'<a href="read.php?id='.$row['id'].'" class="mr-3" title="View Record" data-toggle="tooltip"><span
class="fa fa-eye"></span></a>';
echo'<a href="update.php?id='.$row['id'].'" class="mr-3" title="Update Record" data-
toggle="tooltip"><span class="fa fa-pencil"></span></a>';
echo'<a href="delete.php?id='.$row['id'].'" title="Delete Record" data-toggle="tooltip"><span class="fa fa-
trash"></span></a>';
echo"</td>";
echo"</tr>";
}
echo"</tbody>";
echo"</table>";
// Free result set
mysqli_free_result($result);
}else{
echo'<div class="alert alert-danger"><em>No records were found.</em></div>';
}
}else{
echo"Oops! Something went wrong. Please try again later.";
}
// Close connection
mysqli_close($link);
?>
</div>
</div>
</div>
</div>
</body>
</html>
Once employees table is populated with some records the landing page i.e. the CRUD data grid may look
something like the picture shown below:

T.E. Computer Engineering AY 2023-24 Semester-II Page 40


WTL Lab (2019 Course)

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 41


WTL Lab (2019 Course)

ASSIGNMENT NO: 8
Title of Assignment:Buildadynamic webapplication usingStrut and performfollowing validations.

Problem Statement:
Designaloginpagewithentriesforname,mobilenumberemailidandloginbutton.Usestrutsand
performfollowing validations
a. Validationforcorrectnames
b. Validationfor mobilenumbers
c. Validationfor emailid
d. Validationif no enteredany value
e. Re-displayforwronglyentered valueswithmessage
f. Congratulationsand welcomepage uponsuccessful entries

Objectives:
Theory:
Apache Struts 2 is an open-source web application framework for developing Java EE web applications.
It uses and extends the Java Servlet API to encourage developers to adopt a model–view–controller
architecture. In this article, we will see how we can create a login page with validations using Struts 2.
We will use struts UI tags to create a login page.
Before creating your Struts2 project it is important to make sure that you have the Apache Tomcat server
installed and configured with the IDE of your choice like Eclipse. Now, if the above conditions are
fulfilled then follow all the steps given below. We are going to use Eclipse IDE so that all the required
components will be created under a Dynamic Web Project. Let us now start with creating Dynamic Web
Project.
Creating Dynamic Web Project
First, you simply need to start your Eclipse IDE and create a new Dynamic Web Project project. To do
this go to File > New > Dynamic Web Project and enter the project name as per your wish. I have
named it “struts_validation”

T.E. Computer Engineering AY 2023-24 Semester-II Page 42


WTL Lab (2019 Course)

Set the rest of the options as given in the following screen

Select all the default options on the next screens and don’t forget to check the Generate web.xml
deployment descriptor option

T.E. Computer Engineering AY 2023-24 Semester-II Page 43


WTL Lab (2019 Course)

This will create a dynamic web project for you in Eclipse.


Setup Struts2 Libraries
Now to run the Struts2 application, you need to set up your Struts2 framework.
1. You need to download and install Struts2 on your machine.
2. Download the latest version of Struts2 binaries from here.
3. At the time of writing this article, I downloaded struts-2.5.30-min-lib.zip.
4. After unzipping the downloaded file, you will get files inside struts-2.5.30/lib as follows

struts-2.5.30 directory structure

Now copy all the files from the struts-2.2.3\lib folder to your project’s WEB-INF\lib folder. You can do
this by simply dragging and dropping all the files into the WEB-INF\lib folder. Your project structure
should now look like this

project structure

T.E. Computer Engineering AY 2023-24 Semester-II Page 44


WTL Lab (2019 Course)

web.xml File:
Create a web.xml file under the webapp/WEB-INF folder and copy the following code in web.xml.
XML

<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
id="WebApp_ID"version="4.0">

<display-name>struts_validation</display-name>

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

<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

index.jsp File:
We need a JSP file to display the final result, this page will be called by the Struts 2 framework where a
predefined action will be called and this mapping is defined in the struts.xml file. So we will now create
an index.jsp under the webapp folder in your eclipse project. To create a JSP file, right-click on
the webapp folder in the project explorer and select New >JSP File.

creating JSP file

T.E. Computer Engineering AY 2023-24 Semester-II Page 45


WTL Lab (2019 Course)

Now copy the following code into the index.jsp file


HTML

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


pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags" prefix="s" %>

<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title>Login</title>
<s:head/>
</head>

<bodybgColor="lightGreen">
<s:formaction="Login">
<s:textfieldname="userName"label="User Name"placeholder="Default 'Sanjyot'"/>
<s:passwordname="password"label="Password"/>
<s:textfieldname="phoneNumber"label="Phone Number"placeholder="10 digit phone number"/>
<s:textfieldname="email"label="Email"type="email"/>
<s:submitvalue="Login"/>
</s:form>
</body>
</html>

The <%@tagliburi=”/struts-tags” prefix=”s” %> is a directive that tells the Servlet Container that this
page will be using the Struts2 tags and these tags will be preceded by s. The s:form tag contains all the
form elements. When the user clicks on the Login button, the request is forwarded to the Login action
class.
welcome.jsp File:
Create welcome.jsp under the webapp folder and copy the following code into welcome.jsp
HTML

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


pageEncoding="UTF-8"%>
<%@tagliburi="/struts-tags" prefix="s" %>

<!DOCTYPE html>
<html>
<head>
<metacharset="UTF-8">
<title>Login Successful</title>
</head>

T.E. Computer Engineering AY 2023-24 Semester-II Page 46


WTL Lab (2019 Course)

<body>
<h3> Congratulations! You have logged in successfully.</h3>
<h4> Welcome <s:propertyvalue="userName"/>!!! </h4>
</body>

Action class: Login.java File


Our Login class extends ActionSupport. It is good to extend ActionSupport class as it provides a default
implementation for most common tasks. Create a Login.java class and Copy the following code into
Login.java
Java

packagecom.SanjyotPanure.struts2;

importcom.opensymphony.xwork2.ActionSupport;

publicclassLogin extendsActionSupport {

privateString userName;
privateString password;
privateString phoneNumber;
privateString email;

publicString execute() { returnSUCCESS; }


publicString getUserName() { returnuserName; }
publicvoidsetUserName(String userName) { this.userName = userName; }
publicString getPassword() { returnpassword; }
publicvoidsetPassword(String password) { this.password = password; }
publicString getPhoneNumber() { returnphoneNumber; }
publicvoidsetPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; }
publicString getEmail() { returnemail; }
publicvoidsetEmail(String email) { this.email = email; }

publicvoidvalidate() {
if(getUserName().length() == 0) {
addFieldError("userName", "UserName is required");
}
elseif(!getUserName().equals("Sanjyot"))
{
addFieldError("userName", "Invalid User");
}
if(getPassword().length() == 0)
{

T.E. Computer Engineering AY 2023-24 Semester-II Page 47


WTL Lab (2019 Course)

addFieldError("password", getText("Password is required"));


}
if(getPhoneNumber().length() == 0)
{
addFieldError("phoneNumber", getText("Phone Number is required"));
}
elseif(!(getPhoneNumber().length() == 10))
{
addFieldError("phoneNumber", "Enter 10 digit phone number");
}
if(getEmail().length() == 0)
{
addFieldError("email", getText("Email is required"));
}
}
}

struts.xml File:
We need a mapping between URL to action mapping. The struts.xml maps the Login class, and the
welcome.jsp together. The mapping tells the Struts 2 framework which class will respond to the user’s
action (the URL), which method of that class will be executed, and what view to render based on the
String result that method returns. So we will now create a struts.xml file under the webapp/WEB-
INF folder. Copy the following code into struts.xml:
XML

<?xmlversion="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>
<constantname="struts.custom.i18n.resources"value="LoginAction"/>
<packagename="default"extends="struts-default"namespace="/">
<actionname="Login"class="com.SanjyotPanure.struts2.Login">
<resultname="success">welcome.jsp</result>
<resultname="input">index.jsp</result>
</action>
</package>
</struts>

Here our “default” package extends the “struts-default” package. By extending the “struts-default”
package the action will by default inherit the set of interceptors defined in the default stack. The “struts-
default” package is defined in the struts-default.xml file.

T.E. Computer Engineering AY 2023-24 Semester-II Page 48


WTL Lab (2019 Course)

How to run the project?


Right-click on project > run as > run on server

Right-click on project->run as->run on server

If you’re running your project for the first time you’ll get a prompt as follows:

run on server

T.E. Computer Engineering AY 2023-24 Semester-II Page 49


WTL Lab (2019 Course)

Output
Now expand localhost and select your tomcat server. After this click on the next and finish. You will see
a web page opened on your Eclipse IDE like this:

output screen

All the input fields are required. If you try to submit without entering details you will get a screen as
follows:

output screen- all fields required

The Phone Number should be 10 digits. If you enter an incorrect phone number, you’ll get the following
screen:

T.E. Computer Engineering AY 2023-24 Semester-II Page 50


WTL Lab (2019 Course)

output screen- incorrect phone number

The default User Name is “Sanjyot” and password you can enter anything. After you enter the correct
User Name you’ll get the following screen:

welcome screen

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 51


WTL Lab (2019 Course)

ASSIGNMENT NO: 9
Title of Assignment:Design an application for registration using Angular JS.

Problem Statement: Design an application using Angular JS.

e.g., Design registration (first name, last name, username, password) and login page using
Angular JS.

Objectives:
Theory:

AngularJS is an open-source web application framework. It was originally developed in 2009 by


MiskoHevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.2.21.
General Features
The general features of AngularJS are as follows −
 AngularJS is a efficient framework that can create Rich Internet Applications (RIA).
 AngularJS provides developers an options to write client side applications using JavaScript in a
clean Model View Controller (MVC) way.
 Applications written in AngularJS are cross-browser compliant. AngularJS automatically handles
JavaScript code suitable for each browser.
 AngularJS is open source, completely free, and used by thousands of developers around the world.
It is licensed under the Apache license version 2.0.
Overall, AngularJS is a framework to build large scale, high-performance, and easyto-maintain web
applications.
Angular is a platform and framework for building single-page client applications using HTML and
TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of
TypeScript libraries that you import into your applications.
The architecture of an Angular application relies on certain fundamental concepts. The basic building
blocks of the Angular framework are Angular components that are organized into NgModules. NgModules
collect related code into functional sets; an Angular application is defined by a set of NgModules. An
application always has at least a root module that enables bootstrapping, and typically has many
more feature modules.
 Components define views, which are sets of screen elements that Angular can choose among and
modify according to your program logic and data
 Components use services, which provide specific functionality not directly related to views. Service
providers can be injected into components as dependencies, making your code modular, reusable,
and efficient.
Modules, components and services are classes that use decorators. These decorators mark their type and
provide metadata that tells Angular how to use them.
 The metadata for a component class associates it with a template that defines a view. A template
combines ordinary HTML with Angular directives and binding markup that allow Angular to
modify the HTML before rendering it for display.

T.E. Computer Engineering AY 2023-24 Semester-II Page 52


WTL Lab (2019 Course)

 The metadata for a service class provides the information Angular needs to make it available to
components through dependency injection (DI)
An application's components typically define many views, arranged hierarchically. Angular provides
the Router service to help you define navigation paths among views. The router provides sophisticated in-
browser navigational capabilities.

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web
applications. A Model View Controller pattern is made up of the following three parts −
 Model − It is the lowest level of the pattern responsible for maintaining data.
 View − It is responsible for displaying all or a portion of the data to the user.
 Controller − It is a software Code that controls the interactions between the Model and View.
MVC is popular because it isolates the application logic from the user interface layer and supports
separation of concerns. The controller receives all requests for the application and then works with the
model to prepare any data needed by the view. The view then uses the data prepared by the controller to
generate a final presentable response. The MVC abstraction can be graphically represented as follows.

The Model
The model is responsible for managing application data. It responds to the request from view and to the
instructions from controller to update itself.
The View
A presentation of data in a particular format, triggered by the controller's decision to present the data. They
are script-based template systems such as JSP, ASP, PHP and very easy to integrate with AJAX technology.
The Controller

T.E. Computer Engineering AY 2023-24 Semester-II Page 53


WTL Lab (2019 Course)

The controller responds to user input and performs interactions on the data model objects. The controller
receives input, validates it, and then performs business operations that modify the state of the data model.
AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS uses MVC
methodology.

Steps:

1. Download nodejs from the following website:


Download NodeJS 14.17.5 Windows 64-bit Installer https://nodejs.org/gl/blog/release/v1...
2. Run Command Prompt as Administrator and follow following steps:

T.E. Computer Engineering AY 2023-24 Semester-II Page 54


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 55


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 56


WTL Lab (2019 Course)

You can also follow the steps given in the following Video:
https://drive.google.com/file/d/1E8RVocFtKXUOOPrXZ4S6ajZoNzdlL00R/view?usp=sharing

Sample Output:

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 57


WTL Lab (2019 Course)

ASSIGNMENT NO: 10
Title of Assignment:BuildDesign and implement a business interface with necessary business logic for
any web application using Enterprise Java Beans (EJB).

Problem Statement: Design and implement a business interface with necessary business logic for any
web application
using EJB.
e.g., Design and implement the web application logic for deposit and withdraw amount
Transactions using EJB.

Theory:

Enterprise JavaBeans (EJB) is a specification for developing large-scale, distributed business applications
on the Java platform. The EJB architecture consists of three main components: enterprise beans (EJBs), the
EJB container, and the Java application server. EJBs run inside an EJB container, and the EJB container
runs inside a Java application server.
Enterprise Java Beans (EJB) is one of the several Java APIs for standard manufacture of enterprise
software. EJB is a server-side software element that summarizes business logic of an application.
Enterprise Java Beans web repository yields a runtime domain for web related software elements including
computer reliability, Java Servlet Lifecycle (JSL) management, transaction procedure and other web
services. The EJB enumeration is a subset of the Java EE enumeration.

The EJB enumeration aims to provide a standard way to implement the server-side business software
typically found in enterprise applications. Such machine code addresses the same types of problems, and
solutions to these problems are often repeatedly re-implemented by programmers. Enterprise Java Beans is
assumed to manage such common concerns as endurance, transactional probity and security in a standard
way that leaves programmers free to focus on the particular parts of the enterprise software at hand.

To run EJB application we need an application server (EJB Container) such as Jboss, Glassfish, Weblogic,
Websphere etc. It performs:
1. Life cycle management
2. Security
3. Transaction management
4. Object pooling

Architecture
The EJB architecture has two main layers, i.e., Application Server and EJB Container, based on which the
EJB architecture exist. The graphical representation of the EJB architecture is given below.

T.E. Computer Engineering AY 2023-24 Semester-II Page 58


WTL Lab (2019 Course)

In the above diagram, the logical representation of how EJBs are invoked and deployed by using
RMI(Remote Method Invocation) is defined. The containers of the EJB cannot be self-deployed. In order
to deploy the containers, it requires the Application server.
Application Server
In the EJB architecture, the Application server is the outermost layer that holds or contains the Container to
be deployed. The application layer plays an important role in executing the application developed using the
beans. It provides the necessary environment to execute those applications. Some most popular application
servers are Web-logic, Tomcat, JBoss, Web-sphere, Wildfly, and Glass-finish. The main tasks of the
application server are:
1. Manage Interfaces
2. Execution of the processes
3. Connecting to the database
4. Manage other resources.
Container
In EJB architecture, the Container is the second outermost layer. It is a very important layer for enterprise
beans that are contained in it. For the enterprise bean, the Container provides various supporting services,
which are as follows:
o It provides support for transactional services such as registering the objects, assign remote
interfaces, purge the instances.
o It provides support for monitoring the object's activities and coordinating distributed components.
o It provides support for security services.
o It provides support for the pooling of resources.
o It provides support for managing the Life-cycle of beans and their concurrency.
o It provides support to concentrate on business logic.
Beans
Java beans of the enterprise are installed in the Container in the same way as a Plain old java object (POJO)
is installed and registered to the Container. For developing secured, large scale and robust business
applications, beans provide business logic.

T.E. Computer Engineering AY 2023-24 Semester-II Page 59


WTL Lab (2019 Course)

Types of Enterprise Java Beans

There are three types of EJB:


1. Session Bean: Session bean contains business logic that can be invoked by local, remote or webservice
client. There are two types of session beans: (i) Stateful session bean and (ii) Stateless session bean.

(i) Stateful Session bean :


Stateful session bean performs business task with the help of a state. Stateful session bean can be used to
access various method calls by storing the information in an instance variable. Some of the applications
require information to be stored across separate method calls. In a shopping site, the items chosen by a
customer must be stored as data is an example of stateful session bean.

(ii) Stateless Session bean :


Stateless session bean implement business logic without having a persistent storage mechanism, such as a
state or database and can used shared data. Stateless session bean can be used in situations where
information is not required to used across call methods.

2. Message Driven Bean: Like Session Bean, it contains the business logic but it is invoked by passing
message.
3. Entity Bean: It summarizes the state that can be remained in the database. It is deprecated. Now, it is
replaced with JPA (Java Persistent API). There are two types of entity bean:

(i) Bean Managed Persistence :


In a bean managed persistence type of entity bean, the programmer has to write the code for database calls.
It persists across multiple sessions and multiple clients.

(ii) Container Managed Persistence :


Container managed persistence are enterprise bean that persists across database. In container managed
persistence the container take care of database calls.

When to use Enterprise Java Beans


1.Application needs Remote Access. In other words, it is distributed.
2.Application needs to be scalable. EJB applications supports load balancing, clustering and fail-over.
3.Application needs encapsulated business logic. EJB application is differentiated from demonstration and
persistent layer.

Advantages of Enterprise Java Beans

1. EJB repository yields system-level services to enterprise beans, the bean developer can focus on solving
business problems. Rather than the bean developer, the EJB repository is responsible for system-level
services such as transaction management and security authorization.

T.E. Computer Engineering AY 2023-24 Semester-II Page 60


WTL Lab (2019 Course)

2. The beans rather than the clients contain the application’s business logic, the client developer can focus
on the presentation of the client. The client developer does not have to code the pattern that execute
business rules or access databases. Due to this the clients are thinner which is a benefit that is particularly
important for clients that run on small devices.
3. Enterprise Java Beans are portable elements, the application assembler can build new applications from
the beans that already exists.

index.html:

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>Implement Bank Application using EJB </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form method ="post" action="transact">
<h1> Bank Application using EJB </h1>
Enter Amount:<input type ="text" name="t1" /><br/><br/>

<h3> Select Option </h3>


<input type="radio" name="transaction" value="deposit"> Deposit<br/>
<input type="radio" name="transaction" value="withdraw"> Withdraw<br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>

To create transact.java -- right click on -war file - select new servlet-- name: transact.java - Add

transact.java:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates

T.E. Computer Engineering AY 2023-24 Semester-II Page 61


WTL Lab (2019 Course)

* and open the template in the editor.


*/

import bankexamp.BankTransactLocal;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
*
* @author Rucha Pathari
*/
public class transact extends HttpServlet {

BankTransactLocalbankTransact = lookupBankTransactLocal();

/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */

String selectedType =request.getParameter("transaction");


int amount= Integer.parseInt(request.getParameter("t1"));

T.E. Computer Engineering AY 2023-24 Semester-II Page 62


WTL Lab (2019 Course)

if(selectedType.equals("deposit")){

bankTransact.deposit(amount);
}

if(selectedType.equals("withdraw")){
int amt=bankTransact.withdraw(amount);
out.println(amount+"successfully withdrawn. your balance is:"+amt);

}
}

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the
code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}

/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);

T.E. Computer Engineering AY 2023-24 Semester-II Page 63


WTL Lab (2019 Course)

/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>

private BankTransactLocallookupBankTransactLocal() {
try {
Context c = new InitialContext();
return (BankTransactLocal) c.lookup("java:global/Bank/Bank-
ejb/BankTransact!bankexamp.BankTransactLocal");
} catch (NamingException ne) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
throw new RuntimeException(ne);
}
}

To create BankTransact.java ---Right click on .ejb file  select new session Bean -EJBname: BankTransact
package: bankexamp stateful—select local - finish

BankTransact.java:

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package bankexamp;

import javax.ejb.Stateful;

/**
*
* @author Rucha Pathari
*/

T.E. Computer Engineering AY 2023-24 Semester-II Page 64


WTL Lab (2019 Course)

@Stateful
public class BankTransact implements BankTransactLocal {

//Let's consider default balance amount : 10000 rs

int balance=10000;

@Override
public void deposit(int amount) {
balance=balance+amount;
}

// Add business logic below. (Right-click in editor and choose


// "Insert Code > Add Business Method")

@Override
public int withdraw(int amount) {
balance=balance-amount;
return balance;
}

Run:

.ejb file deploy


.ejb file- clean and build  deploy
EE file( ) Run

T.E. Computer Engineering AY 2023-24 Semester-II Page 65


WTL Lab (2019 Course)

SAMPLE OUTPUT:

T.E. Computer Engineering AY 2023-24 Semester-II Page 66


WTL Lab (2019 Course)

T.E. Computer Engineering AY 2023-24 Semester-II Page 67


WTL Lab (2019 Course)

Conclusion:

T.E. Computer Engineering AY 2023-24 Semester-II Page 68

You might also like