Professional Documents
Culture Documents
IP IAT 2 - Ans Key
IP IAT 2 - Ans Key
Assessment – 2
Answer key
Part A
1. DOM.
A Document Object Model is an application programming interface that defines how JavaScript
programs can access and manipulate the HTML document currently displayed by a browser.
2. List out Java Script Native Objects.
Native objects are those objects supplied by JavaScript. Examples of these are String, Number,
Array, Image, Date, Math, etc. Host objects are objects that are supplied to JavaScript by the browser
environment. Examples of these are window, document, forms, etc
3. Describe the syntax of Regular Expression
A regular expression is an object that describes pattern of characters. Java script RegExp class
represents regular expressions, and both String &RegExp Methods that use regular expressions to
persorm powerful pattern matching and search-and-replace functions on text.
Syntax: var pattern = new RegExp(pattern, attributes);
Var pattern = /pattern/attributes.
Pattern – A string that specifies the pattern of the regular expression or another regular expression.
Attributes – An optional string contains any of the ‘g’, ‘I’, and ‘m’ attributes specifies global, case-
insensitive and multi line matches respectively.
4. Define Exception handling in java Script.
There are three types of errors in programming: (a) Syntax Errors, (b) Runtime Errors, and (c) Logical
Errors.
Syntax errors, also called parsing errors, occur at compile time in traditional programming languages
and at interpret time in JavaScript.
Runtime errors, also called exceptions, occur during execution (after compilation/interpretation).
Logic errors can be the most difficult type of errors to track down. These errors are not the result of a
syntax or runtime error. Instead, they occur when you make a mistake in the logic that drives your
script and you do not get the result you expected.
The latest versions of JavaScript added exception handling capabilities. JavaScript implements
the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript
syntax errors.
GET - It is HTTP method, asks to get thing at the requested URL.
POST - It is HTTP method, asks the server to accept the body info attached to the request, and give it
to the thing at the requested URL. It is like GET with extra info sent with the request.
Difference :
Although both GET and POST can send parameters but POST has a body. With GET, the parameter
data is limited to 255 character only what you can stuff into the Request line. In POST, there is no such
length limitation because it works as a part of the body of the HTTP request and there is no size limit
for the body of an HTTP request/response.
When we use GET, you can see the parameter data in the browser's input bar, right after the actual
URL, which is separated by a "?". It is not a secure way to send request. POST request is encapsulated
in the body of the HTTP request So you can use POST in such case because POST method provides
security.
If we talk about the performance then we find that the GET request is faster than POST request because
GET request creation is simpler and it also save time which is spent in encapsulation of POST request.
The maximum length limitation gives a better optimization of GET implementation.
GET request holds only text data as it is sent through URL string and we know URL can be text-only.
In POST request there is no restriction so you can carry both text as well as binary data.
JavaServer Pages (JSP) is a technology for developing Webpages that supports dynamic content. This
helps developers insert java code in HTML pages by making use of special JSP tags, most of which
start with <% and end with %>.
The JavaServer Pages Standard Tag Library (JSTL) is a collection of useful JSP tags which
encapsulates the core functionality common to many JSP applications.JSTL has support for common,
structural tasks such as iteration and conditionals, tags for manipulating XML documents,
internationalization tags, and SQL tags. It also provides a framework for integrating the existing
custom tags with the JSTL tags.
Part B.
JSON - Introduction
❮PreviousNext❯
JSON: JavaScript Object Notation.
What is JSON?
JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format
Since the JSON format is text only, it can easily be sent to and from a server, and used as a data format by any
programming language.
JavaScript has a built in function to convert a string, written in JSON format, into native JavaScript objects:
JSON.parse()
So, if you receive data from a server, in JSON format, you can use it like any other JavaScript object.
Exchanging Data
When exchanging data between a browser and a server, the data can only be text.
JSON is text, and we can convert any JavaScript object into JSON, and send JSON to the server.
We can also convert any JSON received from the server into JavaScript objects.
This way we can work with the data as JavaScript objects, with no complicated parsing and translations.
Sending Data
If you have data stored in a JavaScript object, you can convert the object into JSON, and send it to a server:
Example
var myObj = {name: "John", age: 31, city: "New York"};
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
Try it Yourself »
Receiving Data
If you receive data in JSON format, you can convert it into a JavaScript object:
Example
var myJSON = '{"name":"John", "age":31, "city":"New York"}';
var myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
Try it Yourself »
Storing Data
When storing data, the data has to be a certain format, and regardless of where you choose to store it, text is
always one of the legal formats.
Example
// Storing data:
myObj = {name: "John", age: 31, city: "New York"};
myJSON = JSON.stringify(myObj);
localStorage.setItem("testJSON", myJSON);
// Retrieving data:
text = localStorage.getItem("testJSON");
obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.name;
Try it Yourself »
JSON Syntax
A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:
Example
"name":"John"
JSON Function Files
A common use of JSON is to read data from a web server, and display the data in a web page.
This chapter will teach you, in 4 easy steps, how to read JSON data, using function files.
JSON Example
This example reads a menu from myTutorials.js, and displays the menu in a web page:
JSON Example
<div id="id01"></div>
<script>
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
</script>
Example Explained
myArray
var myArray = [
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]
myFunction()
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i<arr.length; i++) {
out += '<a href="' + arr[i].url + '">' + arr[i].display + '</a><br>';
}
document.getElementById("id01").innerHTML = out;
}
Call myFunction() with myArray as argument:
Example
myFunction(myArray);
Calling myFunction()
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
myTutorials.js
myFunction([
{
"display": "JavaScript Tutorial",
"url": "https://www.w3schools.com/js/default.asp"
},
{
"display": "HTML Tutorial",
"url": "https://www.w3schools.com/html/default.asp"
},
{
"display": "CSS Tutorial",
"url": "https://www.w3schools.com/css/default.asp"
}
]);
Add the external script to your page (instead of the function call):
2.
Servlet Architecture: Basics of Servlets
Servlet Exceution
This is how a servlet execution takes place when client (browser) makes a request to the webserver.
Servlet architecture includes:
a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet interface can be implemented
directly or indirectly by extending GenericServlet or HttpServlet class.
The first time a servlet is invoked, the init method is called. It is called only once during the lifetime of
a servlet. So, we can put all your initialization code here.
The Service method is used for handling the client request. As the client request reaches to the
container it creates a thread of the servlet object, and request and response object are also created.
These request and response object are then passed as parameter to the service method, which then
process the client request. The service method in turn calls the doGet or doPost methods (if the user
has extended the class from HttpServlet ).
c) Number of instances
publicclassfirstServletextendsHttpServlet{
publicvoidinit(){
/* Put your initialization code in this method,
* as this method is called only once */
}
publicvoid service(){
// Service request for Servlet
}
publicvoid destroy(){
// For taking the servlet out of service, this method is called only once
}
}
Servlet life cycle contains five steps: 1) Loading of Servlet 2) Creating instance of Servlet 3) Invoke
init() once 4) Invoke service() repeatedly for each client request 5) Invoke destroy()
For those who are wondering what is instance and invoke means: Instance and objects are same
thing. Invoking a method means calling a method, it is just a fancy word that we use in programming
world in place of calling :)
Let’s back to the main topic. Here are the five steps of servlet life cycle.
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.beginnersbook.MyServletDemo</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
Now the init() method for corresponding servlet class com.beginnersbook.MyServletDemo would
be invoked during web container startup.
Note: The init() method is called only once during the life cycle of servlet.
For example if its a Get Request the service() method would dispatch the request to the doGet()
method by calling the doGet() method with request parameters. Similarly the requests like Post, Head,
Put etc. are dispatched to the corresponding handlers doPost(), doHead(), doPut() etc. by service()
method of servlet.
Note: Unlike init() and destroy() that are called only once, the service() method can be called any
number of times during servlet life cycle. As long as servlet is not destroyed, for each client request
the service() method is invoked.
Out of all the 5 steps in life cycle, this is the only step that executes multiple times.
PART - C
JDBC API is a Java API that can access any kind of tabular data, especially data stored in a Relational Database.
JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with
database usage.
Applications of JDBC
Fundamentally, JDBC is a specification that provides a complete set of interfaces that allows for portable access
to an underlying database. Java can be used to write different types of executables, such as −
Java Applications
Java Applets
Java Servlets
All of these different executables are able to use a JDBC driver to access a database, and take advantage of the
stored data.
JDBC provides the same capabilities as ODBC, allowing Java programs to contain database-independent code.
JDBC Architecture
The JDBC API supports both two-tier and three-tier processing models for database access but in general, JDBC
Architecture consists of two layers −
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to
heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager
is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases.
Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC
drivers and the Java application −
Common JDBC Components
DriverManager: This class manages a list of database drivers. Matches connection requests from the
java application with the proper database driver using communication sub protocol. The first driver that
recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
Driver: This interface handles the communications with the database server. You will interact directly
with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this
type. It also abstracts the details associated with working with Driver objects.
Connection: This interface with all methods for contacting a database. The connection object
represents communication context, i.e., all communication with database is through connection object
only.
Statement: You use objects created from this interface to submit the SQL statements to the database.
Some derived interfaces accept parameters in addition to executing stored procedures.
ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects. It acts as an iterator to allow you to move through its data.
This sample example can serve as a template when you need to create your own JDBC application
in the future.
//STEP 1. Import required packages
import java.sql.*;
publicclassFirstExample{
// JDBC driver name and database URL
staticfinalString JDBC_DRIVER ="com.mysql.jdbc.Driver";
staticfinalString DB_URL ="jdbc:mysql://localhost/EMP";
// Database credentials
staticfinalString USER ="username";
staticfinalString PASS ="password";
publicstaticvoid main(String[]args){
Connection conn =null;
Statement stmt =null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//Display values
System.out.print("ID: "+ id);
System.out.print(", Age: "+ age);
System.out.print(", First: "+ first);
System.out.println(", Last: "+last);
}
//STEP 6: 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
System.out.println("Goodbye!");
}//end main
}//end FirstExample
Now let us compile the above example as follows −
C:\>javac FirstExample.java
C:\>
When you run FirstExample, it produces the following result −
C:\>java FirstExample
Connecting to database...
Creating statement...
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
C:\>