0% found this document useful (0 votes)
12 views46 pages

WE April May 2023

The document provides an answer key for the IT3401 - Web Essentials exam, detailing key concepts such as web servers, URLs, HTML elements, CSS, JavaScript, PHP, servlets, and web protocols. It also covers client-side and server-side scripting, web browsers, and the principles of effective website design. Additionally, it includes examples of HTML form objects and CSS text effects.

Uploaded by

madhantamil2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views46 pages

WE April May 2023

The document provides an answer key for the IT3401 - Web Essentials exam, detailing key concepts such as web servers, URLs, HTML elements, CSS, JavaScript, PHP, servlets, and web protocols. It also covers client-side and server-side scripting, web browsers, and the principles of effective website design. Additionally, it includes examples of HTML form objects and CSS text effects.

Uploaded by

madhantamil2005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

V.S.B ENGINEERING COLLEGE, KARUR -639 111.

(An Autonomous Institution, Affiliated to Anna University, Chennai)

B.E/B.Tech.End Semenster Theory Examinations, April/May 2023.

IT3401- WEB ESSENTIALS - Answer Key

(Regulation 2021)

Part A

1. What is meant by web server?

Web server is a special type of server to which the web browser submit the request web page
which is desired by the client. For example: IIS, Apache.

Web server process the request of the user which it submits using the web browser. Sometimes the
web servers access the database system and fetch the required information required web page is compiled
and sent to the user in his/her web browser.

2. Define URL.

 The Uniform Resource Locator (URL) is unique address for the file that has to be accessed
over the internet.

 When we want to access some website we enter its URL in the address bar of the web browser.

 For example if we want to access www.google.com then we must specify its URL in the
address bar.

http://www.google.com,

http – Protocol name, www-Host name, google-Server name, com- Domain name.

3. Write about any two HTML elements.

<title> - This element is used to specify the title of the web page. This element is defined within the
<head>

<p> - This element is generally defined in the <body> part. It is used to create a paragraph.

<body> - This element is specify the main content which is to be display the web page.

4. Mention the need for CSS.

The casecading style sheet allows separation between the information contained in a document and
its presentation. Hence any change in presentation can be made without disturbing the information of the
document. The casecading style sheet allows the developer to give the consistent appearance to all
elements of the web page.
5. What is a JavaScript Statement? Give an example.

The assignment statement in JavaScript is very much similar to C. Every statement end with
semicolon and with in <script> </script> tag.

For example,

<script>

Sum=sum+10;

Sum+=10;

</script>

6. List any four methods of date object.

getTime() – It returns the number of milliseconds. This value is the difference between the current time and
the time value from 1st January 1970.

getDate() – Returns the current date based on the computers local time.

getDay() – Returns the current day. The day number is from 0 to 6 i.e. from Sunday to Saturday.

getHours() – Returns the hour value ranging from 0 to 23, based on local time.

7. What does PHP stand for?

The PHP stands for PHP-Hypertext Preprocessor. PHP is a server side scripting language. It is
mainly used for form handling and database access.

8. Differentiate echo() and print() function.

echo() print()

echo can pass multiple string separated as (,) print doesn’t pass multiple argument

echo does not return any value print always return 1

It is faster than print It is slower the echo

9. What are the uses of Servlets?

 Servlets can process and store the data submitted by an HTML form.

 Servlets are useful for providing the dynamic contents. For example retrieving and
updating the databases.

 Servlets can be used in the cookies and session tracking.


10. What is a driver manager?

The driver manager is a class that connects the java application or servlet to the JDBC driver. The
driver manager also attempts to open a connection with the desired database using the method
DriverManager.getConnection().

Part B

11. a) i) Explain the various Web Protocols.

TCP protocol:

It is a connection oriented protocol and offers end to end packet delivery. It acts as back bone of the
connection.

Features:

· Stream data transfer

· Reliability

· Full duplex operation

· It transmit the bytes not acknowledged within specific time period.

Services:

· Stream delivery service

· Sending and receiving buffers

· Bytes and segments

· Full duplex services

· Connection oriented services

IP Protocol:

IP Protocol is a connectionless and unreliable protocol. It ensures no guarantee of successfully transmission


of data. In order to make it reliable, it must pair with TCP at transport layer like TCP/IP. The length of
datagram is available.

The datagram is divided into 2 parts

 Header

 Data Header

HTTP (Hyper Text Transfer Protocol)

This protocol is used to transfer hypertexts over the internet and it is defined by the www(world
wide web) for information transfer. This protocol defines how the information needs to be formatted and
transmitted. And, it also defines the various actions the web browsers should take in response to the calls
made to access a particular web page. Whenever a user opens their web browser, the user will indirectly
use HTTP as this is the protocol that is being used to share text, images, and other multimedia files on the
World Wide Web.

FTP (File Transfer Protocol)

This protocol is used for transferring files from one system to the other. This works on a client-
server model. When a machine requests for file transfer from another machine, the FTO sets up a
connection between the two and authenticates each other using their ID and Password. And, the desired file
transfer takes place between the machines.

SMTP (Simple Mail Transfer Protocol)

These protocols are important for sending and distributing outgoing emails. This protocol uses the
header of the mail to get the email id of the receiver and enters the mail into the queue of outgoing mail.
And as soon as it delivers the mail to the receiving email id, it removes the email from the outgoing list.
The message or the electronic mail may consider the text, video, image, etc. It helps in setting up some
communication server rules.

ii) Write short notes on Web browsers and Web servers.

Web Browser

A software application used to access information on the World Wide Web is called a Web
Browser. When a user requests some information, the web browser fetches the data from a web server and
then displays the webpage on the user’s screen.

It is also important to know in detail about what a web browser is for candidates preparing for
Government exams. This is because Computer Knowledge is a common topic for many competitive exams
and questions based on web browsers may be asked.

Functions of Web Browser

Our dependency on the Internet has massively increased. Stated below are functions of web browsers and
how are they useful:

 The main function is to retrieve information from the World Wide Web and making it available for
users

 Visiting any website can be done using a web browser. When a URL is entered in a browser, the web
server takes us to that website

 To run Java applets and flash content, plugins are available on the web browser

 It makes Internet surfing easy as once we reach a website we can easily check the hyperlinks and get
more and more useful data online
 Browsers user internal cache which gets stored and the user can open the same webpage time and
again without losing extra data

 Multiple webpages can be opened at the same time on a web browser

 Options like back, forward, reload, stop reload, home, etc. are available on these web browsers, which
make using them easy and convenient

Types

 Mosaic

 Netscape Navigator

 Internet Explorer

 Firefox

 Google Chrome

Web server

A web server is a computer system that hosts websites. It stores and delivers web pages to users
who request them through the internet. Web servers are the foundation of the modern web, providing the
infrastructure for websites to exist and function. They are responsible for delivering web content to users,
and for providing the necessary security and performance features to ensure a safe and reliable experience.

A web server is responsible for hosting websites and providing them with the necessary resources
to function. It stores and delivers web pages to users who request them through the internet. Web servers
are responsible for delivering web content to users, and for providing the necessary security and
performance features to ensure a safe and reliable experience.

Functions of the web server

 Stores and secures website data:

In web hosting services, a web server stores all website data and secures it from unauthorized users when it
is properly configured.

 Provides web database access:

A web server’s responsibility is to provide access to websites that are hosted. Web hosting service
providers own some web servers that are used in variable ways to provide different web hosting services,
such as backend database servers.

 Serve the end user requests:

Web servers accept requests from different users connected over the internet and serve them accordingly.

 Bandwidth controlling to regulate network traffic:


It is a feature available in web server to minimize excess network traffic. Web Hosts can set bandwidth
values to regulate the rate of data transmission over the internet. This feature avoids the down time caused
by high web traffic.

 Virtual hosting:

Virtual Hosting is a type of web hosting service in which a web server is used to host other software based
virtual web-servers web sites, data, applications and other services. Virtualized Web servers do possess this
feature to provide virtual hosting.

 Server side web scripting:

This feature of web server enables the user to create dynamic web pages. The popular server side scripting
languages include Perl, Ruby, Python, PHPandASP etc.

b) i) Explain in detail the working principle of the website.

Website Purpose

Your website needs to accommodate the needs of the user. Having a simple clear intention on all
pages will help the user interact with what you have to offer. What is the purpose of your website? Are you
imparting practical information like a ‘How to guide’? Is it an entertainment website like sports coverage
or are you selling a product to the user? There are many different purposes that websites may have but
there are core purposes common to all websites;

 Describing Expertise
 Building Your Reputation
 Generating Leads
 Sales and After Care

Simplicity

Simplicity is the best way to go when considering the user experience and the usability of your
website. Below are ways to achieve simplicity through design.

 Color
 Type
 Imaginary

Navigation

Navigation is the way finding system used on websites where visitors interact and find what they
are looking for. Website navigation is key to retaining visitors. If the website navigation is confusing
visitors will give up and find what they need elsewhere. Keeping navigation simple, intuitive and
consistent on every page is key.
F-Shaped Pattern Reading

The F- based pattern is the most common way visitors scan text on a website. Eye-tracking studies
have found that most of what people see is in the top and left areas of the screen. The F shaped layout
mimics our natural pattern of reading in the West (left to right and top to bottom). An effectively designed
website will work with a reader’s natural pattern of scanning the page.

Visual Hierarchy

Visual hierarchy is the arrangement of elements in order of importance. This is done either by size,
colour, imagery, contrast, typography, whitespace, texture and style. One of the most important functions
of visual hierarchy is to establish a focal point; this shows visitors where the most important information is.

Content

An effective website has both great design and great content. Using compelling language great
content can attract and influence visitors by converting them into customers.

Grid Based Layout

help to structure your design and keep your content organised. The grid helps to align elements on
the page and keep it clean. The grid-based layout arranges content into a clean rigid grid structure with
columns, sections that line up and feel balanced and impose order and results in an aesthetically pleasing
website.

Load Time

Waiting for a website to load will lose visitors. Nearly half of web visitors expect a site to load in 2
seconds or less and they will potentially leave a site that isn’t loaded within 3 seconds. Optimising image
sizes will help load your site faster.

Mobile Friendly

More people are using their phones or other devices to browse the web. It is important to consider
building your website with a responsive layout where your website can adjust to different screens.

ii) Describe about Client-side Scripting and Server-side Scripting.

Client-side scripting

Web browsers execute client-side scripting. It is used when browsers have all code. Source code is
used to transfer from webserver to user’s computer over the internet and run directly on browsers. It is also
used for validations and functionality for user events.

It allows for more interactivity. It usually performs several actions without going to the user. It
cannot be basically used to connect to databases on a web server. These scripts cannot access the file
system that resides in the web browser. Pages are altered on basis of the user’s choice. It can also be used
to create “cookies” that store data on the user’s computer.
Server-side scripting

Web servers are used to execute server-side scripting. They are basically used to create dynamic
pages. It can also access the file system residing at the webserver. A server-side environment that runs on a
scripting language is a web server.

Scripts can be written in any of a number of server-side scripting languages available. It is used to
retrieve and generate content for dynamic pages. It is used to require to download plugins. In this load
times are generally faster than client-side scripting. When you need to store and retrieve information a
database will be used to contain data. It can use huge resources of the server. It reduces client-side
computation overhead. The server sends pages to the request of the user/client.

Client-side scripting Server-side scripting

Source code is not visible to the user because its


Source code is visible to the user.
output of server-sideside is an HTML page.

Its main function is to provide the requested Its primary function is to manipulate and provide access
output to the end user. to the respective database as per the request.

It usually depends on the browser and its In this any server-side technology can be used and it
version. does not depend on the client.

It runs on the user’s computer. It runs on the webserver.

There are many advantages linked with this


The primary advantage is its ability to highly customize,
like faster. response times, a more interactive
response requirements, access rights based on user.
application.

It does not provide security for data. It provides more security for data.

It is a technique that uses scripts on the webserver to


It is a technique used in web development in
produce a response that is customized for each client’s
which scripts run on the client’s browser.
request.

HTML, CSS, and javascript are used. PHP, Python, Java, Ruby are used.
Client-side scripting Server-side scripting

No need of interaction with the server. It is all about interacting with the servers.

It reduces load on processing unit of the server. It surge the processing load on the server.

12. a) Demonstrate any five HTML form objects for a typical online user registration process.

<html>

<head>

<title>

Registration Page

</title>

</head>

<body>

<br>

<form>

<label> Firstname </label>

<input type="text" name="firstname" > <br> <br>

<label> Middlename: </label>

<input type="text" name="middlename" > <br> <br>

<label> Lastname: </label>

<input type="text" name="lastname" > <br> <br>

<label>

Course :

</label>

<select>

<option value="Course">Course</option>
<option value="BCA">BCA</option>

<option value="BBA">BBA</option>

<option value="B.Tech">B.Tech</option>

<option value="MBA">MBA</option>

<option value="MCA">MCA</option>

<option value="M.Tech">M.Tech</option>

</select>

<br>

<br>

<label>

Gender :

</label><br>

<input type="radio" name="male"/> Male <br>

<input type="radio" name="female"/> Female <br>

<input type="radio" name="other"/> Other

<br>

<br>

<label>

Phone :

</label>

<input type="text" name="phone" size="10"/> <br> <br>

Address

<br>

<textarea value="address">

</textarea>

<br> <br>

Email:

<input type="email" id="email" name="email"/> <br>


<br>

<input type="button" value="Submit">

</form>

</body>

</html>

b) i) Explain the text effects in CSS illustrative example.

CSS Text Overflow

The CSS text-overflow property specifies how overflowed content that is not displayed should be signaled
to the user.

It can be clipped:
This is some long text that

or it can be rendered as an ellipsis (...):


This is some long text t…
that

The CSS code is as follows:

Example

p.test1 {
white-space: nowrap;
width: 200px;
border: 1px solid #000000;
overflow: hidden;
text-overflow: clip;
}

p.test2 {
white-space: nowrap;
width: 200px;
border: 1px solid #000000;
overflow: hidden;
text-overflow: ellipsis;
}

CSS Word Wrapping

The CSS word-wrap property allows long words to be able to be broken and wrap onto the next line.
If a word is too long to fit within an area, it expands outside:

This paragraph contains a


very long word:
thisisaveryveryveryveryve
ryverylongword. The long
word will break and wrap
to the next line.

The word-wrap property allows you to force the text to wrap - even if it means splitting it in the middle of
a word:

This paragraph contains


a very long word:
thisisaveryveryveryvery
veryverylongword. The
long word will break and
wrap to the next line.

Example

p{
word-wrap: break-word;
}

CSS Word Breaking

The CSS word-break property specifies line breaking rules.

This paragraph
contains some text.
This line will-break-
at-hyphens.

This paragraph
contains some text.
The lines will break at
any character.

Example

p.test1 {
word-break: keep-all;
}
p.test2 {
word-break: break-all;
}

CSS Writing Mode

The CSS writing-mode property specifies whether lines of text are laid out horizontally or vertically.

Some text with a span element with a vertical-rl writing-mode.

The following example shows some different writing modes:

Example

p.test1 {
writing-mode: horizontal-tb;
}

span.test2 {
writing-mode: vertical-rl;
}

p.test2 {
writing-mode: vertical-rl;
}

ii) Create a HTML page which uses CSS to display a paragraph element that has 2px black border
and a green online with a width of 10px.

<!DOCTYPE html>

<html>

<head>

<style>

p{

margin:30px;

width:180px;

border:2px soild #00000;

outline:10px soild #00FF00;

outline-offset:15px;

</style>
</head>

<body>

<h3> outline property</h3>

<p>

There was once a Merchant who had three daughters. the youngest of whom was so beautiful that
everybody called her Beauty. This made the two eldestvery jealous; and as they were spiteful and bad-
tempered by nature. Instead of loving their youngsister they felt nothing but envy and hated towards her.

</p>

</body>

</html>

output

There was once a Merchant who


had three daughters. the
youngest of whom was so
beautiful that everybody called
her Beauty. This made the two
eldest very jealous; and as they
were spiteful and bad-tempered
by nature. Instead of loving their
young sister they felt nothing
but envy and hated towards her.

13. a) i) Write a javascript program to print prime numbers from 1 to 100.

<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

function primeNumber(from, to)

var flag=false;
for(i= from; i <= to; i++){

for 1-21<ic j++){

if(i % j==0){

flag =false:

break;

else

flag=true:

if(flag)

document.write(+1);}}}

</script>

</head>

<body>

<h4> Prime Numbers from 1 to 100 are...</b>

<script type="text/javascript">

primeNumber(1, 100)

</script>

</body>

</html>

Output:

Prime Numbers from 1 to 100 are...

2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97.

ii) Explain various Operators in javascript detail.

JavaScript Operators:

There are various operators supported by JavaScript.

 JS Arithmetic Operators

 JS Assignment Operators
 JS Comparison Operators

 JS Logical Operators

 JS Ternary Operators

 JS Bitwise Operators

JavaScript Arithmetic Operators:

These are the operators that operate upon the numerical values and return a numerical value.

 Addition (+): Addition ‘+’ operator performs addition on two operands. This ‘+’ operator can also
be used to concatenate (add) strings.

Y = 5 + 5 gives Y = 10

 Subtraction (-): Subtraction ‘-‘ operator performs subtraction on two operands.

Y = 5 - 3 gives Y = 2

 Multiplication (*): Multiplication ‘*’ operator performs multiplication on two operands.

Y = 5 * 5 gives Y = 25

 Division (/): Division ‘/’ operator performs division on two operands (divide the numerator by the
denominator).

Y = 5 / 5 gives Y = 1

 Modulus (%): Modulus ‘%’ operator gives a remainder of an integer division.

A % B means remainder (A/B)

Y = 5 % 4 gives Y = 1

 Exponentiation (**): Exponentiation ‘**’ operator give the power of the first operator raised to
the second operator.

Y = 5 ** 3 gives Y = 125

 Increment(++): Increment ‘+ +’ operator increases an integer value by one.

let A = 10 and Y = A + + then A = 11, Y=10

 Decrement (- -): Decrement ‘- -‘ operator decreases an integer value by one.

let A = 10 and Y = A - - then A = 9, Y=10


Example:

let x = 5;

let y = 3;

// addition

console.log('x + y = ', x + y);

// subtraction

console.log('x - y = ', x - y);

// multiplication

console.log('x * y = ', x * y);

// division

console.log('x / y = ', x / y);

// remainder

console.log('x % y = ', x % y);

// increment

console.log('++x = ', ++x);

console.log('x++ = ', x++);

console.log('x = ', x);

// decrement

console.log('--x = ', --x);

console.log('x-- = ', x--);

console.log('x = ', x);

//exponentiation

console.log('x ** y =', x ** y);


b) i) Write a javascript program to remove duplicate items from an array ignoring case sensitivity.

<html>

<body>

<script>

function getUnique(array)

var uniqueArray=[];

for(i=0;i<array.length;i++)

if(uniqueArray.indexOf(array[i]===-1)

uniqueArray.push(array[i]);

return uniqueArray;

var name=[“AAA”,”BBB”,”CCC”,”DDD”];

var uniqueNames=getUnique(names);

console.log(uniqueNames);

</script>

</body>

</html>

ii) How do you use Exceptions in javascript?

Throw, and Try...Catch...Finally

 The try statement defines a code block to run (to try).


 The catch statement defines a code block to handle any error.
 The finally statement defines a code block to run regardless of the result.
 The throw statement defines a custom error.
Example

<p id="demo"></p>

<script>

try {

adddlert("Welcome guest!");

catch(err) {

document.getElementById("demo").innerHTML = err.message;

</script>

JavaScript try and catch

 The try statement allows you to define a block of code to be tested for errors while it is being
executed.
 The catch statement allows you to define a block of code to be executed, if an error occurs in the try
block.
 The JavaScript statements try and catch come in pairs:

Syntax

try {

Block of code to try

catch(err) {

Block of code to handle errors

JavaScript Throws Errors

 When an error occurs, JavaScript will normally stop and generate an error message.
 The technical term for this is: JavaScript will throw an exception (throw an error).
 JavaScript will actually create an Error object with two properties: name and message.

The throw Statement

 The throw statement allows you to create a custom error.


 Technically you can throw an exception (throw an error).
 The exception can be a JavaScript String, a Number, a Boolean or an Object:

The finally Statement

The finally statement lets you execute code, after try and catch, regardless of the result:

Syntax

try {

Block of code to try

catch(err) {

Block of code to handle errors

finally {

Block of code to be executed regardless of the try / catch result

Example

function myFunction() {

const message = document.getElementById("p01");

message.innerHTML = "";

let x = document.getElementById("demo").value;

try {

if(x.trim() == "") throw "is empty";

if(isNaN(x)) throw "is not a number";

x = Number(x);

if(x > 10) throw "is too high";

if(x < 5) throw "is too low";

catch(err) {

message.innerHTML = "Error: " + err + ".";

}
finally {

document.getElementById("demo").value = "";

14. a) i) Create an HTML form to enter one number .Write PHP code to display the message about
whether the number is odd or even.

<html>

<body>

<form method="post" action="">

<label>Enter the Number</label>

<input type="text" name="num">

<input type="submit" name="sub" value="calculate">

</form>

</body>

</html>

<?php

if(isset($_POST['sub']))

$NUM=$_POST['num'];

if($NUM%2==0)

echo "<h2>".$NUM. " is even number </h2>";

else

echo "<h2>".$NUM. " is Odd number </h2>";

}
?>

ii) Explain data types in PHP.

Data Types define the type of data a variable can store. The data types are:

 Boolean

 Integer

 Double

 String

Integer type

 For displaying the integer value.

 It is similar to long type in C.

 The size is 32 bit.

Double Type

 For displaying the real values the double data type is used.

 It includes the numbers with decimal point, exponentiation or both. The exponent can be
represented by E ore followed by integer literal

 It is not compulsory to have digits before and after the decimal point. For instance 123 or
123. is allowed in PHP.

String Type

 There is no character data type in PHP. If the character has to be represented then it is
represented using the string type itself, but in this case the string is considered to be of
length l. The string literals can be defined using either single or double quotes.

 In single quotes the escape sequence or the values of the literals can not be recognized by
PHP but in double quotes the escape sequences can be recognized. For example

‘The total marks are =$marks’

will be typed as it is but

“The total macks $marks”

will display the value of $marks variable

Boolean Type

 There are only two types of values that can be defined by the Boolean type and those are
TRUE and FALSE
 If Boolean values are used in context of integer type variable then TRUE will be
interpreted as 1 and FALSE will be interpreted as 0.

 If Boolean values are used in context of double type then the FALSE will be interpreted as
0.0.

b) i) Explain various types of arrays used in PHP.

PHP Arrays

PHP array is an ordered map (contains value on the basis of key). It is used to hold multiple values
of similar type in a single variable.

Advantage of PHP Array

 Less Code: We don't need to define multiple variables.


 Easy to traverse: By the help of single loop, we can traverse all the elements of an array.
 Sorting: We can sort the elements of array.

PHP Array Types

There are 3 types of array in PHP.

 Indexed Array
 Associative Array
 Multidimensional Array

PHP Indexed Array

PHP index is represented by number which starts from 0. We can store number, string and object
in the PHP array. All PHP array elements are assigned to an index number by default.

There are two ways to define indexed array:

1st way:

$season=array("summer","winter","spring","autumn");

2nd way:

$season[0]="summer";

$season[1]="winter";

$season[2]="spring";

$season[3]="autumn";

Example

File: array1.php

<?php
$season=array("summer","winter","spring","autumn");

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

?>

Output:

Season are: summer, winter, spring and autumn

File: array2.php

<?php

$season[0]="summer";

$season[1]="winter";

$season[2]="spring";

$season[3]="autumn";

echo "Season are: $season[0], $season[1], $season[2] and $season[3]";

?>

Output:

Season are: summer, winter, spring and autumn

PHP Associative Array

We can associate name with each array elements in PHP using => symbol.

There are two ways to define associative array:

1st way:

$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

2nd way:

$salary["Sonoo"]="350000";

$salary["John"]="450000";

$salary["Kartik"]="200000";

Example

File: arrayassociative1.php

<?php
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000");

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";

echo "John salary: ".$salary["John"]."<br/>";

echo "Kartik salary: ".$salary["Kartik"]."<br/>";

?>

Output:

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000

File: arrayassociative2.php

<?php

$salary["Sonoo"]="350000";

$salary["John"]="450000";

$salary["Kartik"]="200000";

echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";

echo "John salary: ".$salary["John"]."<br/>";

echo "Kartik salary: ".$salary["Kartik"]."<br/>";

?>

Output:

Sonoo salary: 350000

John salary: 450000

Kartik salary: 200000

PHP Multidimensional Array

PHP multidimensional array is also known as array of arrays. It allows you to store tabular data in
an array. PHP multidimensional array can be represented in the form of matrix which is represented by row
* column.

Definition

$emp = array
(

array(1,"sonoo",400000),

array(2,"john",500000),

array(3,"rahul",300000)

);

PHP Multidimensional Array Example

Let's see a simple example of PHP multidimensional array to display following tabular data. In this
example, we are displaying 3 rows and 3 columns.

Id Name Salary

1 sonoo 400000

2 john 500000

3 rahul 300000

File: multiarray.php

<?php

$emp = array

array(1,"sonoo",400000),

array(2,"john",500000),

array(3,"rahul",300000)

);

for ($row = 0; $row < 3; $row++) {

for ($col = 0; $col < 3; $col++) {

echo $emp[$row][$col]." ";

echo "<br/>";

?>

Output:
Play

Next

Unmute

Current TimeÂ

0:00

DurationÂ

18:10

Fullscreen

Backward Skip 10s

Play Video

Forward Skip 10s

Output:

1 sonoo 400000

2 john 500000

3 rahul 300000

ii) Explain about File read and write operations in PHP.

There are 3 simple steps to do file operation :

 Open a file in the proper mode.


 Read/write contents in file.
 Close the file.

Modes of opening a file in PHP

There are several ways to open a file:

w: It opens the file in write-only mode. If the file is not present, a file is created. If the file exists, then the
contents of the file are erased.

r: It opens the file in read-only mode.

a: It opens the file in append mode i.e. the contents are inserted at the end of the file.
w+: It opens the file in read and write mode. If the file is not present, a file is created. If the file exists, then
the contents of the file are erased.

r+: It opens the file in read/write mode.

a+: It opens the file in read/write mode. The contents are inserted at the end of the file.

Opening a file in PHP

The function to open a file:

fopen(filename,mode);

Example:-

fopen("myfile.txt",'w');

Reading a file in PHP

The fread() function is used to read the contents of a file.

Example:

<?php

$file = "myfile.txt";

//opening a file in reading mode

$h = fopen($file, 'r');

//reading file upto file length and storing it in a variable "fcontents"

$fContents = fread($h, filesize($file));

//closing file

fclose($h);

//displaying the content

echo $fContents;

?>

Ouput:

Welcome to codespeedy.This is a example of file read.

Writing a file in PHP

The fwrite() function is used to write contents to a file.

<?php
$file = "myfile.txt";

//opening a file in writing mode

$h = fopen($file, 'a');

//adding new contents to file

$ncontents = "This line added to the file.";

fwrite($h, $ncontents);

//closing file

fclose($h);

//opening a file in reading mode

$h = fopen($file, 'r');

//reading file to check whether content is added or not

$fContents = fread($h, filesize($file));

//closing file

fclose($h);

//displaying the content

echo $fContents;

?>

Output:

Welcome to codespeedy.This is a example of file read. This line added to the file.

Closing a file in PHP

The following function is used to close an opened file:

fclose(filename);

Example:-

fclose($file);

This is how we can perform read and write operations on a file.

15. a) i) Discuss the advantages and disadvantages of Servlet.

Advantages of servlet:
 Servlets are multithreaded. That is whenever the servlet container receives a request for the
execution of a servlet, the servlet container loads the servlet in its main memory., and assigns a
thread of this servlet for processing this client’s requests.
 If more clients send the request for the same servlet, the servlet container does not create new
servlet instances. Instead, it creates a new thread of the same servlet instance.
 And allocates these thread instances to the different client requests. This makes the overall
processing faster and reduces the memory demands on the servlet container/Web Server.
 Because servlets execute inside a controlled environment(Container) they are usually quite stable
and simple to deploy.

 As Servlets are specific java programs, they inherit all the good features of the java programming
language, such as object orientation, inherit security, network capabilities, integration with other
Java enterprise technologies, etc.
 It provides better performance as it is capable to create the thread for each request instead of the
process.
 Because the use of the Java language is easily portable.
 It is robust in nature as JVM manages the servlet completely and thus we do not need to worry
about the memory leak, garbage collection and etc.
 Java makes the servlet more secure.

Disadvantages of Servlet:

 The dynamic construction of HTML documents is still low-level, that is fragments of textual
HTML are written to an output stream, eventually forming a complete HTML document.
 There are no compile-time guarantees that the result is valid according to some schema or even
well-formed. For non-trivial programs, it can be more difficult to avoid this kind of bug.
 It is difficult to separate the concerns of the programmers and HTML designers.
 The control flow through a session involving different servlets can be difficult to follow for the
programmer. The connection between the code that generates an HTML document with a form and
the code that subsequently handles the form field data is often not obvious.
 Moreover, the way the session state is managed through the set Attribute/gets attribute mechanism
is vulnerable Since the session control flow is not always clear the programmer must be careful
about assuming that certain attributes have or have not been set in an earlier interaction.
 Also, we have seen it is necessary to downcast all results from getAttribute. Which is an additional
source of errors that are not detected statically.

ii) Write the code for converting currencies into US dollars.

Step 1: We will write the simple HTML document, which will create the interface. The user can select the
type of currencies and will enter the value.

<html>

<body>
<formname=”form1” method=”post” action=http://localhost/example/servlets/servlet/DollarDemo>

Select the type of Currency:

<Select name=”currency”>

<option value=”Euro”>Euro</option>

<option value=”Pound”>Pound</option>

<option value=”Rupees”>Rupees</option>

</select>

<br><br/>

Enter the value:

<input type=”text” name=”currencyVal” value=””/>

</form>

</body>

</html>

Step 2: The java servlet for converting the currency value to dollar is as given below.

import java.io.*;

import java.net.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class DollarDemo extends HttpServlet{

pubic void doPost(HttpServletReques req,HttpServletResponse res)throws


ServletException.IOException.NullPointerException

res.setContentType(“text/html”);

PrintWriter out=res.getWriter();

String c=req.getParameter(“currency”);

double RupeeValue,EuroValue,PoundValue;

double DollarValue=0;

String vaue=req.getParameter(“currencyVal”);
if(c.equals(“Rupees”))

RupeeValue=Double.parseDouble(value);

DollarValue=RupeeValue/61;

if(c.equals(“Euro”))

EuroValue=Double.parseDouble(value);

DollarValue=EuroValue/0.77;

if(c.equals(“Pound”))

PoundValue=Double.parseDouble(value);

DollarValue=PoudValue*1.62;

out.println(“<p> The dollar value=”+DollarValue+”</p>);

out.close();

Output:
b) i) How do you create cookies and retrieve its value?

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

STEP 1: Creation of cookies

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object

response.addCookie(ck);//adding cookie in the response

STEP 2: Reading cookies

Cookie ck[]=request.getCookies();

for(int i=0;i<ck.length;i++){

out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie

Example:

In this we are storing the name of the user in the cookie object and accessing it in another servlet. As we
know well that session corresponds to the particular user. So if you access it from too many browsers with
different values, you will get the different value.

HTML Program

<html>

<body>

<form action="servlet1" method="post">

Name:<input type="text" name="userName"/><br/>


<input type="submit" value="go"/>

</form>

</body>

</html>

Servlet program 1

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class FirstServlet extends HttpServlet

public void doPost(HttpServletRequest request, HttpServletResponse respon)

try

response.setContentType("text/html");

PrintWriter out = response.getWriter();

String n=request.getParameter("userName");

out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object

response.addCookie(ck);//adding cookie in the response

//creating submit button

out.print("<form action='servlet2'>");

out.print("<input type='submit' value='go'>");

out.print("</form>");

out.close();

catch(Exception e){

System.out.println(e);
}

Servlet program 2

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse respon)

try

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();

out.print("Hello "+ck[0].getValue());

out.close();

}catch(Exception e){System.out.println(e);}

ii) Expalin the life cycle of servlets with suitable example.

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
 Servlet class is loaded.

 Servlet instance is created.

 init method is invoked.

 service method is invoked.

 destroy method is invoked.

Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded when the first request
for the servlet is received by the web container.

Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.

init method is invoked

The web container calls the init method only once after creating the servlet instance. The init method is used to
initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is
given below:

public void init(ServletConfig config) throws ServletException

Service method is invoked

The web container calls the service method each time when request for the servlet is received. If servlet is
not initialized, it follows the first three steps as described above then calls the service method. If servlet is
initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service
method of the Servlet interface is given below:

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

Destroy method is invoked

The web container calls the destroy method before removing the servlet instance from the service. It gives
the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the
destroy method of the Servlet interface is given below:

public void destroy()

Example:

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class AdvanceJavaConcepts extends HttpServlet

private String output;

public void init() throws ServletException

output = "Advance Java Concepts";

// Requesting and printing the output

public void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException,


IOException

resp.setContentType("text/html");

PrintWriter out = resp.getWriter();

out.println(output);

}
public void destroy()

System.out.println("Over");

PART C

16. a) Explain the steps involved to create JDBC connectivity. Create an application for online
shopping with JDBC Connectivity. List the advantages of JDBC.

Steps involved to create JDBC Connectivity

Step 1: Import java.sql.* package in the JDBC program

Following line can be included in your JDBC program at the beginning.

import.java.sql.*;

Step 2: Load JDBC Driver.

The JDBC driver for MYSQL can be loaded using following statement.

Class.forName(“com.mysql.jdbc.Driver”);

Step 3: Get connection using the Driver Manager

Conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/my_database”,”root”,”password”);

Step 4: Create statement

Stmt=conn.createStatment();

Step 5: Execute Query

String sql=”Select rollno,studname from my_table”;

ResultSet rs=stmt.executeQuery(sql);

Step 6: Display the result.

Online shopping application using JDBC Connectivity

Defining servlet for adding product in the database

import java.io.File;

import java.io.IOException;

import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.connection.DatabaseConnection;

@WebServlet("/AddProducts")

public class AddProducts extends HttpServlet {

//Path where all the images are stored

private final String UPLOAD_DIRECTORY = "ENTER_YOUR_DIRECTORY_PATH";

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

//Creating session in java online shopping project

HttpSession session = request.getSession();

if (ServletFileUpload.isMultipartContent(request)) {

try {

//Taking all image requests

List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

String imageName = null;

String productName = null;

String productQuantity = null;

String productPrice = null;


String descrip = null;

String mrpPrice = null;

String status = null;

String category = null;

//SALTCHARS to generate unique code for product

String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

StringBuilder salt = new StringBuilder();

Random rnd = new Random();

while (salt.length() < 3) { // length of the random string.

int index = (int) (rnd.nextFloat() * SALTCHARS.length());

salt.append(SALTCHARS.charAt(index));

String code = salt.toString();

for (FileItem item : multiparts) {

if (!item.isFormField()) {

//Getting image name

imageName = new File(item.getName()).getName();

//Storing in the specified directory

item.write(new File(UPLOAD_DIRECTORY + File.separator + imageName));

//Retrieving all information from frontend of online shopping system

FileItem pName = (FileItem) multiparts.get(0);

productName = pName.getString();

FileItem price = (FileItem) multiparts.get(1);

productPrice = price.getString();

FileItem description = (FileItem) multiparts.get(2);

descrip = description.getString();

FileItem mprice = (FileItem) multiparts.get(3);

mrpPrice = mprice.getString();
FileItem fstatus = (FileItem) multiparts.get(4);

status = fstatus.getString();

FileItem pcategory = (FileItem) multiparts.get(5);

category = pcategory.getString();

try {

int id = 0;

String imagePath = UPLOAD_DIRECTORY + imageName;

//Querying to insert product in the table

int i = DatabaseConnection.insertUpdateFromSqlQuery("insert into


tblproduct(id,active,code,description,image,image_name,name,price,mrp_price,product_category)
values('" + id + "','" + status + "','" + code + "','" + descrip + "','" + imagePath + "','" + imageName + "','" +
productName + "','" + productPrice + "','" + mrpPrice + "','" + category + "')");

//If product inserted successfully in the database

if (i > 0) {

String success = "Product added successfully.";

//Adding method in session.

session.setAttribute("message", success);

//Response send to the admin-add-product.jsp

response.sendRedirect("admin-add-product.jsp");

} catch (Exception e) {

e.printStackTrace();

} catch (Exception ex) {

//If any error occurred while uploading product image

request.setAttribute("message", "File Upload Failed due to " + ex);

}
} else {

request.setAttribute("message", "Sorry this Servlet only handles file upload request");

Defining add to cart servlet

import java.io.IOException;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import com.connection.DatabaseConnection;

@WebServlet("/AddToCart")

public class AddToCart extends HttpServlet {

@Override

protected void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

int id = 0;

//Getting all the parameters from the user

int productId = Integer.parseInt(request.getParameter("productId"));

String price = request.getParameter("price");

String mrp_price = request.getParameter("mrp_price");

HttpSession hs = request.getSession();

try {

//If user session is null user have to re-login

if ((String) hs.getAttribute("name") == null) {


response.sendRedirect("customer-login.jsp");

//Inserting cart details to the database

} else {

int customerId = (int) hs.getAttribute("id");

//Querying to the database.

int addToCart = DatabaseConnection.insertUpdateFromSqlQuery("insert into tblcart values('" + id + "','" +


price + "',1,'" + price + "','" + customerId + "','" + productId + "','" + mrp_price + "')");

if (addToCart > 0) {

response.sendRedirect("index.jsp");

} catch (Exception e) {

e.printStackTrace();

Advantages

JDBC helps the client to store and retrieve the databases.

JDBC allows the client to update the databases.

b) Design a webpage with a textbox where the user can enter a four digit number and a button
“validate”. Validate the entered number for the following using javascript. No zero as the first digit
Entered number must be in ascending order of digits(EX:1234,5678…)

<!DOCTYPE html>

<html>

<head>

<title>Validation</title>

<script type=”text/javascript”>

function my_fun()

{
var myval=document.getElementById(“b1”);

boolean is_pos = (myval>0);

// Getting the absolute value of num

num = Math.abs(num);

// count frequency of each digit in the number

while (num > 0)

int d = num % 10; // extract last digit

freq[d]++; // increment counting

num = num / 10; //remove last digit

int result = 0;

if(is_pos)

// Set the LEFTMOST digit to minimum expect 0

for (int i = 1 ; i <= 9 ; i++)

if (freq[i] != 0)

result = i;

freq[i]--;

break;

// arrange all remaining digits

// in ascending order

for (int i = 0 ; i <= 9 ; i++)

while (freq[i]-- != 0)
result = result * 10 + i;

else // If negative then number should be Largest

// Set the Rightmost digit to maximum

for (int i = 9 ; i >= 1 ; i--)

if (freq[i] !=0)

result = i;

freq[i]--;

break;

// arrange all remaining digits

// in descending order

for (int i = 9 ; i >=0 ; i--)

while (freq[i]-- != 0)

result = result * 10 + i;

// Negative number should be returned here

result = -result;

return result;

</script>

</head>

<body>

<form id=”form1”>
<label>Enter Your Number

<input type=”Number” name=”num” value=””>

</label>

<br><br/>

<input type=”submit” id=”b1” value=”Validate” onsubmit=”my_fun();”/>

</form>

</body>

</html>

You might also like