0% found this document useful (0 votes)
18 views50 pages

Ip 13M

The document discusses various internet protocols and HTML forms. It describes: 1. Common internet protocols like FTP, HTTP, SMTP, POP, IMAP, and SNMP - outlining their basic functions and ports used. 2. The structure of HTTP requests and responses, which follow a request/response format using start lines, headers, and message bodies. 3. The different types of Cascading Style Sheets (CSS) - inline, internal/embedded, and external CSS - and how they are used to style web pages. 4. The anatomy of HTML forms, including common form elements like inputs, buttons, textareas, and how forms are used to collect user data on web pages

Uploaded by

MORTAL
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)
18 views50 pages

Ip 13M

The document discusses various internet protocols and HTML forms. It describes: 1. Common internet protocols like FTP, HTTP, SMTP, POP, IMAP, and SNMP - outlining their basic functions and ports used. 2. The structure of HTTP requests and responses, which follow a request/response format using start lines, headers, and message bodies. 3. The different types of Cascading Style Sheets (CSS) - inline, internal/embedded, and external CSS - and how they are used to style web pages. 4. The anatomy of HTML forms, including common form elements like inputs, buttons, textareas, and how forms are used to collect user data on web pages

Uploaded by

MORTAL
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/ 50

UNIT 1

1.Internet protocols

Protocols used in internet FTP (File transfer Protocol)


● FTP is used to share files among the computers in the LAN
● It uses two connections (data transfer and control)
● FTP data transfer connection uses port 20
● FTP control connection uses port 21
● Some familiar commands in FTP are: USER, PASS, QUIT, CWD,
DELE, LIST, RETR, STOR, HELP

HTTP (Hyper Text Transfer protocol)


● Hyper Text Transfer protocol (HTTP) is a request/Response, stateless
protocol for communication, to transfer information on LAN and WWW
● It is used to deliver files virtually and other data on WWW
● It takes place through TCP/IP sockets
● A browser is a HTTP client – sends HTTP request
● A web server is a HTTP server – sends HTTP reply
SMTP
● Connection-oriented
● Text-based
● Works in application layer
● ACK is available
● It uses port 25
POP
● It uses port 110
● Current version:POP3
● Single client
● Offline email access
● Can’t search email
● Download is needed
● Only 1 mailbox
● Less internet usage
IMAP
● Manipulate email
● No downloading
● Can’t transfer email
● Access the received emails
● Search the mails
● Many mailboxes
● More internet usage

● It uses port no: 80 (HTTP servers listen to this port)


SNMP (Simple Network Management protocol)
● It is used to manage a network such as its participants, etc
● Types of participants: Supervisors, Agents
● UDP is used for message transfer between them
TCP:-
● Connection oriented (link between the packets)
● ACK is available
● Reliable
● Heavy weight protocol
● Handshaking mechanism available
● Error control, flow control, congestion control mechanisms
● Complex, tough to implement
● Ex: Telnet, SMTP, FTP, e-mail, SSH, HTTP, HTTPS
2.HTTP request-response message
HTTP is based on the client-server architecture model and a stateless
request/response protocol that operates by exchanging messages across a
reliable TCP/IP connection.
An HTTP "client" is a program (Web browser or any other client) that
establishes a connection to a server for the purpose of sending one or more
HTTP request messages. An HTTP "server" is a program ( generally a web
server like Apache Web Server or Internet Information Services IIS, etc. )
that accepts connections in order to serve HTTP requests by sending HTTP
response messages.
HTTP makes use of the Uniform Resource Identifier (URI) to identify a
given resource and to establish a connection. Once the connection is
established, HTTP messages are passed in a format similar to that used by
the Internet mail [RFC5322] and the Multipurpose Internet Mail
Extensions (MIME) [RFC2045]. These messages include requests from
client to server and responses from server to client which will have the
following format:
HTTP-message = <Request> | <Response> ; HTTP/1.1 messages
HTTP requests and HTTP responses use a generic message format of RFC
822 for transferring the required data. This generic message format consists
of the following four items.

● A Start-line

● Zero or more header fields followed by CRLF

An empty line (i.e., a line with nothing preceding the CRLF)


● indicating the end of the header fields

● Optionally a message-body
3.CSS types
Cascading Style Sheet(CSS) is used to set the style in web pages that contain
HTML elements. It sets the background color, font-size, font-family, color,
… etc property of elements on a web page.
There are three types of CSS which are given below:

● Inline CSS
● Internal or Embedded CSS
● External CSS

Inline CSS: Inline CSS contains the CSS property in the body section
attached with element is known as inline CSS. This kind of style is specified
within an HTML tag using the style attribute.
Example:

<!DOCTYPE html>
<html>
<head>
<title>Inline CSS</title>
</head>

<body>
<p style = "color:#009900; font-size:50px;
font-style:italic; text-align:center;">
GeeksForGeeks
</p>

</body>
</html>
Internal or Embedded CSS: This can be used when a single HTML
document must be styled uniquely. The CSS rule set should be within the
HTML file in the head section i.e the CSS is embedded within the HTML
file.

Example:

<!DOCTYPE html>
<html>
<head>
<title>Internal CSS</title>
<style>
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
}
.geeks {
font-style:bold;
font-size:20px;
}
</style>
</head>
<body>
<div class = "main">
<div class ="GFG">GeeksForGeeks</div>

<div class ="geeks">


A computer science portal for geeks
</div>
</div>
</body>
</html>
External CSS: External CSS contains separate CSS file which contains only
style property with the help of tag attributes (For example class, id,
heading, … etc). CSS property written in a separate file with .css extension
and should be linked to the HTML document using link tag. This means
that for each element, style can be set only once and that will be applied
across web pages.
Example: The file given below contains CSS property. This file save with
.css extension. For Ex: geeks.css
body {
background-color:powderblue;
}
.main {
text-align:center;
}
.GFG {
color:#009900;
font-size:50px;
font-weight:bold;
}
#geeks {
font-style:bold;
font-size:20px;
}
4.Forms

HTML stands for HyperText Markup Language. It is used to design web


pages using a markup language. It is a combination of Hypertext and
Markup language. HTML uses predefined tags and elements that tell the
browser how to properly display the content on the screen, and form is one
of them. So, in this article, we will learn what is exactly HTML form, what
are the elements of forms and how can we use HTML form in our webpage.
<form> is a HTML element to collect input data with containing interactive
controls. It provides facilities to input text, number, values, email, password,
and control fields such as checkboxes, radio buttons, submit buttons, etc., or
in other words, form is a container that contains input elements like text,
email, number, radio buttons, checkboxes, submit buttons, etc. Forms are
generally used when you want to collect data from the user. For example, a
user wants to buy a bag online, so he/she has to first enter their shipping
address in the address form and then add their payment details in the
payment form to place an order.
Forms are created by placing input fields within paragraphs, preformatted
text, lists and tables. This gives considerable flexibility in designing the
layout of forms.
Syntax:
<form>
<!--form elements-->
</form>

Form elements
These are the following HTML <form> elements:
● <label>: It defines label for <form> elements.
● <input>: It is used to get input data from the form in various types
such as text, password, email, etc by changing its type.
● <button>: It defines a clickable button to control other elements or
execute a functionality.
● <select>: It is used to create a drop-down list.
● <textarea>: It is used to get input long text content.
● <fieldset>: It is used to draw a box around other form elements and
group the related data.
● <legend>: It defines caption for fieldset elements.
● <datalist>: It is used to specify pre-defined list options for input
controls.
● <output>: It displays the output of performed calculations.
● <option>: It is used to define options in a drop-down list.
● <optgroup>: It is used to define group-related options in a drop-down
list.
UNIT 2
1. Javascript form validation

Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button. If the
data entered by a client was incorrect or was simply missing, the server
would have to send all the data back to the client and request that the form
be resubmitted with correct information. This was really a lengthy process
which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer
before sending it to the web server. Form validation generally performs two
functions.
● 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 data.
● Data Format Validation − Secondly, the data that is entered must be
checked for correct form and value. Your code must include appropriate
logic to test correctness of data.

Basic Form Validation


First let us see how to do a basic form validation. In the above form, we are
calling validate() to validate data when onsubmit event is occurring. The
following code shows the implementation of this validate() function.
EXAMPLE:
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {

if( document.myForm.Name.value == "" ) {


alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN(
document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {

alert( "Please provide a zip in the format #####." );


document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>

Data Format Validation


Now we will see how we can validate our entered form data before
submitting it to the web server.
The following example shows how to validate an entered email address. An
email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’
must not be the first character of the email address, and the last dot must at
least be one character after the ‘@’ sign.

EXAMPLE:
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");

if (atpos < 1 || ( dotpos - atpos < 2 )) {


alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
2.Regular expression

A regular expression is a sequence of characters that forms a search


pattern. The search pattern can be used for text search and text to replace
operations. A regular expression can be a single character or a more
complicated pattern. Regular expressions can be used to perform all types
of text search and text replace operations.
Syntax:

/pattern/modifiers;
Example:

var patt = /GeeksforGeeks/i;


Explanation:
/GeeksforGeeks/i is a regular expression.
GeeksforGeeks is a pattern (to be used in a search).
i is a modifier (modifies the search to be Case-Insensitive).
Regular Expression Modifiers :
Modifiers can be used to perform multiline searches:
Examples:

Expression
Description
s

[abc] Find any of the character inside the brackets

[0-9] Find any of the digits between the brackets 0 to 9

Find any of the alternatives between x or y separated


(x | y)
with |
Regular Expression Patterns :
Metacharacters are characters with a special meaning:
Examples:
Metacharacter Description

\d Used to find a digit

\s Used to find a whitespace character

\b Used to find a match at beginning or at the end of a word

Used to find the Unicode character specified by the


\uxxxx
hexadecimal number xxxxx
Quantifiers define quantities:
Examples:

Quantifier Description

n+ Used to match any string that contains at least one n

Used to match any string that contains zero or more occurrences


n*
of n

Used to matches any string that contains zero or one occurrences


n?
of n
3.Exception handling

Exception Handling in Java is one of the effective means to handle the


runtime errors so that the regular flow of the application can be preserved.
Java Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException,
etc.
Exception is an unwanted or unexpected event, which occurs during the
execution of a program, i.e. at run time, that disrupts the normal flow of the
program’s instructions. Exceptions can be caught and handled by the
program. When an exception occurs within a method, it creates an object.
This object is called the exception object. It contains information about the
exception, such as the name and description of the exception and the state of
the program when the exception occurred.

Major reasons why an exception Occurs


● Invalid user input
● Device failure
● Loss of network connection
● Physical limitations (out of disk memory)
● Code errors
● Opening an unavailable file

Exception Hierarchy
All exception and error types are subclasses of class Throwable, which is the
base class of the hierarchy. One branch is headed by Exception. This class is
used for exceptional conditions that user programs should catch.
NullPointerException is an example of such an exception. Another branch,
Error is used by the Java run-time system(JVM) to indicate errors having
to do with the run-time environment itself(JRE). StackOverflowError is an
example of such an error.
Types of Exceptions
Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their own exceptions.
Exceptions can be categorized in two ways:
1. Built-in Exceptions
○ Checked Exception
○ Unchecked Exception
2. User-Defined Exceptions

Let us discuss the above-defined listed exception that is as follows:


A. Built-in Exceptions:
Built-in exceptions are the exceptions that are available in Java libraries.
These exceptions are suitable to explain certain error situations.
● Checked Exceptions: Checked exceptions are called compile-time
exceptions because these exceptions are checked at compile-time by the
compiler.

● Unchecked Exceptions: The unchecked exceptions are just opposite to


the checked exceptions. The compiler will not check these exceptions at
compile time. In simple words, if a program throws an unchecked
exception, and even if we didn’t handle or declare it, the program would not
give a compilation error.

B. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain
situation. In such cases, users can also create exceptions, which are called
‘user-defined Exceptions’.
The advantages of Exception Handling in Java are as follows:
1. Provision to Complete Program Execution
2. Easy Identification of Program Code and Error-Handling Code
3. Propagation of Errors
4. Meaningful Error Reporting
5. Identifying Error Types

4. Event handling
An event can be defined as changing the state of an object or behavior by
performing actions. Actions can be a button click, cursor movement,
keypress through the keyboard or page scrolling, etc.
The java.awt.event package can be used to provide various event classes.

Classification of Events
● Foreground Events
● Background Events

1. Foreground Events
Foreground events are the events that require user interaction to generate,
i.e., foreground events are generated due to interaction by the user on
components in Graphic User Interface (GUI). Interactions are nothing but
clicking on a button, scrolling the scroll bar, cursor moments, etc.

2. Background Events
Events that don’t require interactions of users to generate are known as
background events. Examples of these events are operating system
failures/interrupts, operation completion, etc.
Event Handling
It is a mechanism to control the events and to decide what should happen
after an event occur. To handle the events, Java follows the Delegation
Event model.

Delegation Event model


● It has Sources and Listeners.

● Source: Events are generated from the source. There are various
sources like buttons, checkboxes, list, menu-item, choice, scrollbar, text
components, windows, etc., to generate events.
● Listeners: Listeners are used for handling the events generated from
the source. Each of these listeners represents interfaces that are responsible
for handling events.
To perform Event Handling, we need to register the source with the listener.

Registering the Source With Listener


Different Classes provide different registration methods.
Syntax:
addTypeListener()
where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2:that For ActionEvent we use addActionListener() to register.

Event Classes in Java

Listener
Event Class Description
Interface

An event that indicates


that a
component-defined
ActionEvent ActionListener action occurred like a
button click or
selecting an item from
the menu-item list.

The adjustment event


Adjustment is emitted by an
AdjustmentEvent
Listener Adjustable object like
Scrollbar.
5.JSON

JSON or JavaScript Object Notation is a lightweight text-based open


standard designed for human-readable data interchange. Conventions used
by JSON are known to programmers, which include C, C++, Java, Python,
Perl, etc.
● JSON stands for JavaScript Object Notation.
● The format was specified by Douglas Crockford.
● It was designed for human-readable data interchange.
● It has been extended from the JavaScript scripting language.
● The filename extension is .json.
● JSON Internet Media type is application/json.
● The Uniform Type Identifier is public.json.

Uses of JSON
● It is used while writing JavaScript based applications that includes
browser extensions and websites.
● JSON format is used for serializing and transmitting structured data
over network connection.
● It is primarily used to transmit data between a server and web
applications.
● Web services and APIs use JSON format to provide public data.
● It can be used with modern programming languages.

Characteristics of JSON
● JSON is easy to read and write.
● It is a lightweight text-based interchange format.
● JSON is language independent.

Simple Example in JSON


The following example shows how to use JSON to store information related
to books based on their topic and edition.
{
"book": [
{
"id":"01",
"language": "Java",
"edition": "third",
"author": "Herbert Schildt"
},

{
"id":"07",
"language": "C++",
"edition": "second",
"author": "E.Balagurusamy"
}
]
}
6.Http request

HTTP (Hypertext Transfer Protocol) specifies a collection of request


methods to specify what action is to be performed on a particular resource.
The most commonly used HTTP request methods are GET, POST, PUT,
PATCH, and DELETE. These are equivalent to the CRUD operations
(create, read, update, and delete).

GET: GET request is used to read/retrieve data from a web server. GET
returns an HTTP status code of 200 (OK) if the data is successfully
retrieved from the server.

POST: POST request is used to send data (file, form data, etc.) to the server.
On successful creation, it returns an HTTP status code of 201.

PUT: A PUT request is used to modify the data on the server. It replaces the
entire content at a particular location with data that is passed in the body
payload. If there are no resources that match the request, it will generate
one.

PATCH: PATCH is similar to PUT request, but the only difference is, it
modifies a part of the data. It will only replace the content that you want to
update.

DELETE: A DELETE request is used to delete the data on the server at a


specified location.
Now, let’s understand all of these request methods by example. We have set
up a small application that includes a NodeJS server and MongoDB
database. NodeJS server will handle all the requests and return back an
appropriate response.

Setup and Installation:


Step 1: To start a NodeJS application, create a folder called RestAPI and
run the following command.
npm init -y
Step 2: Using the following command, install the required npm packages.
npm install express body-parser mongoose
Step 3: In your project directory, create a file called index.js.
Project Structure: Our project directory should now look like this.

How to make a GET request


1. To make a GET request, paste the following URL in the Enter request
URL text box of the postman.
https://api.github.com/gists
2. Go to the headers tab and add a header called “Accept” and set it to:
application/vnd.github.v3+json
3. At the bottom, you can see the response formatted as JSON.
UNIT 3
1.Servlet architecture

Servlets are grouped under the Advanced Java tree that are used to create
dynamic web applications. Servlets are robust in nature, well scalable and
are primarily used in developing server-side applications. If we go a little
back in time, we would be able to witness that before the introduction of
servlets, CGI (Common Gateway Interface) were used. Amid several
indigenous tasks that a servlet is capable of doing, dynamically performing
client requests and responses are most common. Other tasks that a servlet
can do effectively are:
● Can easily manage/control the application flow.
● Suitable to implement business logic.
● Can effectively balance the load at the server-side.
● Easily generate dynamic web content.
Talking about the types of servlets, there are primarily two types, namely:
1. Generic Servlets
2. HTTP Servlets
There are three potential ways in which we can employ to create a servlet:
1. Implementing Servlet Interface
2. Extending Generic Servlet
3. Extending HTTP Servlet

Components of Servlet Architecture


Below is the high level architecture diagram of servlet. Let’s see in brief,
how does each component add to the working of a servlet.
Servlet Architecture
1. Client
The client shown in the architecture above is primarily working as a
medium who is sending out HTTP requests over to the web server and
again processing the response it gets back from the server. As we can see in
the diagram, our client here is the web browser.
2. Web Server
Primary job of a web server is to process the requests and responses that a
user sends over time and maintain how a web user would be able to access
the files that has been hosted over the server. The server we are talking
about here is a software which manages access to a centralized resource or
service in a network.. There are precisely two types of webservers:
1. Static web server
2. Dynamic web server
3. Web Container
Web container is another typical component in servlet architecture which is
responsible for communicating with the servlets. Two prime tasks of a web
container are:
● Managing the servlet lifecycle
● URL mapping
Web container sits at the server-side managing and handling all the requests
that are coming in either from the servlets or from some JSP pages or
potentially any other file system.
2. Servlet life cycle

The entire life cycle of a Servlet is managed by the Servlet container which
uses the javax.servlet.Servlet interface to understand the Servlet object and
manage it. So, before creating a Servlet object, let’s first understand the life
cycle of the Servlet object which is actually understanding how the Servlet
container manages the Servlet object.
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through
four stages,
● Loading a Servlet.
● Initializing the Servlet.
● Request handling.
● Destroying the Servlet.

Let’s look at each of these stages in details:

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.

2. The Servlet container performs two operations in this stage :


○ Loading : Loads the Servlet class.
○ Instantiation : Creates an instance of the Servlet. To create a new
instance of the Servlet, the container uses the no-argument constructor.
3.
4. 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.

5. 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 :
○ 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.
○ After creating the request and response objects it invokes the
Servlet.service(ServletRequest, ServletResponse) method by passing the
request and response objects.
6. The service() method while processing the request may throw the
ServletException or UnavailableException or IOException.

7. Destroying a Servlet: When a Servlet container decides to destroy the


Servlet, it performs the following operations,
○ It allows all the threads currently running in the service method of the
Servlet instance to complete their jobs and get released.
○ After currently running threads have completed their jobs, the
Servlet container calls the destroy() method on the Servlet instance.

8. 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 Life Cycle Methods
There are three life cycle methods of a Servlet :
● init()
● service()
● destroy()
3.Session tracking

● Because the HTTP protocol is stateless, we require Session Tracking


to make the client-server relationship stateful.
● Session tracking is important for tracking conversions in online
shopping, mailing applications, and E-Commerce applications.
● The HTTP protocol is stateless, which implies that each request is
treated as a new one. As you can see in the image below.

Session Tracking employs Four Different techniques


1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

A. Cookies
Cookies are little pieces of data delivered by the web server in the response
header and kept by the browser. Each web client can be assigned a unique
session ID by a web server. Cookies are used to keep the session going.
Cookies can be turned off by the client.

B. Hidden Form Field


The information is inserted into the web pages via the hidden form field,
which is then transferred to the server. These fields are hidden from the
user’s view.
Illustration:
<input type = hidden' name = 'session' value = '12345' >

C. URL Rewriting
With each request and return, append some more data via URL as request
parameters. URL rewriting is a better technique to keep session
management and browser operations in sync.

D. HttpSession
A user session is represented by the HttpSession object. A session is
established between an HTTP client and an HTTP server using the
HttpSession interface. A user session is a collection of data about a user that
spans many HTTP requests.
Illustration:
HttpSession session = request.getSession( );
Session.setAttribute("username", "password");
The request must be made. Before sending any document content to the
client, you must first call getSession().
4. Database connectivity

Java Database Connectivity is a standard API or we can say an application


interface present between the Java programming language and the various
databases like Oracle, SQL, PostgreSQL, MongoDB, etc. It basically
connects the front end(for interacting with the users) with the backend for
storing data entered by the users in the table details. JDBC or Java
Database Connection creates a database by following the following steps:
● Import the database
● Load and register drivers
● Create a connection
● Create a statement
● Execute the query
● Process the results
● Close the connection

Step 1: Import the database


Java consists of many packages that ease the need to hardcode every logic.
It has an inbuilt package of SQL that is needed for JDBC connection.

Step 2: Load and register drivers


This is done by JVC(Java Virtual Machines) that loads certain driver files
into secondary memory that are essential to the working of JDBC.

Step 3: Create a connection


Creating a connection is accomplished by the getconnection() method of
DriverManager class, it contains the database URL, username, and
password as a parameter.

Step 4: Create a statement


Query statement is created to interact with the database by following the
proper syntax. Before writing the query, we must connect the database
using connect() method.
Step 5: Execute the query
For executing the query (written above), we need to convert the query in
JDBC readable format, for that we use the preparedstatement() function
and for executing the converted query, we use the executequery() function
of the Statement interface. It returns the object of “rs” which is used to find
all the table records.

Step 6: Process the results


Now we check if rs.next() method is not null, then we display the details of
that particular customer present in the “customer” table.next() function
basically checks if there’s any record that satisfies the query, if no record
satisfies the condition, then it returns null.

Step 7: Close the connection


After all the operations are performed it’s necessary to close the JDBC
connection after the database session is no longer needed. If not explicitly
done, then the java garbage collector does the job for us. However being a
good programmer, let us learn how to close the connection of JDBC. So to
close the JDBC connection close() method is used, this method close all the
JDBC connection.
5. JSTL

JSTL (JSP Standard Tag Library)


The JSP Standard Tag Library (JSTL) represents a set of tags to simplify
the JSP development.

Advantage of JSTL
1. Fast Development JSTL provides many tags that simplify the JSP.
2. Code Reusability We can use the JSTL tags on various pages.
3. No need to use scriptlet tag It avoids the use of scriptlet tag.

JSTL Tags
There JSTL mainly provides five types of tags:
Tag Name Description

Core tags The JSTL core tag provide variable support, URL
management, flow control, etc. The URL for the core tag is
http://java.sun.com/jsp/jstl/core. The prefix of core tag is c.

Function tags The functions tags provide support for string manipulation
and string length. The URL for the functions tags is
http://java.sun.com/jsp/jstl/functions and prefix is fn.

Formatting The Formatting tags provide support for message


tags formatting, number and date formatting, etc. The URL for
the Formatting tags is http://java.sun.com/jsp/jstl/fmt and
prefix is fmt.

XML tags The XML tags provide flow control, transformation, etc.
The URL for the XML tags is
http://java.sun.com/jsp/jstl/xml and prefix is x.

SQL tags The JSTL SQL tags provide SQL support. The URL for
the SQL tags is http://java.sun.com/jsp/jstl/sql and prefix is
sql.
UNIT 4
1.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.

Syntax
You need to declare a schema in your XML document as follows −

Example
The following example shows how to use schema −
<?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>
The basic idea behind XML Schemas is that they describe the legitimate
format that an XML document can take.

Elements
As we saw in the XML - Elements chapter, 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
You can define XML schema 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.

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.

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"/>
2.DTD

A Document Type Definition (DTD) describes the tree structure of a


document and something about its data. It is a set of markup affirmations
that actually define a type of document for the SGML family, like GML,
SGML, HTML, XML.
A DTD can be declared inside an XML document as inline or as an external
recommendation. DTD determines how many times a node should appear,
and how their child nodes are ordered.
There are 2 data types, PCDATA and CDATA
● PCDATA is parsed character data.
● CDATA is character data, not usually parsed.
Syntax:
<!DOCTYPE element DTD identifier
[
first declaration
second declaration
.
.
nth declaration
]>

Example:
3.XML parsers

XML Parsers
An XML parser is a software library or package that provides interfaces for
client applications to work with an XML document. The XML Parser is
designed to read the XML and create a way for programs to use XML.
XML parser validates the document and check that the document is well
formatted.
Let's understand the working of XML parser by the figure given below:

Types of XML Parsers


These are the two main types of XML Parsers:
1. DOM
2. SAX

DOM (Document Object Model)


A DOM document is an object which contains all the information of an
XML document. It is composed like a tree structure. The DOM Parser
implements a DOM API. This API is very simple to use.
Features of DOM Parser
A DOM Parser creates an internal structure in memory which is a DOM
document object and the client applications get information of the original
XML document by invoking methods on this document object.
DOM Parser has a tree based structure.

Advantages
1) It supports both read and write operations and the API is very simple to
use.
2) It is preferred when random access to widely separated parts of a
document is required.

Disadvantages
1) It is memory inefficient. (consumes more memory because the whole
XML document needs to loaded into memory).
2) It is comparatively slower than other parsers.

SAX (Simple API for XML)


A SAX Parser implements SAX API. This API is an event based API and
less intuitive.

Features of SAX Parser


It does not create any internal structure.
Clients does not know what methods to call, they just overrides the methods
of the API and place his own code inside method.
It is an event based parser, it works like an event handler in Java.

Advantages
1) It is simple and memory efficient.
2) It is very fast and works for huge documents.

Disadvantages
1) It is event-based so its API is less intuitive.
2) Clients never know the full information because the data is broken into
pieces.
4.Php from validation

Form Validation in PHP


An HTML form contains various input fields such as text box, checkbox,
radio buttons, submit button, and checklist, etc. These input fields need to
be validated, which ensures that the user has entered information in all the
required fields and also validates that the information provided by the user
is valid and correct.
There is no guarantee that the information provided by the user is always
correct. PHP validates the data at the server-side, which is submitted by
HTML form. You need to validate a few things:
1. Empty String
2. Validate String
3. Validate Numbers
4. Validate Email
5. Validate URL
6. Input length

Empty String
The code below checks that the field is not empty. If the user leaves the
required field empty, it will show an error message. Put these lines of code
to validate the required field.
1. if (emptyempty ($_POST["name"])) {
2. $errMsg = "Error! You didn't enter the Name.";
3. echo $errMsg;
4. } else {
5. $name = $_POST["name"];
6. }

Validate String
The code below checks that the field will contain only alphabets and
whitespace, for example - name. If the name field does not receive valid
input from the user, then it will show an error message:
1. $name = $_POST ["Name"];
2. if (!preg_match ("/^[a-zA-z]*$/", $name) ) {
3. $ErrMsg = "Only alphabets and whitespace are allowed.";
4. echo $ErrMsg;
5. } else {
6. echo $name;
7. }

Validate Number
The below code validates that the field will only contain a numeric value.
For example - Mobile no. If the Mobile no field does not receive numeric
data from the user, the code will display an error message:
1. $mobileno = $_POST ["Mobile_no"];
2. if (!preg_match ("/^[0-9]*$/", $mobileno) ){
3. $ErrMsg = "Only numeric value is allowed.";
4. echo $ErrMsg;
5. } else {
6. echo $mobileno;
7. }

Validate Email
A valid email must contain @ and . symbols. PHP provides various methods
to validate the email address. Here, we will use regular expressions to
validate the email address.
The below code validates the email address provided by the user through
HTML form. If the field does not contain a valid email address, then the
code will display an error message:
1. $email = $_POST ["Email"];
2. $pattern =
"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$^";
3. if (!preg_match ($pattern, $email) ){
4. $ErrMsg = "Email is not valid.";
5. echo $ErrMsg;
6. } else {
7. echo "Your valid email address is: " .$email;
8. }

Input Length Validation


The input length validation restricts the user to provide the value between
the specified range, for Example - Mobile Number. A valid mobile number
must have 10 digits.
The given code will help you to apply the length validation on user input:
1. $mobileno = strlen ($_POST ["Mobile"]);
2. $length = strlen ($mobileno);
3.
4. if ( $length < 10 && $length > 10) {
5. $ErrMsg = "Mobile must have 10 digits.";
6. echo $ErrMsg;
7. } else {
8. echo "Your Mobile number is: " .$mobileno;
9. }

Validate URL
The below code validates the URL of website provided by the user via
HTML form. If the field does not contain a valid URL, the code will display
an error message, i.e., "URL is not valid".
1. $websiteURL = $_POST["website"];
2. if
(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-
a-z0-9+&@#\/%=~_|]/i",$website)) {
3. $websiteErr = "URL is not valid";
4. echo $websiteErr;
5. } else {
6. echo "Website URL is: " .$websiteURL;
7. }
5.Php database

PHP MySQL Create Database


Since PHP 4.3, mysql_create_db() function is deprecated. Now it is
recommended to use one of the 2 alternatives.
● mysqli_query()
● PDO::__query()

PHP MySQLi Create Database Example


Example
1. <?php
2. $host = 'localhost:3306';
3. $user = '';
4. $pass = '';
5. $conn = mysqli_connect($host, $user, $pass);
6. if(! $conn )
7. {
8. die('Could not connect: ' . mysqli_connect_error());
9. }
10.echo 'Connected successfully<br/>';
11.
12.$sql = 'CREATE Database mydb';
13.if(mysqli_query( $conn,$sql)){
14. echo "Database mydb created successfully.";
15.}else{
16.echo "Sorry, database creation failed ".mysqli_error($conn);
17.}
18.mysqli_close($conn);
19.?>
Output:
Connected successfully
Database mydb created successfully.
6.File handling

File Handling is the storing of data in a file using a program. In C


programming language, the programs store results, and other data of the
program to a file using file handling in C. Also, we can extract/fetch data
from a file to work with it in the program.
The operations that you can perform on a File in C are −
● Creating a new file
● Opening an existing file
● Reading data from an existing file
● Writing data to a file
● Moving data to a specific location on the file
● Closing the file

Creating or opening file using fopen()


The fopen() function is used to create a new file or open an existing file in C.
The fopen function is defined in the stdio.h header file.
Now, lets see the syntax for creation of a new file or opening a file
file = fopen(“file_name”, “mode”)
7.Cookies

Cookies are small files which are stored on a user’s computer. They are used
to hold a modest amount of data specific to a particular client and website
and can be accessed either by the web server or by the client computer
When cookies were invented, they were basically little documents
containing information about you and your preferences. For instance, when
you select your language in which you want to view your website, the
website would save the information in a document called a cookie on your
computer, and the next time when you visit the website, it would be able to
read a cookie saved earlier. That way the website could remember your
language and let you view the website in your preferred language without
having to select the language again.
A cookie can contain any type of information such as the time when you
visited the website, the items that you added into your shopping basket, all
the links you clicked in website, etc.,
If a cookie is created in a particular website, and you visit another website
later, the latter would not be able to read the contents from the first website,
in other words only the same website that saves information to a cookie can
access it.

Types of internet Cookies

Session Cookies: A session cookie only lasts for the duration of users using
the website. A web browser normally deletes session cookies when it quits. A
session cookie expires if the user does not access the website for a period of
time chosen by the server(idle timeout). They only last for the duration of
time we are on the site. If someone comes and uses our computer, they
would not be able to see anything on the sites that use session cookies,
because they need to enter the username and password again.

Persistent Cookies: A persistent cookie outlast user sessions. If a persistent


cookie has its maximum age 1 year, then within a year, the initial value set
in the cookie would be sent back to the server every time the user visits the
server. This could be used to record a vital piece of information such as how
the user initially came to the website. For this reason, persistent cookies are
also called tracking cookies. These are kind of cookies are used on websites
that need to know who we are but offer us the ability to “remember me”
when you enter username and password.
Example: Gmail.

Third-party cookies: Third party cookies are the cookies being set with the
different domain than the one shown in the address bar. For example, if you
were to visit Sendflowers.com, it may set the cookie for the address of
SomeAdvertiser.com. Later, when you visit RebuidEngines.com it may set
the cookie for SomeAdvertiser.com. Both of these cookies will be used by
SomeAdvertiser.com to ascertain that you are a person who sends flowers
and works on cars. These are used by advertising agencies who have clients
that pay for displaying ads for products and services but don’t want to
waste money displaying them to people who aren’t going to be a customer.

HTTP Cookies: When you send a request to the server, the server sends a
reply in which it embeds the cookie which serves as an identifier to identify
the user. So, next time when you visit the same website, the cookie lets the
server know that you are visiting the website again.
UNIT 5
1.Ajax client-server architecture

AJAX communicates with the server using XMLHttpRequest object. Let's


try to understand the flow of ajax or how ajax works by the image
displayed below.

As you can see in the above example, XMLHttpRequest object plays a


important role.

1. User sends a request from the UI and a javascript call goes to


XMLHttpRequest object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net
etc.
4. Data is retrieved.
5. Server sends XML data or JSON data to the XMLHttpRequest
callback function.
6. HTML and CSS data is displayed on the browser.
Ajax is a client-side script that communicates to and from a server/database
without the need for a postback or a complete page refresh. The best
definition I’ve read for Ajax is “the method of exchanging data with a
server, and updating parts of a web page – without reloading the entire
page.” Ajax itself is mostly a generic term for various JavaScript techniques
used to connect to a web server dynamically without necessarily loading
multiple pages. In a more narrowly-defined sense, it refers to the use of
XmlHttpRequest objects to interact with a web server dynamically via
JavaScript.

Benefits of Ajax
There are 4 main benefits of using Ajax in web applications:
1. Callbacks: Ajax is used to perform a callback, making a quick round
trip to and from the server to retrieve and/or save data without posting the
entire page back to the server. By not performing a full postback and
sending all form data to the server, network utilization is minimized and
quicker operations occur. In sites and locations with restricted bandwidth,
this can greatly improve network performance. Most of the time, the data
being sent to and from the server is minimal. By using callbacks, the server
is not required to process all form elements. By sending only the necessary
data, there is limited processing on the server. There is no need to process
all form elements, process the ViewState, send images back to the client, or
send a full page back to the client.
2. Making Asynchronous Calls: Ajax allows you to make asynchronous
calls to a web server. This allows the client browser to avoid waiting for all
data to arrive before allowing the user to act once more.
3. User-Friendly: Because a page postback is being eliminated, Ajax
enabled applications will always be more responsive, faster and more
user-friendly.
4. Increased Speed: The main purpose of Ajax is to improve the speed,
performance and usability of a web application. A great example of Ajax is
the movie rating feature on Netflix. The user rates a movie and their
personal rating for that movie will be saved to their database without
waiting for the page to refresh or reload. These movie ratings are being
saved to their database without posting the entire page back to the server.
2. WSDL

WSDL stands for Web Services Description Language. It is the standard


format for describing a web service. WSDL was developed jointly by
Microsoft and IBM.

Features of WSDL
● WSDL is an XML-based protocol for information exchange in
decentralized and distributed environments.
● WSDL definitions describe how to access a web service and what
operations it will perform.
● WSDL is a language for describing how to interface with XML-based
services.
● WSDL is an integral part of Universal Description, Discovery, and
Integration (UDDI), an XML-based worldwide business registry.
● WSDL is the language that UDDI uses.
● WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

WSDL Usage
WSDL is often used in combination with SOAP and XML Schema to provide
web services over the Internet. A client program connecting to a web service
can read the WSDL to determine what functions are available on the server.
Any special datatypes used are embedded in the WSDL file in the form of
XML Schema. The client can then use SOAP to actually call one of the
functions listed in the WSDL.

History of WSDL
WSDL 1.1 was submitted as a W3C Note by Ariba, IBM, and Microsoft for
describing services for the W3C XML Activity on XML Protocols in March
2001.
WSDL 1.1 has not been endorsed by the World Wide Web Consortium
(W3C), however it has just released a draft for version 2.0 that will be a
recommendation (an official standard), and thus endorsed by the W3C.
3. SOAP

SOAP is an acronym for Simple Object Access Protocol. It is an XML-based


messaging protocol for exchanging information among computers. SOAP is an
application of the XML specification.

Points to Note
● SOAP is a communication protocol designed to communicate via
Internet.
● SOAP can extend HTTP for XML messaging.
● SOAP provides data transport for Web services.
● SOAP can exchange complete documents or call a remote procedure.
● SOAP can be used for broadcasting a message.
● SOAP is platform- and language-independent.
● SOAP is the XML way of defining what information is sent and how.
● SOAP enables client applications to easily connect to remote services
and invoke remote methods.
Although SOAP can be used in a variety of messaging systems and can be
delivered via a variety of transport protocols, the initial focus of SOAP is
remote procedure calls transported via HTTP.
Other frameworks including CORBA, DCOM, and Java RMI provide similar
functionality to SOAP, but SOAP messages are written entirely in XML and
are therefore uniquely platform- and language-independent.

You might also like