Professional Documents
Culture Documents
Explain types of DTD’s and List out the advantages of schema over
DTD?
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]>
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">
XSD is extensible. You can derive new elements from the existing elements.
DTD is not extensible.
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.
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>
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?
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.../>
Attribute declaration:
DTD file
<!ELEMENT hr EMPTY>
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.
Let’s jump to the SAX parser example program now, I will explain different
features in detail later on.
employees.xml
We will use SAX parser to parse this XML and create a list of Employee
object.
package com.journaldev.xml;
@Override
public String toString() {
return "Employee:: ID="+this.id+" Name=" + this.name + "
Age=" + this.age + " Gender=" + this.gender +
" Role=" + this.role;
}
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;
@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.
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 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 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
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
<table>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
The <tr> element defines a table row, the <th> element defines a table
header, and the <td> element defines a table cell.
Browser Support
Element
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 main advantage of frames is that it allows the user to view multiple documents
within a single Web page.
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.
<!DOCTYPE html>
<html>
<body style="background-color:black;">
</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.
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:
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
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.
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>");
}
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>");
out.println("</body></html>");
}
}
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
// Database credentials
static final String USER = "root";
static final String PASS = "password";
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);
//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?
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.
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.
Disadvantages of CGI
There are many problems in CGI technology:
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:
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.
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:
Servlet
ServletRequest
ServletResponse
ServletConfig
ServletContext
SingleThreadModel
RequestDispatcher
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener
Filter
FilterConfig
FilterChain
GenericServlet
ServletInputStream
ServletOutputStream
ServletException
ServletRequestWrapper
ServletRequestEvent
ServletResponseWrapper
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
UnavailableException
HttpSession
HttpServletRequest
HttpServletResponse
HttpSessionAttributeListener
HttpSessionListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext
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>
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>
....
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/
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