0% found this document useful (0 votes)
16 views

Unit-III Final Java Servlets and XML Notes

Uploaded by

zaidp8256
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Unit-III Final Java Servlets and XML Notes

Uploaded by

zaidp8256
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Servlet life cycle

Q. Explain Servlet Life Cycle [END SEM - 4M OR 8M]


Q. Explain the life cycle of servlet with a neat diagram. [END SEM - 5M OR 8M]

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
Let's see the life cycle of the servlet
1. The servlet is initialized by calling the init() method.
2. The servlet calls service() method to process a client's request.
3. The servlet is terminated by calling the destroy() method.
4. Finally, servlet is garbage collected by the garbage collector of the JVM.

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 1


The Life Cycle of a Servlet
Stages of the Servlet Life Cycle: The Servlet life cycle mainly goes through four stages,
● Loading a Servlet by Servlet Container
● Initializing the Servlet using - init() method
● Request handling using - service() method
● Destroying the Servlet using - destroy() method

1. Loading a Servlet by Servlet Container


1. The first stage of the Servlet life cycle involves loading and initializing the Servlet by the
Servlet container .
2. Servlet container Initializing the context, on configuring the Servlet with a zero or
positive integer value.
3. Creates an instance of the Servlet.
4. To create a new instance (object) of the Servlet, the container uses the no-argument
constructor.

2. Initializing a Servlet: init() method


1. The web container calls the init () method only once after creating the servlet instance.
2. The init method is used to initialize the servlet.
3. init() method: The init() method is called by the Servlet container to indicate that this
Servlet instance (object) is instantiated successfully and is about to be put into service.

//init() method
public class MyServlet implements Servlet {
public void init(ServletConfig config) throws ServletException
{
//initialization code
}
}
3. Request handling using - service() method
The service() method of the Servlet is invoked to inform the Servlet about the client requests.

● This method uses ServletRequest object to collect the data requested by the client.
● This method uses ServletResponse object to generate the output content.

public class MyServlet implements Servlet


{
public void service (ServletRequest res, ServletResponse res) throws ServletException,
IOException
{
// request handling code
}
}

4. Destroying the Servlet using - destroy() method


The destroy() method runs only once during the lifetime of a Servlet and signals the end of the
Servlet instance.
public void destroy()
As soon as the destroy() method is activated, the Servlet container releases the Servlet
instance.
A “Hello World” servlet

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 2


Q. Write a simple servlet program to display hello World [END SEM - 9M ]
Ans
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class Hello extends HttpServlet{
public void doGet(HttpServletRequest req , HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html"); //setting the content type
PrintWriter pw=res.getWriter(); //get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Hello World");
pw.println("</body></html>");
pw.close();//closing the stream
}
}

The deployment descriptor is an xml file From which Web Container gets the information about the
servlet to be invoked.

web.xml file

<web-app>
<servlet>
<servlet-name>Hello</servlet-name>
<servlet-class>Hello</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Hello</servlet-name>
<url-pattern>/Hello</url-pattern>
</servlet-mapping>
</web-app>

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 3


Parameter Data
1. Parameter data" typically refers to the information sent from a client (usually a web browser) to
the server as part of an HTTP request.
2. To access parameter data in a servlet, we use the HttpServletRequest object, which is passed
to the servlet's doGet or doPost methods.

Servlets handles form data parsing automatically using the following methods depending on the
situation

1. getParameter() −
a. Retrieves the value of a single request parameter as a String. If the parameter does not
exist, it returns null.
b. You call the request.getParameter() method to get the value of a form parameter.
c. This method should be used on the parameter that has only one value

Example :
HTML CODE :
<input type="text" name="name" />
<input type="text" name="phone" />

HTML OUTPUT :

Servlet code to get the data

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


String phNum = request.getParameter("phone");

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 4


2. getParameterValues() −
a. The method returns an array of String objects containing all of the values of the given
field/parameter from the request.If the specified parameter name does not exist, it returns
null.
b. Call this method if the parameter appears more than once and returns multiple values,
c. This is useful when a parameter can have multiple values, such as when using multiple
checkboxes with the same name.

Example :
HTML CODE Here language common name to all Checkbox
<input type="checkbox" name="language" value="java" />Java
<input type="checkbox" name="language" value="python" />Python
<input type="checkbox" name="language" value="sql" />SQL
<input type="checkbox" name="language" value="php" />PHP

HTML OUTPUT :

Servlet code to get the data into Array


String progLang[] = request.getParameterValues("language");

3. getParameterNames() −
a. Retrieves an Enumeration of all parameter names in the request. This can be useful
for iterating over all parameters.
b. Call this method if you want a complete list of all parameters in the current request.

Servlet Code to get the data


Enumeration <String> parameterNames = request.getParameterNames();

Note :
1. Parameters are always treated as String values.
2. If you need to handle other data types, you will need to convert or parse them manually (e.g.,
using Integer.parseInt() for integer values).

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 5


Example : Parameter Data handle using the getParameter() method

1. We Create the HelloForm.html form


2. Write Servlet HelloForm.java to handle the html form data.
3. Configure the web.xml

HelloForm.html
<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name"> <br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form> </body>
</html>

HelloForm.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

@WebServlet("/HelloForm ")
public class HelloForm extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.println("<html>\n" + "<head></head>\n" +"<body>" +


"<b>First Name</b>: "+request.getParameter("first_name")+"\n" +
"<b>Last Name</b>: "+request.getParameter("last_name")+"\n" +
"</body>" +"</html>");
}
}

Web.xml
<servlet>
<servlet-name>HelloForm</servlet-name>
<servlet-class> HelloForm</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloForm</servlet-name>
<url-pattern>/HelloForm</url-pattern>
</servlet-mapping>

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 6


Producer to Run the Above Servlet Program using Apache Tomcat Server

1. Create the HelloForm.html into Apache Tomcat Server under the folder
<Tomcat-installationdirectory>/webapps/ROOT directory.
2. Compile the HelloForm.java servlet after the compilation HelloForm.class file is created which
would have to copy this class file in under
Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes

Compile the Program using the servlet package as below from command prompt

Javac HelloForm.java -classpath "C:\Program Files\Apache Software


Foundation\Tomcat 6.0\lib\servlet-api.jar"

3. Create following entries in web.xml file located


Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
4. You would access http://localhost:8080/HelloForm.html

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 7


Sessions
Q. What is session management ?Explain different techniques of session management ? END SEM
8M

1. Session is a conversational state between client and server and it can consist of multiple requests
and responses between client and server.
2. Sessions are used to track user interactions and maintain state across multiple requests.
3. The HttpSession interface provides a way to store and retrieve data for a particular user during
their interaction with a web application.

Why is Session Tracking Required?


● 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.

Different techniques of session management


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

1. Cookies
1. Cookies are small pieces of data sent from the server and stored on the client's browser.
2. They are a common method for session tracking and are automatically included with each
request to the server.
3. Each web client can be assigned a unique session ID by a web server.
4. Cookies are used to manage the ongoing user session.

How It Works:

● The server sends a cookie containing the session ID to the client's browser.
● The client's browser stores the cookie and sends it back with each subsequent request.
● The server reads the session ID from the cookie to identify the session.
● Cookie information is stored in the cache of the browser.Now, if a request is sent by the same
user, a cookie is added with the request by default. Thus the server recognizes the request
coming from the same user and the session is maintained.

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 8


Cookie types
There are two types of cookies:

1. Persistent – It is valid for multiple sessions. It is not removed from the browser each time
when the user closes the browser. It is removed only if the user logs out or signs out.
2. Non-persistent – It is valid for a single session only. It is removed each time the user closes the
browser.

Constructors
Cookie()
Cookie(String name, String value)

Commonly used methods of Cookie class

Method Description

public String getName() Get the name of the cookie.

public String getValue() Get the value of the cookie

public void setName(String name) Sets the name

public void setValue(String value) Sets the value

public void setMaxAge(int expiry) Sets the max age of the cookie in seconds

How to create cookie object


Cookie ck = new Cookie("user","Nitin");
response.addCookie(ck); //adding cookie in the response object

Reference Site : Cookies in Servlets - Java Training School

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 9


2. Hidden Form Field

1. Hidden form field is another technique which is used for session tracking of a client. In this
technique, a hidden field is used to store client state.
2. Hidden form field can also be used to store session information for a particular client.
3. Hidden form field is used to store session information of a client.
4. Hidden form fields are used to pass data from the client to the server without displaying it to the
user.

How to use hidden field


<input type=”hidden” name=”userName” value=”Nitin”>

Hidden form field example


index.html
<html>
<body>
<form method="post" action="servletOne">
Name:<input type="text" name="user" /><br/>
<input type="submit" value="submit"> </form>
</body>
</html>

ServletOne.java

import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/index")
public class ServletOne extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("user");
out.print("Welcome " + userName);
out.print("<form action='servletTwo'>");
out.print("<input type='hidden' name='uname' value='" + userName + "'><br>");
out.print("<input type='submit' value='Get Value from Hidden Field'>");
out.print("</form>");
out.close();
}
catch (Exception e)
{
System.out.println(e);
}

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 10


}
}
ServletTwo.java
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ServletTwo extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) {


try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// Get the value from the hidden field


// hidden field name is uname
String uname = request.getParameter("uname");
out.print("Hello " + uname);
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

Web.xml
<web-app>
<servlet>
<servlet-class>ServletOne</servlet-class>
<servlet-name>servletOne</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>servletOne</servlet-name>
<url-pattern>/servletOne</url-pattern>
</servlet-mapping>
<servlet>
<servlet-class>ServletTwo</servlet-class>
<servlet-name>servletTwo</servlet-name>
</servlet>
<servlet-mapping>
<servlet-name>servletTwo</servlet-name>
<url-pattern>/servletTwo</url-pattern>
</servlet-mapping>
</web-app>

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 11


URL Rewriting END SEM - 4M

● URL rewriting is a technique used to maintain session state between a client and a server without
relying on cookies.
● Url rewriting is a process of appending or modifying any url structure while loading a page.
● In Java Servlets, URL rewriting is commonly used to pass session information when cookies are
not supported or disabled
● URL rewriting involves appending session information directly to the URL
● If your browser does not support cookies, URL rewriting provides you with another session
tracking alternative.

In URL rewriting, we append a query string to the URL


Example of

http://demo/servlet?Name=Nitin&Address=Nashik

Query string is a name value pair separated using an equal = sign, a name/value pair is separated
from another name/value pair using the ampersand (&). Query string always should start from
Question mark (?). From a Servlet, we can use getParameter(), getParameterNames() methods to
obtain a name value pair.

Example :

index.html

<html>
<body>
<form action="/FirstServlet" method="post">
Enter Personal Details:<br /> Name:<input type="text" name="name" /><br />
<input type="submit" value="go" />
/form>
</body>
</html>

FirstServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@WebServlet("/index")
public class FirstServlet extends HttpServlet {

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 12


public void doPost(HttpServletRequest request, HttpServletResponse response) {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
out.print("Welcome " + name);
out.print("<form action='servlet2?name="+name+"' method='post'> ");
out.print("Enter Contact Details:<br/>");
out.print("Address:<input type='text' name='address'/><br/>");
out.print("<input type='submit' value='go'/> ");
out.print("</form>");
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}

From the above FirstServlet.java servlet program the url rewriting is done by appending the
name information into out.print("<form action='servlet2?name="+name+"' method='post'> ");

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 13


HttpSession END SEM -05M or 8M

1. A session is simply the limited interval of time in which two systems communicate with each
other.
2. HttpSession is a Java class used in servlets to manage user sessions in a web application
3. It allows you to store user-specific data between HTTP requests, which is useful for maintaining
state and user-specific information across multiple interactions with the server.

How to create sessions with a unique session id for each user in java servlet.
For this, servlets provide an interface called ‘HttpSession’ Interface.
The following diagram explains how Http Sessions work in servlets:

Container creates a session id for each user.The container uses this id to identify the particular
user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.

Methods in HttpSession Interface


1. Creating a Session:
When a user first accesses a servlet that uses sessions, a new HttpSession object is created
automatically if one doesn't already exist. You can get this session object using the
HttpServletRequest object’s getSession() method.

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 14


Java Code :
HttpSession session = request.getSession();

2. Storing Data: You can store data in the session using setAttribute(), where the data is stored
as key-value pairs.
Java Code :
session.setAttribute("username", "Nitin");

3. Retrieving Data: To retrieve data from the session, use getAttribute() with the key used when
storing the data.
Java Code :
String username = (String) session.getAttribute("username");

4. Invalidating a Session: You can invalidate a session when it is no longer needed (e.g., when a
user logs out) using the invalidate() method.
Java Code :
session.invalidate();

5. Session Timeout: Sessions have a timeout period which can be configured in the web
application's deployment descriptor (web.xml) or programmatically. The default timeout is
usually 30 minutes. After this period of inactivity, the session will be invalidated.

Web.xml

<session-config>
<session-timeout>15</session-timeout>
</session-config>

Example of using HttpSession


In this example, we are setting the attribute in the session scope in one servlet and getting that value
from the session scope in another servlet. To set the attribute in the session scope, we have used the
setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute
method.

index.html
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 15


FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {


@WebServlet("/index")
public void doGet(HttpServletRequest request, HttpServletResponse response){
try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n = request.getParameter("userName");
out.print("Welcome "+n);

HttpSession session=request.getSession();

session.setAttribute("uname",n);

out.print("<a href='servlet2'>visit</a>");

out.close();

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

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e); }
}

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 16


web.xml
<web-app>

<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>SecondServlet</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>SecondServlet</servlet-name>
<url-pattern>/SecondServlet2</url-pattern>
</servlet-mapping>

</web-app>

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 17


Servlet capabilities,
data storage
servlets concurrency
1. Servlet concurrency is a key aspect of web application development that deals with handling
multiple requests to a servlet concurrently.
2. A Java servlet container / web server is typically multithreaded.
3. That means that multiple requests to the same servlet may be executed at the same time.
Therefore, you need to take concurrency into consideration when you implement your servlet.
4. By default servlets are not thread safe and it is a responsibility of a servlet developer to take
care of it.
Concurrency in Servlets:
● Servlets operate in a multi-threaded environment. When a request is made to a servlet, the server
creates a new thread to handle that request. This means that multiple requests can be processed
simultaneously by different threads.
● The servlet container manages the threads, and each request is handled independently. However,
this requires careful management to avoid issues like race conditions or data inconsistency.

To make sure that a servlet is thread safe, there are a few basic rules of thumb you must
follow:

Thread Safety:

● To ensure thread safety, servlets must be designed to handle concurrent access properly. This
often involves:
○ Avoiding the use of instance variables to store request-specific data, as multiple
threads might access and modify these variables simultaneously.
○ Using local variables within request-handling methods (e.g., doGet or doPost), as these
are thread-local and thus isolated from other threads.
○ Synchronizing access to shared resources, such as shared data structures or files, if they
are used.

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 18


databases (MySQL) and Java Servlets.

Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 19


Asst.Prof. Nitin D. Dhamale [AI & DS] METs IOE 20
Database (Mysql) and Java Servlet

JDBC API : is used to access tabular data stored in


relational databases like Oracle, MySQL, MS Access, etc.

JDBC DriverManager: It is the class in JDBC API.


It loads the JDBC driver in a Java application for establishing a
connection with the database.

JDBC driver provides the connection to the database.


Also, it implements the protocol for sending the query and result
between client and database.
Database (Mysql) and Java Servlet

1. Setup MySQL Database


First, ensure you have MySQL installed and running.
Create a database and table for your application.
For example, let's create a database called testdb and a table called users.

SQL> CREATE DATABASE testdb;

SQL>USE testdb;

SQL> CREATE TABLE users (id INT, username VARCHAR(50), password VARCHAR(50);
Database (Mysql) and Java Servlet
Establish a database connection in a Java servlet, you'll need to follow several
steps.

1. Add Required Libraries


Ensure you have the JDBC driver for your database in your project's classpath.
1. For MySQL, you'll need the MySQL Connector/J.
2. From the MySQL Connector/J add the JAR file to your project's classpath
3. MySQL Connectors provide connectivity to the MySQL server for client programs.

2. Database Configuration
1. Store your database connection details, like URL, username, and password.
2. You can do this in a properties file or directly in your servlet for simplicity (though using a properties
file is more secure).
Database (Mysql) and Java Servlet
Index.html UI interface

<html>
<head>
<title>User Registration</title>
</head><body> <h1>User Registration</h1>
<form action="UserServlet" method="post">
<body>
<input type="text" name="username" required>
<input type="password" name="password" required>
<button type="submit"> Register </button>
</form>
</body>
</html>
Create a Servlet
Create a new Servlet to handle HTTP requests and interact with the MySQL database.
Here’s a simple example of a servlet that inserts a user into the users table:

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/index")
public class UserServlet extends HttpServlet
{
private static final String JDBC_URL = "jdbc:mysql://localhost:3306/testdb";
private static final String JDBC_USER = "root"; // Your MySQL username
private static final String JDBC_PASSWORD = "password"; // Your MySQL password
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String username = request.getParameter("username");
String password = request.getParameter("password");

try
{
// Load the MySQL JDBC driver

Class.forName("com.mysql.cj.jdbc.Driver");

// Establish the connection


Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);

// Prepare the SQL statement

String sql = "INSERT INTO users (username, password) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, username);
statement.setString(2, password);
PrintWriter out = response.getWriter();
// Execute the statement
int rowsInserted = statement.executeUpdate();

if (rowsInserted > 0)
{
out.println("User registered successfully!");
} else

{
out.println("User registration failed.");
}

// Clean up
statement.close();
connection.close();
}
catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
}
University Question on XML Ask in Previous Years

Q. Explain XML with respect to XML declaration, DOM based XML Processing. 6M

Q. What is DTD? Explain with example. 5M

Q. How to apply style in XML?Explain with proper example. 8M

Q. Explain the following 8M

i)XML namespace

ii)HTTP session
XML : XML documents and vocabularies
1. XML stands for Extensible Markup Language
2. XML was designed to store and transport data
3. XML was designed to be self-descriptive
4. XML is just information wrapped in tags
5. XML Does Not Use Predefined Tags

XML Simplifies Things

● XML simplifies data sharing


● XML simplifies data transport
● XML simplifies platform changes
● XML simplifies data availability
Why we need XML?
Why xml

1. Platform Independent and Language Independent


2. The main benefit of xml is that you can use it to take data from a program like Microsoft
SQL, convert it into XML then share that XML with other programs and platforms.
3. You can communicate between two platforms which are generally very difficult.
4. The main thing which makes XML truly powerful is its international acceptance.
5. Many corporation use XML interfaces for databases, programming, office application mobile
phones and more. It is due to its platform independent feature.
XML declaration & Vocabularies
Components of the XML Declaration:
1. XML declaration, specifies the version of XML being used, as well as the character encoding scheme.
This declaration, if present, must be the first line of the file.
2. Version: This specifies the version of XML. The most common version is 1.0.
3. Encoding: This indicates the character encoding used in the document, such as UTF-8 or ISO-8859-1. If
omitted, UTF-8 is assumed.
4. XML documents create a hierarchical structure looks like a tree so it is known as XML Tree that starts at
"the root" and branches to "the leaves".
5. XML elements :
a. The logical structure of an XML file requires that all data in the file be encapsulated within an XML
element called the root element or document element.
b. The root element contains other elements that define the different parts of the XML document.
c. The elements in an XML document form a document tree. The tree starts at the root and branches to
the lowest level of the tree.
d. All XML elements must be properly terminated for an XML file to be considered well-formed.
XML Entities

1. XML entities are special placeholders that represent characters that have specific meanings in
XML syntax or characters that cannot be easily typed.
2. They help ensure that the document is well-formed.
3. These are standard entities defined by XML that represent special characters:
All elements can have sub elements (child elements).

<root>

<child>

<subchild>.....</subchild>

</child>

</root>
XML declaration
XML declaration
XML example
The following is an example of a simple XML file:

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


Root Element
<library>
<book>
<title>The Fire Next Time</title>
<author>Baldwin, James</author>
</book>
<book>
<title>Beloved</title>
<author>Morris, Toni</author>
</book>
<book>
<title>The Messiah of Stockholm</title>
<author>Ozick, Cynthia</author>
</book>
</library>
XML Namespaces
XML DTD
Internal DTD
External DTD
DOM based XML processing
1. The XML DOM defines a standard way for accessing and manipulating XML
documents.
2. It presents an XML document as a tree-structure.
3. The XML DOM is a standard for how to get, change, add, or delete XML
elements.
Programming Interface

 The DOM models XML as a set of node objects.

 The nodes can be accessed with JavaScript or other programming languages.

The programming interface to the DOM is defined by a set standard properties and
methods.

1. Properties are often referred to as something that is (i.e. nodename is "book").

2. Methods are often referred to as something that is done (i.e. delete "book").
XML DOM Properties
These are some typical DOM properties:

x.nodeName - the name of x


x.nodeValue - the value of x
x.parentNode - the parent node of x
x.childNodes - the child nodes of x
x.attributes - the attributes nodes of x

XML DOM Methods


x.getElementsByTagName(name) - get all elements with a specified tag name
x.appendChild(node) - insert a child node to x
x.removeChild(node) - remove a child node from x

In the list above, x is a node object.


DOM parser :
A DOM parser maps an XML document into such a tree rooted at a Document node, upon
which the application can search for nodes, read their information, and update the contents
of the nodes.
childNodes 0
<bookstore>
<book> nodeValue
<title>Let C</title>
<author>Kanetkar</author>
<year>2003</year>
</book>
<book> childNodes 1
<title>Web Technology</title>
<author>Rajesh</author>
<year>2005</year>
</book>
</bookstore>
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var parser, xmlDoc;
var text = "<bookstore><book>" +"<title>Everyday Italian</title>" +"<author>Giada De
Laurentiis</author>" +"<year>2005</year>" +"</book>"+
"<book><title>NDD</title>" +
"<author>Dhamale</author>" +
"<year>2005</year>" +
"</book></bookstore>";
parser = new DOMParser();
xmlDoc = parser.parseFromString(text,"text/xml");
document.getElementById("demo").innerHTML =
xmlDoc.getElementsByTagName("author")[1].childNodes[0].nodeValue;
</script></body>
</html>
How to apply style in XML? Explain with proper example
XML stands for Extensible Markup Language.
It is a dynamic markup language. It is used to transform data from one form to
another form.
An XML file can be displayed using two ways. These are as follows :-
 Cascading Style Sheet
 Extensible Stylesheet Language Transformation

Displaying XML file using CSS :

CSS can be used to display the contents of the XML document in a clear and
precise manner.

It gives the design and style to whole XML document


Linking XML with CSS :

In order to display the XML file using CSS, link XML file with CSS.

Below is the syntax for linking the XML file with CSS

<?xml-stylesheet type="text/css" href="name_of_css_file.css"?>


<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="Rule.css"?>
<books>
<heading>Welcome To Book </heading>
<book>
<title>Title -: Web Programming</title>
<author>Author -: Chrisbates</author>
<publisher>Publisher -: Wiley</publisher>
<edition>Edition -: 3</edition>
<price> Price -: 300</price>
</book>
<book>
<title>Title -: Internet world-wide-web</title>
<author>Author -: Ditel</author>
<publisher>Publisher -: Pearson</publisher>
<edition>Edition -: 3</edition>
<price>Price -: 400</price>
</book>
</books>
Rule.css
books {
color: white;
background-color : gray;
width: 100%;
}
heading {
color: green;
font-size : 40px;
background-color : powderblue;
}
heading, title, author, publisher, edition, price {
display : block;
}
title {
font-size : 25px;
font-weight : bold;
}
Output
AJAX: Introduction
1. AJAX = Asynchronous JavaScript And XML
2. AJAX is not a programming language.
3. AJAX allows web pages to be updated asynchronously by exchanging data with a web
server behind the scenes. This means that it is possible to update parts of a web page,
without reloading the whole page.
4. AJAX just uses a combination of:
a. A browser built-in XMLHttpRequest object (to request data from a web
server)
b. JavaScript and HTML DOM (to display or use the data)
Working of AJAX.
Working of AJAX.

1. An event occurs in a web page (the page is loaded, a button is clicked)


2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

You might also like