Java Servlet
Java Servlet
Prepared By
Servlet:
XML:
● Servlet architecture overview,
● Servlet life cycle, ● XML documents
● A “Hello World” servlet, and vocabularies,
● Servlets generating dynamic ● XML declaration, AJAX:
content, ● XML Namespaces, • Introduction,
● parameter data, ● DOM based XML processing, • Working of AJAX.
● sessions, cookies, URL ● transforming XML
rewriting, documents,
● other Servlet capabilities, ● DTD: Schema,
● data storage, Servlets elements, attributes.
concurrency, databases
(MySQL) and Java Servlets.
SERVLETs
Java Servlets
Servlet
● 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.
● HowCookie 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- URLRewriting
● 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- URLRewriting
● 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- URLRewriting
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- URLRewriting
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
● Two threads
running in Hello
Counter concurrently.
● The initial value of
visits is assumed to be
17.
Thread Synchronization
XML
• XML is a software- and hardware-independent tool for storing and transporting data.
• What is XML?
MR. A. N. GHARU 47
XML Does Not DO Anything
• This note is a note to Tove from Jani, stored as XML::
• <note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
• The XML above is quite self-descriptive:
• It has sender information.
• It has receiver information
• It has a heading
• It has a message body. MR. A. N. GHARU 48
XML Properties
Data Data
Transfer
Solution Transfer
XML
Why we need XML?
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 Vs HTML
XML Syntax & Example
DTD
A DTD defines the structure and the legal elements and attributes of an XML
document
Types of DTD
Internal External
Internal DTD- DTD is declared inside the XML file, and
wrapped inside the <!DOCTYPE> definition
2. Attributes
Attributes provide extra information about elements.
Attributes are always placed inside the opening tag of an element. Attributes always come in name/value pairs. The
following "img" element has additional information about a source file:
<img src="computer.gif" />
The name of the element is "img". The name of the attribute is "src". The value of the attribute is "computer.gif".
Since the element itself is empty it is closed by a " /".
BUILDING BLOCK OF XML
3. Entities
Some characters have a special meaning in XML, like the less than sign (<) that defines the start of an XML tag.
Most of you know the HTML entity: " ". This "no-breaking-space" entity is used in HTML to insert an extra
space in a document. Entities are expanded when a document is parsed by an XML parser.
5. CDATA
• CDATA means character data.
• CDATA is text that will NOT be parsed by a parser. Tags inside the text will NOT be treated as markup and
entities will not be expanded.
DTD point of view - XML documents
XML schema is a language which is used for expressing constraint about XML
documents. There are so many schema languages which are used now a days for
example : XSD (XML schema definition).
<?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 doesn’t support array.
XML file sizes are usually very large due to its verbose nature, it is totally dependent on who is writing it.
function
<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"
request.onreadystatechange=getInfo; value="ShowTable"
onClick="sendInfo()">
request.open("GET",url,true);
</form>
request.send();
<span id="amit"> </span>
} </body>
AJAX Example- index.jsp
<%
int n=Integer.parseInt(request.getParameter("val"));
for(int i=1;i<=10;i++)
out.print(i*n+"<br>");
%>
AJAX Example output
References
• https://www.javatpoint.com/cookies-in-servlet
• https://www.javatpoint.com/hidden-form-field-in-session- tracking
• https://www.studytonight.com/servlet/hidden-form-field.php
• https://www.studytonight.com/servlet/url-rewriting-for- session-
management.php
• https://www.tutorialspoint.com/jsp/jsp_overview.htm
• https://www.javatpoint.com/jsp-tutorial
• https://www.studytonight.com/jsp/introduction-to-jsp.php
• https://www.studytonight.com/jsp/creating-a-jsp-page.php
• https://www.studytonight.com/jsp/jsp-scripting-element.php
• https://www.javatpoint.com/java-jdbc
• https://www.javatpoint.com/jsp-include-action
Thank You
[email protected]
Blog : anandgharu.wordpress.com