You are on page 1of 36

1. What is DTD?

Explain types of DTD’s and List out the advantages of schema over
DTD?

XML Document Type Declaration, commonly known as DTD, is a way to describe


precisely the XML language. DTDs check the validity of structure and vocabulary of
an XML document against the grammatical rules of the appropriate XML language.
The following diagram represents that a DTD is used to structure the XML
document −

Syntax
Basic syntax of a DTD is as follows −
<!DOCTYPE element DTD identifier
[
declaration1
declaration2
........
]>

Types
DTD can be classified on its declaration basis in the XML document, such as −
 Internal DTD
 External DTD
When a DTD is declared within the file it is called Internal DTD and if it is declared
in a separate file it is called External DTD.
An XML DTD can be either specified inside the document, or it can be kept in a
separate document and then the document can be linked to the DTD document to
use it.

Internal DTD
A DTD is referred to as an internal DTD if elements are declared within the XML
files. To reference it as internal DTD, standalone attribute in XML declaration must
be set to yes. This means the declaration works independent of external source.
Syntax
The syntax of internal DTD is as shown −
<!DOCTYPE root-element [element-declarations]>

where root-element is the name of root element and element-declarations is where


you declare the elements.

External DTD
In external DTD elements are declared outside the XML file. They are accessed by
specifying the system attributes which may be either the legal .dtd file or a valid
URL. To reference it as external DTD, standalone attribute in the XML declaration
must be set as no. This means, declaration includes information from the external
source.
Syntax
Following is the syntax for external DTD −
<!DOCTYPE root-element SYSTEM "file-name">

where file-name is the file with .dtd extension.


Advantages of XSD over DTD

 XSD is extensible. You can derive new elements from the existing elements.
DTD is not extensible.

 XSD is defined in XML. It does not require intermediate processing by a


parser. DTD is not defined in XML. You need separate parsers for DTD and
XML.

 XSD supports data types. You can restrict the content of an element. DTD
does not support data types. Therefore, you cannot restrict the content of an
element.
 XSD supports default values. You can specify default values of the elements.
You cannot specify the default values of elements in DTD.

 XSD supports references to external XML schemas. You can include or


import more than one XML schema within an XML schema. You cannot
include other DTDs within a DTD.

2. What are the different XSLT elements? Give an example

Element Description Example


apply- Applies a template
templates rule to the current <xsl:apply-templates/>
element or to the
current element's
child nodes
choose Used in
conjunction with
<when> and <xsl:choose>

<otherwise> to </xsl:choose>
express multiple
conditional tests
for-each Loops through
each node in a
specified node set <xsl:for-each
select="input[@name=$name]">

</xsl:for-each>

if Contains a
template that will
be applied only if a
specified condition <xsl:if
test="$type='text' or
is true $type='password'">

</xsl:if>

otherwise Specifies a default


<xsl:otherwise>
action for the

<choose> element </xsl:otherwise>

stylesheet Defines the root


element of a style <xsl:stylesheet>

sheet </xsl:stylesheet>
template
Rules to apply
<xsl:template match="//input">
when a specified

node is matched </xsl:template>

variable Declares a local or


global variable <xsl:variable name="type"
select="@type"/>

when Specifies an action


for the <choose> <xsl:when test="$type='radio'">

element
</xsl:when>

call-template Calls a named


template <xsl:call-template
name="lib:make-elem">

import Imports the


contents of one <xsl:import
href="..\Library\FuncLib.xslt"/>
style sheet into
another. Note: An
imported style
sheet has lower
precedence than
the importing style
sheet
output Defines the format
of the output <xsl:output method="xml" omit-
xml-declaration="yes"
document
encoding="UTF-8"/>

param Declares a local or


global parameter <xsl:param name="elem-name"/>

text Writes literal text


to the output <xsl:text>ClaimNumber
ClaimSeqNumber</xsl:text>

value-of Extracts the value


of a selected node <xsl:value-of select="$s"/>

with-param Defines the value


of a parameter to <xsl:with-param name="elem-name"
be passed into a
template select="'hma:ClaimNumber'"/>

3.What are the different types of XML elements? How can you declare attributes in
XML? Give an example.
or

6. Define XML? How can you declare attributes in XML with example?

Extensible Markup Language is a markup language that


defines a set of rules for encoding documents in a format that is
both human-readable and machine-readable.

XML elements can be defined as building blocks of an XML. Elements can behave


as containers to hold text, elements, attributes, media objects or all of these.
Each XML document contains one or more elements, the scope of which are either
delimited by start and end tags, or for empty elements, by an empty-element tag.

Syntax
Following is the syntax to write an XML element −
<element-name attribute1 attribute2>
....content
</element-name>

where,
 element-name is the name of the element. The name its case in the start
and end tags must match.
 attribute1, attribute2 are attributes of the element separated by white
spaces. An attribute defines a property of the element. It associates a name
with a value, which is a string of characters. An attribute is written as −
name = "value"
name is followed by an = sign and a string value inside double(" ") or single(' ')
quotes.

Empty Element
An empty element (element with no content) has following syntax −
<name attribute1 attribute2.../>

Following is an example of an XML document using various XML element −


<?xml version = "1.0"?>
<contact-info>
<address category = "residence">
<name>Tanmay Patil</name>
<company>TutorialsPoint</company>
<phone>(011) 123-4567</phone>
</address>
</contact-info>

XML Elements Rules


Following rules are required to be followed for XML elements −
 An element name can contain any alphanumeric characters. The only
punctuation mark allowed in names are the hyphen (-), under-score (_) and
period (.).
 Names are case sensitive. For example, Address, address, and ADDRESS
are different names.
 Start and end tags of an element must be identical.
 An element, which is a container, can contain text or elements as seen in the
above example.

Attribute declaration:

DTD file

<!ELEMENT hr EMPTY>

<!ATTLIST hr width CDATA '100'>

<!ATTLIST hr color CDATA>

Xml data
<hr width=“80” color=“pink” />

5. What is an XML SAX? How SAX parses the XML file? Explain with suitable example.
SAX Parser in java provides API to parse XML documents. SAX parser
is different from DOM parser because it doesn’t load complete XML
into memory and read xml document sequentially.

SAX Parser
javax.xml.parsers.SAXParser provides method to parse XML document using
event handlers. This class implements XMLReader interface and provides
overloaded versions of parse() methods to read XML document from File,
InputStream, SAX InputSource and String URI.
The actual parsing is done by the Handler class. We need to create our
own handler class to parse the XML document. We need to
implement org.xml.sax.ContentHandler interface to create our own handler
classes. This interface contains callback methods that receive notification
when an event occurs. For example StartDocument, EndDocument,
StartElement, EndElement, CharacterData etc.
org.xml.sax.helpers.DefaultHandler provides default implementation
of ContentHandler interface and we can extend this class to create our
own handler. It’s advisable to extend this class because we might need
only a few of the methods to implement. Extending this class will keep our
code cleaner and maintainable.

SAX parser Example

Let’s jump to the SAX parser example program now, I will explain different
features in detail later on.

employees.xml

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


<Employees>
<Employee id="1">
<age>29</age>
<name>Pankaj</name>
<gender>Male</gender>
<role>Java Developer</role>
</Employee>
<Employee id="2">
<age>35</age>
<name>Lisa</name>
<gender>Female</gender>
<role>CEO</role>
</Employee>
<Employee id="3">
<age>40</age>
<name>Tom</name>
<gender>Male</gender>
<role>Manager</role>
</Employee>
<Employee id="4">
<age>25</age>
<name>Meghna</name>
<gender>Female</gender>
<role>Manager</role>
</Employee>
</Employees>
So we have a XML file stored somewhere in file system and by looking at it,
we can conclude that it contains list of Employee. Every Employee
has id attribute and fields age, name, gender and role.

We will use SAX parser to parse this XML and create a list of Employee
object.

Here is the Employee object representing Employee element from XML.

package com.journaldev.xml;

public class Employee {


private int id;
private String name;
private String gender;
private int age;
private String role;

public int getId() {


return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}

@Override
public String toString() {
return "Employee:: ID="+this.id+" Name=" + this.name + "
Age=" + this.age + " Gender=" + this.gender +
" Role=" + this.role;
}

Let’s create our own SAX Parser Handler class


extending DefaultHandler class.

package com.journaldev.xml.sax;

import java.util.ArrayList;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.journaldev.xml.Employee;

public class MyHandler extends DefaultHandler {

// List to hold Employees object


private List<Employee> empList = null;
private Employee emp = null;
private StringBuilder data = null;

// getter method for employee list


public List<Employee> getEmpList() {
return empList;
}
boolean bAge = false;
boolean bName = false;
boolean bGender = false;
boolean bRole = false;

@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {

if (qName.equalsIgnoreCase("Employee")) {
// create a new Employee and put it in Map
String id = attributes.getValue("id");
// initialize Employee object and set id
attribute
emp = new Employee();
emp.setId(Integer.parseInt(id));
// initialize list
if (empList == null)
empList = new ArrayList<>();
} else if (qName.equalsIgnoreCase("name")) {
// set boolean values for fields, will be
used in setting Employee variables
bName = true;
} else if (qName.equalsIgnoreCase("age")) {
bAge = true;
} else if (qName.equalsIgnoreCase("gender")) {
bGender = true;
} else if (qName.equalsIgnoreCase("role")) {
bRole = true;
}
// create the data container
data = new StringBuilder();
}

@Override
public void endElement(String uri, String localName,
String qName) throws SAXException {
if (bAge) {
// age element, set Employee age

emp.setAge(Integer.parseInt(data.toString()));
bAge = false;
} else if (bName) {
emp.setName(data.toString());
bName = false;
} else if (bRole) {
emp.setRole(data.toString());
bRole = false;
} else if (bGender) {
emp.setGender(data.toString());
bGender = false;
}

if (qName.equalsIgnoreCase("Employee")) {
// add Employee object to list
empList.add(emp);
}
}

@Override
public void characters(char ch[], int start, int
length) throws SAXException {
data.append(new String(ch, start, length));
}
}
MyHandler contains the list of the Employee object as a field with a getter
method only. The Employee objects are getting added in the event handler
methods. Also, we have an Employee field that will be used to create an
Employee object and once all the fields are set, add it to the employee list.

7. What are the different types of lists in HTML? Explain how these lists are created in
HTML with suitable examples.

Lists are used to group together related pieces of information so they are clearly associated with
each other and easy to read. In modern web development, lists are workhorse elements,
frequently used for navigation as well as general content.

Lists are good from a structural point of view as they help create a well-structured, more
accessible, easy-to-maintain document. They are also useful because they provide specialized
elements to which you can attach CSS styles. Finally, semantically correct lists help visitors read
your web site, and they simplify maintenance when your pages need to be updated.

The three list types


There are three list types in HTML:

 unordered list — used to group a set of related items in no particular order


 ordered list — used to group a set of related items in a specific order
 description list — used to display name/value pairs such as terms and definitions

Each list type has a specific purpose and meaning in a web page.

Unordered lists

Unordered (bulleted) lists are used when a set of items can be placed in any order. An example
is a shopping list:
 milk

 bread

 butter

 coffee beans

Although the items are all part of one list, you could put the items in any order and the list would
still make sense:

 bread
 coffee beans
 milk
 butter

You can use CSS to change the bullet to one of several default styles, use your own image, or
even display the list without bullets — we’ll look at how to do that in the Styling lists and
links article.

Unordered list markup

Unordered lists use one set of <ul></ul> tags wrapped around one or more sets
of <li></li> tags:

<ul>
<li>bread</li>
<li>coffee beans</li>
<li>milk</li>
<li>butter</li>
</ul>
Ordered lists

Ordered (numbered) lists are used to display a list of items that should be in a specific order. An
example would be cooking instructions:

1. Gather ingredients
2. Mix ingredients together
3. Place ingredients in a baking dish
4. Bake in oven for an hour
5. Remove from oven
6. Allow to stand for ten minutes
7. Serve

If the list items were moved around into a different order, the information would no longer make
sense:

1. Gather ingredients
2. Bake in oven for an hour
3. Serve
4. Remove from oven
5. Place ingredients in a baking dish
6. Allow to stand for ten minutes
7. Mix ingredients together
Ordered lists can be displayed with several sequencing options. The default in most browsers is
decimal numbers, but there are others available:

 Letters
o Lowercase ascii letters (a, b, c…)
o Uppercase ascii letters (A, B, C…).
o Lowercase classical Greek: (έ, ή, ί…)

 Numbers
o Decimal numbers (1, 2, 3…)
o Decimal numbers with leading zeros (01, 02, 03…)
o Lowercase Roman numerals (i, ii, iii…)
o Uppercase Roman numerals (I, II, III…)
o Traditional Georgian numbering (an, ban, gan…)
o Traditional Armenian numbering (mek, yerku, yerek…)

As with unordered lists, you can use CSS to change the style of your ordered lists. See Styling
lists and links for more information.

Description lists

Description lists (previously called definition lists, but renamed in HTML5) associate specific


names and values within a list. Examples might be items in an ingredient list and their
descriptions, article authors and brief bios, or competition winners and the years in which they
won. You can have as many name-value groups as you like, but there must be at least one name
and at least one value in each pair.

Description lists are flexible: you can associate more than one value with a single name, or vice
versa. For example, the term “coffee” can have several meanings, and you could show them one
after the other:

coffee

a beverage made from roasted, ground coffee beans


a cup of coffee
a social gathering at which coffee is consumed
a medium to dark brown colour

Or, you can associate more than one name with the same value. This is useful to show variations
of a term, all of which have the same meaning:

soda
pop
fizzy drink
cola

a sweet, carbonated beverage

8. Describe the tables tags with suitable examples.


HTML <table> Tag
Example
A simple HTML table, containing two columns and two rows:

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
</table>

Definition and Usage


The <table> tag defines an HTML table.

An HTML table consists of one <table> element and one or more <tr>, <th>,


and <td> elements.

The <tr> element defines a table row, the <th> element defines a table
header, and the <td> element defines a table cell.

An HTML table may also include <caption>, <colgroup>, <thead>, <tfoot>,


and <tbody> elements.

Browser Support
Element

<table> Yes Yes Yes Yes


Global Attributes
The <table> tag also supports the Global Attributes in HTML.

Event Attributes
The <table> tag also supports the Event Attributes in HTML.

Example
How to add collapsed borders to a table (with CSS):

<html>
<head>
<style>
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
</style>
</head>
<body>

<table>
  <tr>
    <th>Month</th>
    <th>Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

</body>
</html>

9.What are the uses of frames in HTML? Write a simple HTML script in which the home
page of your website is divided in three areas. The left vertical area displays the contents
at a glance. The right top frame is reserved for displaying the logo of the company and the
right bottom frame displays the description of the company.

The advantages of HTML frames include:

 The main advantage of frames is that it allows the user to view multiple documents
within a single Web page.

 It is possible to load pages from different servers in a single frameset.

 The concern that older browsers do not support frames can be addressed using the
<noframe> tag. This tag provides a section in an HTML document to include
alternative content for browsers without support for frames. However, it requires
that the Web designer provide two formats for one page.
 <frameset cols="*,*">
 <frame src="frame_1.html">
 <frameset rows="*,*">
 <frame src="frame_2.html">
 <frame src="frame_3.html">
 </frameset>
 </frameset>
10.What is CSS stand for? What are the different ways of using style sheets? Explain with
example
CSS is the acronym of “Cascading Style Sheets”.
CSS is a computer language for laying out and structuring web pages (HTML or XML).
This language contains coding elements and is composed of these “cascading style sheets” which
are equally called CSS files (.css).
There 3 different ways of using the cascading sheets they are:
Inline
Internal
External.
Internal CSS
Internal or embedded CSS requires you to add <style> tag in the <head>section of
your HTML document.

This CSS style is an effective method of styling a single page. However, using this
style for multiple pages is time-consuming as you need to put CSS rules to every
page of your website.
<!DOCTYPE html>
<html>
<head>
<style>
body {
background-color: blue;
}
h1 {
color: red;
padding: 60px;
}
</style>
</head>
<body>

<h1>Hostinger Tutorials</h1>
<p>This is our paragraph.</p>

</body>
</html>

External css
With external CSS, you’ll link your web pages to an external .css file, which can be
created by any text editor in your device (e.g., Notepad++).

This CSS type is a more efficient method, especially for styling a large website. By
editing one .css file, you can change your entire site at once.

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" href="styles.css">
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

Inline css
Inline CSS
Inline CSS is used to style a specific HTML element. For this CSS style, you’ll only
need to add the style attribute to each HTML tag, without using selectors.

This CSS type is not really recommended, as each HTML tag needs to be styled
individually. Managing your website may become too hard if you only use inline CSS.
However, inline CSS in HTML can be useful in some situations. For example, in
cases where you don’t have access to CSS files or need to apply styles for a single
element only.

Let’s take a look at an example. Here, we add an inline CSS to


the <p>and <h1> tag:

<!DOCTYPE html>
<html>
<body style="background-color:black;">

<h1 style="color:white;padding:30px;">Hostinger Tutorials</h1>


<p style="color:white;">Something usefull here.</p>

</body>
</html>
11.Create an HTML page which generates a registration form with following
fields(Name,Username,password,date of birth,education qualifications

<html>
<head>
<title>HTML Table</title>
</head>
<body>
<form method="" action="">
<table border="1" align="center" width="400" bgcolor="#CCCCCC" >
<caption>Registration form</caption>
<tr>
<th>Enter your first name</th>
<td><input type="text" name="fn" id="fn1" maxlength="10" title="enter your first name"
placeholder="enter your first name" required/></td>
</tr>
<tr>
<th>Enter your username name</th>
<td><input type="text"/></td>
</tr>
<tr>
<th>Enter your password</th>
<td><input type="password"/></td>
</tr>
<tr>
<th>Enter your education qualification</th>
<td><textarea rows="8" cols="20"></textarea></td>
</tr>
<tr>
<th>Select your DOB</th>
<td><input type="date"/></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Save My Data"/>
<input type="reset" value="Reset Data"/>
</td>
</tr>
</table>
</form>
</body>
</html>

12.Explain session tracking. How cookies can be used for session tracking? With example program.

Session simply means a particular interval of time.

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 are the mostly used technology for session tracking. Cookie is a key
value pair of information, sent by the server to the browser. This should be
saved by the browser in its space in the client computer. Whenever the
browser sends a request to that server it sends the cookie along with it. Then
the server can identify the client using the cookie.
In java, following is the source code snippet to create a cookie:

Cookie cookie = new Cookie(“userID”, “7456”);


res.addCookie(cookie);

Session tracking is easy to implement and maintain using the cookies.


Disadvantage is that, the users can opt to disable cookies using their browser
preferences. In such case, the browser will not save the cookie at client
computer and session tracking fails.

13.What does ServletConfig interface does?

An object of ServletConfig is created by the web container for each servlet. This object
can be used to get configuration information from web.xml file.

If the configuration information is modified from the web.xml file, we don't need to
change the servlet. So it is easier to manage the web application if any specific content
is modified from time to time.

The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.

Methods Description
getInitParameter(java.lang.String name) Returns a String containing the value of the name initia

getInitParameterNames( ) Returns the name of the servlet initialization parameter

getServletContext( ) Returns the reference of the ServletContext.

getServletName( ) Returns the name of the servlet instance.

14.How do we support both GET and POST protocol from the same Servlet give an example
program for it.

Now, we want a servlet to be able to handle both GET and POST requests.
This approach is a good standard practice when you want HTML forms to
have some flexibility in how they send data to the servlet. To do this, call
doGet inside the doPost method as shown in following code.

// doGet() handles GET request


protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
......
......
}

// doPost() handles POST request


protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response); // call doGet()
}

Now, following is the modified code of the servlet written in previous section
to handle both GET and POST request.

package com.beginwithjava.servlet;

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

@WebServlet("/entry")
public class EntryForm extends HttpServlet
{
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Add</title></head><body>");

out.println("<p>Username: "
+ request.getParameter("username") + "</p>");
out.println("<p>Password: "
+ request.getParameter("user-password")
+ "</p>");
out.println("<p>Gender: "
+ request.getParameter("sex") + "</p>");
out.println("<p>Hobbies:</p>");
String[] sports = request
.getParameterValues("sports");
out.println("<ul>");
for (String sport : sports)
{
out.println("<li>" + sport + "</li>");
}
out.println("</ul>");

out.println("<p>Address: "
+ request.getParameter("address") + "</p>");
out.println("<p>City: "
+ request.getParameter("city") + "</p>");
out.println("</body></html>");
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
doGet(request, response); // call doGet()
}
}

Displays form and process the Request in the same Servlet


Display the form, process the data, and present the result all steps can be by
the same servlet. Normal practice is to use doGet() to display the form
and doPost() to postprocess the form. You only need to ensure that you
use <form method="post">.
Following program explains this :

package com.beginwithjava.servlet;

import java.io.*;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

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

out.println("<html>");
out.println("<head><title>Table Example</title></head>");
out.println("<body>");
out.println("<h3>Add Two Numbers</h3>");
out.println("<form method='post' action='add'>");
out.println("<p>Enter First Number: <input type='text'
name='first'></p>");
out.println("<p>Enter Second Number: <input type='text'
name='second'></p>");
out.println("<p><input type='submit' value='submit'></p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
String a = request.getParameter("first");
String b = request.getParameter("second");

int sum = Integer.parseInt(a) + Integer.parseInt(b);


response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>Add</title></head><body>");

out.println("<p>The sum of " + a + " and "


+ b + " is " + sum + ".</p>");

out.println("</body></html>");

}
}

15.Write a servlet program to retrieve data from the database

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DatabaseAccess extends HttpServlet{

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// JDBC driver name and database URL


static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";

// Database credentials
static final String USER = "root";
static final String PASS = "password";

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";

String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

// Open a connection
Connection conn = DriverManager.getConnection(DB_URL,
USER, PASS);

// Execute SQL query


Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

// Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");

// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
stmt.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
}
16. What are the advantages of Servlet over CGI?

Advantages of Servlets over CGI


Servlets are server side components that provides a powerful mechanism for developing
server web applications for server side. Earlier CGI was developed to provide server side
capabilities to the web applications. Although CGI played a major role in the explosion of the
Internet, its performance, scalability and reusability issues make it less than optimal
solutions. Java Servlets changes all that. Built from ground up using Sun’s write once run
anywhere technology java servlets provide excellent framework for server side processing.

Using servlets web developers can create fast and efficient server side applications and can
run it on any servlet enabled web server. Servlet runs entirely inside the Java Virtual
Machine. Since the servlet runs on server side so it does not depend on browser
compatibility.

Servlets have a number of advantages over CGI and other


API’s. They are:
1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets can run on
any Servlet enabled web server. For example if you develop an web application in windows
machine running Java web server, you can easily run the same on apache web server (if
Apache Serve is installed) without modification or compilation of code. Platform
independency of servlets provide a great advantages over alternatives of servlets.

2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java servlets
runs very fast. These are due to the way servlets run on web server. For any program
initialization takes significant amount of time. But in case of servlets initialization takes place
first time it receives a request and remains in memory till times out or server shut downs.
After servlet is loaded, to handle a new request it simply creates a new thread and runs
service method of servlet. In comparison to traditional CGI scripts which creates a new
process to serve the request.

3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented
language which can be extended or polymorphed into new objects. So the java servlets take
all these advantages and can be extended from existing class to provide the ideal solutions.

4. Safety
Java provides very good safety features like memory management, exception handling etc.
Servlets inherits all these features and emerged as a very powerful web server extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the web server.
Servlets are also benefited with Java Security Manager.

CGI(Common Gateway Interface)


CGI technology enables the web server to call an external program and pass HTTP request
information to the external program to process the request. For each request, it starts a
new process.

Disadvantages of CGI
There are many problems in CGI technology:

 If number of clients increases, it takes more time for sending response.


 For each request, it starts a process and Web server is limited to start
processes.
 It uses platform dependent language e.g. C, C++, perl.

Advantage of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the servlet. Threads have a lot of benefits over the
Processes such as they share a common memory area, lighweight, cost of communication
between the threads are low. The basic benefits of servlet are as follows:

1. better performance: because it creates a thread for each request not process.


2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about momory leak,
garbage collection etc.
4. Secure: because it uses java language.
17. What is Servlet? Explain Servlet API

What Is a Servlet?

A servlet is a Java programming language class that is used to extend the capabilities of servers that host
applications accessed by means of a request-response programming model. Although servlets can respond to
any type of request, they are commonly used to extend the applications hosted by web servers. For such
applications, Java Servlet technology defines HTTP-specific servlet classes.

You need to use Servlet API to create servlets. There are two packages that
you must remember while using API, the javax.servlet package that contains the
classes to support generic servlet (protocol-independent servlet) and
the javax.servlet.http package that contains classes to support http servlet. You
may be wondering what is generic and http servlet, I have explained them
later in this post.

Let’s see the hierarchy of packages:

java.lang.Object
|_extended byjavax.servlet.GenericServlet
|_extended byjavax.servlet.http.HttpServlet
Every Servlet must implement the java.servlet.Servlet interface, you can do it by
extending one of the following two
classes: javax.servlet.GenericServlet or javax.servlet.http.HttpServlet. The first one is for
protocol independent Servlet and the second one for http Servlet.
How servlet works?

Generic Servlet
As I mentioned above, if you are creating a Generic Servlet then you must
extend javax.servlet.GenericServlet class. GenericServlet class has an abstract
service() method. Which means the subclass of GenericServlet should always
override the service() method.
Signature of service() method:

public abstract void service(ServletRequest request, ServletResponse response)


throws ServletException, java.io.IOException
The service() method accepts two arguments ServletRequest object and
ServletResponse object. The request object tells the servlet about the request
made by client while the response object is used to return a response back to
the client.
HTTP Servlet
If you creating Http Servlet you must extend javax.servlet.http.HttpServlet class,
which is an abstract class. Unlike Generic Servlet, the HTTP Servlet doesn’t
override the service() method. Instead it overrides one or more of the following
methods. It must override at least one method from the list below:

 doGet() – This method is called by servlet service method to


handle the HTTP GET request from client. The Get method is used
for getting information from the server
 doPost() – Used for posting information to the Server
 doPut() – This method is similar to doPost method but unlike
doPost method where we send information to the server, this
method sends file to the server, this is similar to the FTP operation
from client to server
 doDelete() – allows a client to delete a document, webpage or
information from the server
 init() and destroy() – Used for managing resources that are held
for the life of the servlet
 getServletInfo() – Returns information about the servlet, such as
author, version, and copyright.

In Http Servlet there is no need to override the service() method as this


method dispatches the Http Requests to the correct method handler, for
example if it receives HTTP GET Request it dispatches the request to the
doGet() method.
Interfaces in javax.servlet package

 Servlet
 ServletRequest
 ServletResponse
 ServletConfig
 ServletContext
 SingleThreadModel
 RequestDispatcher
 ServletRequestListener
 ServletRequestAttributeListener
 ServletContextListener
 ServletContextAttributeListener
 Filter
 FilterConfig
 FilterChain

Classes in javax.servlet package

 GenericServlet
 ServletInputStream
 ServletOutputStream
 ServletException
 ServletRequestWrapper
 ServletRequestEvent
 ServletResponseWrapper
 ServletContextEvent
 ServletRequestAttributeEvent
 ServletContextAttributeEvent
 UnavailableException

Interfaces in javax.servlet.http package

 HttpSession
 HttpServletRequest
 HttpServletResponse
 HttpSessionAttributeListener
 HttpSessionListener
 HttpSessionBindingListener
 HttpSessionActivationListener
 HttpSessionContext

Classes in javax.servlet.http package

 HttpServlet
 Cookie
 HttpSessionEvent
 HttpSessionBindingEvent
 HttpServletRequestWrapper
 HttpServletResponseWrapper
 HttpUtils

18. List out the steps that are needed for accessing a database from Servlet

 To start with basic concept, let us create a simple table and create few
records in that table as follows −

 Create Table
 To create the Employees table in TEST database, use the following steps −
 Step 1
 Open a Command Prompt and change to the installation directory as follows

 C:\>
 C:\>cd Program Files\MySQL\bin
 C:\Program Files\MySQL\bin>
 Step 2
 Login to database as follows
 C:\Program Files\MySQL\bin>mysql -u root -p
 Enter password: ********
 mysql>
 Step 3
 Create the table Employee in TEST database as follows −
 mysql> use TEST;
 mysql> create table Employees (
 id int not null,
 age int not null,
 first varchar (255),
 last varchar (255)
 );
 Query OK, 0 rows affected (0.08 sec)
 mysql>

 Create Data Records


 Finally you create few records in Employee table as follows −
 mysql> INSERT INTO Employees VALUES (100, 18, 'Zara',
'Ali');
 Query OK, 1 row affected (0.05 sec)

 mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz',
'Fatma');
 Query OK, 1 row affected (0.00 sec)

 mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid',
'Khan');
 Query OK, 1 row affected (0.00 sec)

 mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit',
'Mittal');
 Query OK, 1 row affected (0.00 sec)

 mysql>

 Accessing a Database
 Here is an example which shows how to access TEST database using
Servlet.
 // Loading required libraries
 import java.io.*;
 import java.util.*;
 import javax.servlet.*;
 import javax.servlet.http.*;
 import java.sql.*;

 public class DatabaseAccess extends HttpServlet{

 public void doGet(HttpServletRequest request,
HttpServletResponse response)
 throws ServletException, IOException {

 // JDBC driver name and database URL
 static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver";
 static final String
DB_URL="jdbc:mysql://localhost/TEST";

 // Database credentials
 static final String USER = "root";
 static final String PASS = "password";

 // Set response content type
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 String title = "Database Result";

 String docType =
 "<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

 out.println(docType +
 "<html>\n" +
 "<head><title>" + title + "</title></head>\n" +
 "<body bgcolor = \"#f0f0f0\">\n" +
 "<h1 align = \"center\">" + title + "</h1>\n");
 try {
 // Register JDBC driver
 Class.forName("com.mysql.jdbc.Driver");

 // Open a connection
 Connection conn =
DriverManager.getConnection(DB_URL, USER, PASS);

 // Execute SQL query
 Statement stmt = conn.createStatement();
 String sql;
 sql = "SELECT id, first, last, age FROM Employees";
 ResultSet rs = stmt.executeQuery(sql);

 // Extract data from result set
 while(rs.next()){
 //Retrieve by column name
 int id = rs.getInt("id");
 int age = rs.getInt("age");
 String first = rs.getString("first");
 String last = rs.getString("last");

 //Display values
 out.println("ID: " + id + "<br>");
 out.println(", Age: " + age + "<br>");
 out.println(", First: " + first + "<br>");
 out.println(", Last: " + last + "<br>");
 }
 out.println("</body></html>");

 // Clean-up environment
 rs.close();
 stmt.close();
 conn.close();
 } catch(SQLException se) {
 //Handle errors for JDBC
 se.printStackTrace();
 } catch(Exception e) {
 //Handle errors for Class.forName
 e.printStackTrace();
 } finally {
 //finally block used to close resources
 try {
 if(stmt!=null)
 stmt.close();
 } catch(SQLException se2) {
 } // nothing we can do
 try {
 if(conn!=null)
 conn.close();
 } catch(SQLException se) {
 se.printStackTrace();
 } //end finally try
 } //end try
 }
 }

 Now let us compile above servlet and create following entries in web.xml
 ....
 <servlet>
 <servlet-name>DatabaseAccess</servlet-name>
 <servlet-class>DatabaseAccess</servlet-class>
 </servlet>

 <servlet-mapping>
 <servlet-name>DatabaseAccess</servlet-name>
 <url-pattern>/DatabaseAccess</url-pattern>
 </servlet-mapping>
 ....

 Now call this servlet using URL http://localhost:8080/DatabaseAccess which


would display following response −
 Database Result

 ID: 100, Age: 18, First: Zara, Last: Ali
 ID: 101, Age: 25, First: Mahnaz, Last: Fatma
 ID: 102, Age: 30, First: Zaid, Last: Khan
 ID: 103, Age: 28, First: Sumit, Last: Mittal

20. Explain object & events models used in DHTML?

 Dynamic HTML is a collective term for a combination of Hypertext


Markup Language (HTML) tags and options that can make Web
pages more animated and interactive than previous versions of
HTML. Much of dynamic HTML is specified in HTML 4.0. Simple
examples of dynamic HTML capabilities include having the color of a
text heading change when a user passes a mouse over it and
allowing a user to "drag and drop" an image to another place on a
Web page. Dynamic HTML can allow Web documents to look and act
like desktop applications or multimedia productions.
 An object is described by its properties, methods, collections (or arrays) of
nested items, and event handlers. The Dynamic HTML features that you
associate with a document rely entirely upon the objects and the properties,
methods, and events that are supported by the browsers used by the page's
visitors. The scriptable object model of early browsers was a simple one,
with relatively few objects, and those objects had short lists of implemented
properties, methods, and events. Today's model, however, is huge, due
primarily to a greatly expanded object model for Microsoft Internet Explorer
(especially the Windows version) and, more recently, the addition of a
completely new abstract object model designed by the W3C.
https://www.slideshare.net/ReemAlattas/dynamic-html-event-model

21. Explain briefly about Event handlers in Java Script and write a java script for
sorting the elements of an array using function

http://home.ubalt.edu/abento/701/javascript/eventehand.html

https://www.geeksforgeeks.org/javascript-array-sort-method/

22. Explain onClick() and onSubmit() event handlers in JavaScriptwith example


programs?

https://www.tutorialspoint.com/javascript/javascript_events.htm

23. Explain about JavaScript dialog boxes and their usage of each one with
example?
https://www.tutorialspoint.com/javascript/javascript_dialog_boxes.htm

You might also like