0% found this document useful (0 votes)
11 views13 pages

Iat 2 WT

Uploaded by

romancena972005
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)
11 views13 pages

Iat 2 WT

Uploaded by

romancena972005
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/ 13

PART-B

1) SERVLET ARCHIETECTURE
● Java Servlets are programs that run on a Web or Application server and act as a
middle layer between a requests coming from a Web browser or other HTTP client
and databases or applications on the HTTP server.
● Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically.
● Java Servlets often serve the same purpose as programs implemented using the
Common Gateway Interface (CGI). But Servlets offer several advantages in
comparison with the CGI.
⮚ Performance is significantly better.
⮚ Servlets execute within the address space of a Web server. It is not necessary
to create a separate process to handle each client request.
⮚ Servlets are platform-independent because they are written in Java.
⮚ Java security manager on the server enforces a set of restrictions to protect the
resources on a server machine. So servlets are trusted.
⮚ The full functionality of the Java class libraries is available to a servlet. It can
communicate with applets, databases, or other software via the sockets and
RMI mechanisms that you have seen already.

1.1 Servlets Architecture

The following diagram shows the position of Servlets in a Web Application.

Fig: 3.1 Servlet Architecture

1.2 Servlets Tasks

Servlets perform the following major tasks –


● Read the explicit data sent by the clients (browsers). This includes an HTML form
on a Web page or it could also come from an applet or a custom HTTP client program.
● Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.
● Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing
the response directly.
● Send the explicit data (i.e., the document) to the clients (browsers). This document
can be sent in a variety of formats, including text (HTML or XML), binary (GIF
images), Excel, etc.
● Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML),
setting cookies and caching parameters, and other such tasks.

Servlets Packages
● Java Servlets are Java classes run by a web server that has an interpreter that
supports the Java Servlet specification.
● Servlets can be created using the javax.servlet and javax.servlet.http packages, which
are a standard part of the Java's enterprise edition, an expanded version of the Java
class library that supports large-scale development projects.
● These classes implement the Java Servlet and JSP specifications. At the time of
writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1.
● Java servlets have been created and compiled just like any other Java class. After you
install the servlet packages and add them to your computer's Classpath, you can
compile servlets with the JDK's Java compiler or any other current compiler.

1.3 Basic Structure of a Servlet

public class firstServlet extends HttpServlet {


public void init() {
/* Put your initialization code in this method,
* as this method is called only once */
}
public void service() {
// Service request for Servlet
}
public void destroy() {
// For taking the servlet out of service, this method is called only once
}
}

2) GET & POST:


<!DOCTYPE html> <!DOCTYPE html>
<html> <html>

<body> <body>
Welcome Welcome
<?php echo $_GET["username"]; ?> </br> <?php echo $_POST["username"]; ?> </br>
Your City is: YOur Area of Study is:
<?php echo $_GET["city"]; ?> <?php echo $_POST["area"]; ?>
</body> </body>

</html> </html>

3) Control statements in php


control staments are used to determine the flow of execution in PHP scripts.
Types of control structures:
 Conditional statements (if, else, switch)
 Loops (for, while, do-while)
 Control transfer (break, continue, exit)

Conditional statements
If
The if statement executes a block of code if a specified condition is true. It is the
simplest form of control statement.
Example:
$x = 10;
if ($x > 5) {
echo "X is greater than 5";
}
Output:
X is greater than 5

If-else
The if...else statement allows you to execute one block of code if a condition is
true and another block if the condition is false.
example:
$x = 3;
if ($x > 5) {
echo "X is greater than 5";
} else {
echo "X is less than or equal to 5";
}
Output:
X is less than or equal to 5

If elseif else:
else if statement allows you to evaluate multiple conditions sequentially and execute
the corresponding block of code if any condition is true.
Example:
$x = 5;
if ($x > 10) {
echo "X is greater than 10";
} elseif ($x == 5) {
echo "X equals 5";
} else {
echo "X is less than 5"; }
Output:
X equals 5

Switch:
PHP switch statement provides an alternative to multiple elseif statements by
allowing you to test a variable against multiple possible values and execute different blocks
of code accordingly.
Example:
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
Output:
Your favorite color is red!

Loops (for, while, do-while)

For Loop:
PHP for loop is used when you know exactly how many times you want to iterate
through a block of code. It consists of three expressions:
Initialization: Sets the initial value of the loop variable.
Condition: Checks if the loop should continue.
Increment/Decrement: Changes the loop variable after each iteration.
Example:
for ($num = 1; $num <= 5; $num += 1) {
echo $num . " ";}
OUTPUT:
12345

WHILE LOOP:
The while loop is also an entry control loop like for loops. It first checks the condition
at the start of the loop and if its true then it enters into the loop and executes the block of
statements, and goes on executing it as long as the condition holds true.
Example:
$num = 1;

while ($num <= 5) {


echo $num . " ";
$num++;
}
Output:
12345

do-while Loop
The do-while loop is an exit control loop which means, it first enters the loop,
executes the statements, and then checks the condition. Therefore, a statement is
executed at least once using the do…while loop. After executing once, the program is
executed as long as the condition holds true.
Example:
$num = 1;
do {
echo $num . " ";
$num++;
} while ($num <= 5);
Output:
12345

foreach Loop
This foreach loop is used to iterate over arrays. For every counter of loop, an array
element is assigned and the next counter is shifted to the next element.
Example:
$arr = array (10, 20, 30, 40, 50, 60);
foreach ($arr as $val) {
echo $val . " ";
}
echo "\n";
// foreach loop over an array with keys
$ages = array(
"John" => 25,
"Alice" => 30,
"Bob" => 22
);
foreach ($ages as $name => $age) {
echo $name . " => " . $age . "\n";
}
Output:
10 20 30 40 50 60
John => 25
Alice => 30
Bob => 22

Control transfer
Break: Exits the current loop or switch statement.
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
break; // exit loop
}
echo $i;
}

Continue: Skips the current iteration of a loop and moves to the next one.
for ($i = 0; $i < 10; $i++) {
if ($i == 5) {
continue; // skip this iteration
}
echo $i;
}
Exit: Terminates script execution.
echo "This is a PHP script.";
exit("Goodbye!"); // This will output "Goodbye!" and terminate the script.
echo "This line will not be executed.";

4) Built-in Functions in PHP


PHP has over 1,000 built-in functions for common tasks.
They help with operations on strings, arrays, dates, files, databases, etc.
Functions save time and ensure efficiency by eliminating the need to write repetitive
code.

String Functions
Common String Functions:
strlen($string) – Returns the length of the string.
strpos($haystack, $needle) – Finds the position of the first occurrence of a substring.
str_replace($search, $replace, $subject) – Replaces all occurrences of a search string with a
replacement string.
substr($string, $start, $length) – Returns a part of a string.

Array Functions
Popular Array Functions:
array_push($array, $value) – Adds one or more elements to the end of an array.
array_pop($array) – Removes the last element from an array.
array_merge($array1, $array2) – Merges two or more arrays.
array_slice($array, $offset, $length) – Extracts a portion of an array.

Math Functions
Essential Math Functions:
abs($number) – Returns the absolute value.
ceil($number) – Rounds a number up to the next highest integer.
floor($number) – Rounds a number down to the nearest integer.
rand($min, $max) – Generates a random integer between two values.

Date and Time Functions


Working with Date and Time:
date($format) – Formats a local date and time.
strtotime($time) – Parses a time string into a Unix timestamp.
time() – Returns the current Unix timestamp.
mktime($hour, $minute, $second, $month, $day, $year) – Returns the Unix timestamp for
a specific date.

File Handling Functions


Managing Files:
fopen($filename, $mode) – Opens a file or URL.
fwrite($handle, $string) – Writes to an open file.
fread($handle, $length) – Reads from an open file.
fclose($handle) – Closes an open file.

Database Functions (MySQL)


Interacting with Databases:
mysqli_connect($host, $user, $password, $database) – Opens a new connection to a
MySQL server.
mysqli_query($connection, $query) – Performs a query against the database.
mysqli_fetch_assoc($result) – Fetches a result row as an associative array.
mysqli_close($connection) – Closes a MySQL connection.

Error Handling Functions


Handling Errors in PHP:
error_reporting($level) – Sets the error reporting level.
trigger_error($message, $type) – Generates a user-level error or warning.
set_error_handler($handler) – Sets a user-defined error handler function.

Miscellaneous Functions
empty($variable) – Checks if a variable is empty.
isset($variable) – Determines if a variable is set and is not null.
die($message) – Outputs a message and terminates the script.
print_r($value) – Prints human-readable information about a variable.

5) XML SCHEMA:
● XML Schema is commonly known as XML Schema Definition (XSD).
● It is used to describe and validate the structure and the content of XML data. XML
schema defines the elements, attributes and data types.
● Schema element supports Namespaces. It is similar to a database schema that
describes the data in a database.

EXAMPLE:

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


<xs:schema xmlns:xs = "http://www.w3.org/2001/XMLSchema">
<xs:element name = "contact">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
Elements
Elements are the building blocks of XML document. An element can be defined
within an XSD as follows −
<xs:element name = "x" type = "y"/>
Definition Types
XML schema can be define elements in the following ways −
Simple Type
Simple type element is used only in the context of the text. Some of the predefined
simple types are: xs:integer, xs:boolean, xs:string, xs:date. For example −
<xs:element name = "phone_number" type = "xs:int" />
Complex Type
A complex type is a container for other element definitions. This allows you to specify
which child elements an element can contain and to provide some structure within your
XML documents. For example −
<xs:element name = "Address">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
<xs:element name = "phone" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
In the above example, Address element consists of child elements. This is a container
for other <xs:element> definitions, that allows to build a simple hierarchy of elements in
the XML document.
Global Types
With the global type, you can define a single type in your document, which can be
used by all other references. For example, suppose you want to generalize
the person and company for different addresses of the company. In such case, you can
define a general type as follows −
<xs:element name = "AddressType">
<xs:complexType>
<xs:sequence>
<xs:element name = "name" type = "xs:string" />
<xs:element name = "company" type = "xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
Now use this type in our example as follows −
<xs:element name = "Address1">
<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone1" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name = "Address2">
<xs:complexType>
<xs:sequence>
<xs:element name = "address" type = "AddressType" />
<xs:element name = "phone2" type = "xs:int" />
</xs:sequence>
</xs:complexType>
</xs:element>
● Instead of having to define the name and the company twice (once for Address1 and
once for Address2), we now have a single definition.
● This makes maintenance simpler, i.e., if you decide to add "Postcode" elements to
the address, you need to add them at just one place.

Attributes
Attributes in XSD provide extra information within an element. Attributes
have name and type property as shown below –
<xs:attribute name = “x” type = “y”/>

PART-C
16) SERVLET LIFE CYCLE
A servlet life cycle can be defined as the entire process from its creation till
the destruction. The following are the paths followed by a servlet.
● The servlet is initialized by calling the init() method.
● The servlet calls service() method to process a client's request.
● The servlet is terminated by calling the destroy() method.
● Finally, servlet is garbage collected by the garbage collector of the JVM.

2.1 The init() Method

● The init method is called only once. It is called only when the servlet is created, and
not called for any user requests afterwards. So, it is used for one-time initializations,
just as with the init method of applets.
● The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started.
● When a user invokes a servlet, a single instance of each servlet gets created, with
each user request resulting in a new thread that is handed off to doGet or doPost as
appropriate.
● The init() method simply creates or loads some data that will be used throughout the
life of the servlet.
● The init method definition looks like this –
Public void init() throws ServletException {
// Initialization code
}

2.2 The service() Method


● The service() method is the main method to perform the actual task. The
servlet container (i.e. web server) calls the service() method to handle requests
coming from the client( browsers) and to write the formatted response back to the
client.
● Each time the server receives a request for a servlet, the server spawns a new
thread and calls service.
● The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
● Here is the signature of this method −
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException { }
● The service () method is called by the container and service method invokes
doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to
do with service() method but you override either doGet() or doPost() depending on
what type of request you receive from the client.
● The doGet() and doPost() are most frequently used methods with in each
service request. Here is the signature of these two methods.

2.3 The doGet() Method

● A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
2.4 The doPost() Method
● A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
// Servlet code
}
2.5 The destroy() Method
● The destroy() method is called only once at the end of the life cycle of a
servlet. This method gives your servlet a chance to close database connections, halt
background threads, write cookie lists or hit counts to disk, and perform other such
cleanup activities.
● After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this −

public void destroy() {


// Finalization code...
}
2.6 Architecture Diagram
● The following figure depicts a typical servlet life-cycle scenario.
● First the HTTP requests coming to the server are delegated to the servlet
container.
● The servlet container loads the servlet before invoking the service() method.
● Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet.

Fig 3.2 Servlet Life Cycle

You might also like