Opic: Servlets, XML & Ajax
Opic: Servlets, XML & Ajax
Unit- III
Topic:
Servlets, XML & Ajax-
Syllabus
Servlet:
XML:
● Servlet architecture overview,
● XML documents and
● Servlet life cycle,
vocabularies,
● A “Hello World” servlet, AJAX:
● XML declaration,
● Servlets generating dynamic content,
● XML Introduction,
● Namespaces,
● parameter data,
● DOM ● based
Working
XMLofprocessing,
AJAX.
● sessions, cookies, URL rewriting,
● transforming XML documents,
● other Servlet capabilities,
● DTD: Schema, elements,
● data storage, Servlets concurrency,
attributes.
databases (MySQL) and Java Servlets.
Servlets
Java Servlets
Servlet
● 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.
Servlets Architecture
Servlet Life Cycle Diagram
● 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 response back to the client.
● When server receives a request for a servlet, the service() method checks the HTTP request type (GET, POST)
and calls doGet, doPost, methods as appropriate.
● 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.
A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() 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, and
perform other such cleanup activities.
● After the destroy() method is called, the servlet object is marked for garbage collection.
import java.io.*;
import javax.servlet.*; {
import javax.servlet.http.*; response.setContentType("text/html");
public class HelloWorld extends HttpServlet { PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
public void init() throws ServletException { } }
public void destroy() { }
}
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
Reading Form Data using Servlet
● It requires 2 files:
○ 1. HTML (s1.html)File
○ 2. Servlet (s2.java) File
● First Run HTML file and after clicking on submit button it will run
servel(.java) file.
Example 2-
To read data from HTML file and print that .
S1.html (html code)
<html>
<form method=“post” action=“s2”>
Enter Your Name
<input type=text name=“t1”>
<br>
<input type=“submit” value=“submit”>
</form>
</body>
</html>
Example 2-
To read data from HTML file and print that .
S2.java (Servlet Code)
import java.io.*;
import javax.servlet.*;
public class s2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
String a= request.getParameter("t1");
PrintWriter out= response.getWriter();
out.print("<br>Your Name is: "+a);
}
}
Session Tracking (Management)
● Session Tracking is a way to maintain state (data) of an user. It is also known as session management
in servlet.
● Http protocol is a stateless so we need to maintain state using session tracking techniques.
● Each time user requests to the server, server treats the request as the new request.
● So we need to maintain the state of an user to recognize to particular user.
Cookies
Hidden Form Field
URL Rewriting
HttpSession
Session Tracking- Using Cookies
● A cookie is a small piece of information that is persisted between the multiple client requests.
● A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
● How Cookie works
○ In cookies technique, we add cookie with response from the servlet. So cookie is stored in the cache
of the browser. After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.
Session Tracking- Using Cookies
● Types of Cookie
○ Non-persistent cookie
○ Persistent cookie
● Non-persistent cookie
○ It is valid for single session only. It is removed each time when user closes the browser.
● Persistent cookie
○ It is valid for multiple session . It is not removed each time when user closes the browser.
It is removed only if user logout or sign out.
Session Tracking- Using Cookies
● Advantage of Cookies
○ Simplest technique of maintaining the state.
○ Cookies are maintained at client side.
● Disadvantage of Cookies
○ It will not work if cookie is disabled from the browser.
○ Only textual information can be set in Cookie object.
Session Tracking- Using Cookies
? index.html
Servlet2.java
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}
Session Tracking- URL Rewriting
● If the client has disabled cookies in the browser then session management using cookie wont work.
● In that case URL Rewriting can be used as a backup. URL rewriting will always work.
● In URL rewriting, a token(parameter) is added at the end of the URL.
● The token consist of name/value pair separated by an equal(=) sign.
● For Example:
Session Tracking- URL Rewriting
● When the User clicks on the URL having parameters, the request goes to the Web Container with extra bit of
information at the end of URL.
● The Web Container will fetch the extra part of the requested URL and use it for session management.
● The getParameter() method is used to get the parameter value at the server side.
● Advantage of URL Rewriting
○ It will always work whether cookie is disabled or not (browser independent).
○ Extra form submission is not required on each pages.
● Disadvantage of URL Rewriting
○ It will work only with links.
○ It can send only textual information.
Session Tracking- URL Rewriting
index.html
Validate.java
{
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234")) {
response.sendRedirect("First?user_name="+name+"");
}
Session Tracking- URL Rewriting
First.java
{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user = request.getParameter("user_name");
out.println("Welcome "+user);
}
}
Servlet- Data Storage
XML
Data Data
Transfer
Solution Transfer
XML
Why we need XML?
Machine-1 Machine-2 Machine-3 Machine-4
Data Data
Transfer
Solution Transfer
XML HTML
Is Case Sensitive Is not Case Sensitive
Has user defined tags Has its own predefined tags
Used for Transferring Data Used for Displaying Data
Closing tags are mandatory Closing tags are not always mandatory
It is Dynamic It is Static
XML preserve white spaces HTML does not preserve white spaces
XML Syntax & Example
<?xml version="1.0" encoding="UTF-8"?>
<note>
<root>
<child> <to>Amisha</to>
<subchild>.....</subchild> <from>Janvi</from>
</child> <heading>Reminder</heading>
</root> <body>Don't forget Meeting!</body>
</note>
XML Tree Structure
<?xml version="1.0" encoding="UTF-8"?>
<bookstore>
<book category="cooking">
<title lang="en">Everyday Italian</title>
<author>Giada De Laurentiis</author>
<year>2005</year>
<price>30.00</price>
</book>
<book category="children">
<title lang="en">Harry Potter</title>
<author>J K. Rowling</author>
<year>2005</year>
<price>29.99</price>
</book>
</bookstore>
XSL
T
• XSLT (eXtensible Stylesheet Language Transformations) is
the
recommended style sheet language for XML.
• XSLT is far more sophisticated than CSS.
• With XSLT you can add/remove elements and attributes to or
from the output file.
• You can also rearrange and sort elements, perform tests and
make decisions about which elements to hide and display, and
a lot more.
Displaying XML with XSLT
<xsl:for-each select="class/student">
<tr>
<td><xsl:value-of select = "@rollno"/></td>
<td><xsl:value-of select = "firstname"/></td>
<td><xsl:value-of select = "lastname"/></td>
</tr>
</xsl:for-each> </table>
</body> </html>
</xsl:template>
Step 3: Link the XSLT Document
to the XML Document
• <?xml version = "1.0"?>
• <?xml-stylesheet type = "text/xsl" href =
"students.xsl"?>
• <class>
• ...
• </class>
Step 4: View the XML Document
in Internet Explorer
<?xml version = "1.0"?>
<?xml-stylesheet type = "text/xsl" href =
"students.xsl"?>
<class>
<student rollno = "393">
<firstname>Dinkar</firstname>
<lastname>Kad</lastname>
</student>
<student rollno = "493">
<firstname>Vaneet</firstname>
<lastname>Gupta</lastname>
</student>
</class>
Output
Web Technology
Unit- III
Topic:
DTD- Document Type Defination
DTD
DTD
Types of DTD
Internal External
Internal DTD- DTD is declared inside the XML file, and wrapped
inside the <!DOCTYPE> definition
❏ !DOCTYPE note defines that the root element of this document is note
❏ !ELEMENT note defines that the note element must contain four elements:
"to,from,heading,body"
❏ !ELEMENT to defines the to element to be of type "#PCDATA"
❏ !ELEMENT from defines the from element to be of type "#PCDATA"
❏ !ELEMENT heading defines the heading element to be of type "#PCDATA"
❏ !ELEMENT body defines the body element to be of type "#PCDATA"
External DTD- Requires 2 Files
1> XML and 2>DTD
XML File
❏ An XML Schema describes the structure of an XML document, just like a DTD.
❏ XML Schema is an XML-based alternative to DTD
❏ XML Schemas are More Powerful than DTD
❏ XML Schemas are written in XML
❏ XML Schemas are extensible to additions
❏ XML Schemas support data types
❏ XML Schemas support namespaces
XML Schema- Example
<?xml version="1.0"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="emp">
<xs:complexType>
<xs:sequence>
<xs:element name="name" type="xs:string"/>
<xs:element name="address" type="xs:string"/>
<xs:element name="salary" type="xs:int"/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>
XML Schema Example Explained
SGML syntax is used for DTD. XML is used for writing XSD.
Advantages
XML is platform independent and programming language independent, thus it can be used on any
system and supports the technology change
It supports Unicode, allowing almost any information in any written human language to be
communicated
The data stored and transported using XML can be changed at any point of time without affecting the
data presentation
XML allows validation using DTD and Schema. This validation ensures that the XML document is free
from any syntax error.
It is XML simplifies data sharing between various systems because of its platform independent nature
XML
Advantages & Limitations(Disadvantages)
Disadvantages
XML syntax is verbose and redundant compared to other text-based data transmission formats such as
JSON.
The redundancy in syntax of XML causes higher storage and transportation cost when the volume of
data is large.
XML document is less readable compared to other text-based data transmission formats such as JSON.
XML file sizes are usually very large due to its verbose nature, it is totally dependent on who is writing it.
Web Technology
Unit- III
Topic:
Ajax
AJAX
● What is AJAX?
● AJAX cannot work independently. It is used in combination with other technologies to create interactive webpages.
● JavaScript
○ Loosely typed scripting language.
○ JavaScript function is called when an event occurs in a page.
○ Glue for the whole AJAX operation.
● DOM
○ API for accessing and manipulating structured documents.
○ Represents the structure of XML and HTML documents.
● CSS
○ Allows for a clear separation of the presentation style from the content and may be changed programmatically by JavaScript
● XMLHttpRequest
○ JavaScript object that performs asynchronous interaction with the server.
AJAX – Real Time Examples
Here is a list of some famous web applications that make use of AJAX.
● Google Maps
○ A user can drag an entire map by using the mouse, rather than clicking on a button.
● Google Suggest
○ As you type, Google offers suggestions. Use the arrow keys to navigate the results.
● Gmail
○ Gmail is a webmail built on the idea that emails can be more intuitive, efficient, and useful.
● Yahoo Maps (new)
○ Now it's even easier and more fun to get where you're going!
How AJAX Works
AJAX Processing Steps
function getInfo(){
<html>
if (request.readyState==4) {
<head>
var val=request.responseText;
<script>
document.getElementById('amit').innerHTML=val;
var request;
}
}
function sendInfo() { </script>
var v=document.f1.t1.value; </head>
var url="index.jsp?val="+v;
<body>
if(window.XMLHttpRequest){ <h1>This is an example of ajax</h1>
request=new XMLHttpRequest(); <form name=“f1">
} <input type="text" name="t1">
<input type="button" value="ShowTable"
onClick="sendInfo()">
request.onreadystatechange=getInfo;
</form>
request.open("GET",url,true);
<span id="amit"> </span>
request.send(); </body>
} </html>
AJAX Example- index.jsp
<%
int n=Integer.parseInt(request.getParameter("val"));
for(int i=1;i<=10;i++)
out.print(i*n+"<br>");
%>
AXAX Example output