Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 13

Internet Programming

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 try...catch...finally Statement

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.

5. List out standard events in event handling of JS.


Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a
set of events which can trigger JavaScript Code.
onclick Event Type
This is the most frequently used event type which occurs when a user clicks the left button of his
mouse. You can put your validation, warning etc., against this event type.
onsubmit Event Type
onsubmit is an event that occurs when you try to submit a form. You can put your form validation
against this event type.
onmouseover and onmouseout
These two event types will help you create nice effects with images or even with text as well.
The onmouseover event triggers when you bring your mouse over any element and
the onmouseout triggers when you move your mouse out from that element.
6. What is JSON & need for it?
JSON stands for JavaScript Object Notation
JSON is a lightweight data-interchange format
JSON is "self-describing" and easy to understand
JSON is language independent *
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.
7. Define Servlets.
A servlet is a Java program that runs on a Web server. It is similar to an applet, but is processed on the
server rather than a client's machine. Servlets are often run when the user clicks a link, submits a form,
or performs another type of action on a website.
8. Differentiate GET & POST actions in Servlets

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.

9. Define Cookies & state its types


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.
10. What is JSP& JSTL?

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.

JSON is a syntax for storing and exchanging data.

JSON is text, written with JavaScript object notation.

What is JSON?
 JSON stands for JavaScript Object Notation
 JSON is a lightweight data-interchange format

 JSON is "self-describing" and easy to understand

 JSON is language independent *

Why use JSON?

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 »

You will learn more about the JSON.stringify() function later in this tutorial.

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 »

You will learn more about the JSON.parse() function later in this tutorial.

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.

JSON makes it possible to store JavaScript objects as text.

Example

Storing data in local storage

// 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

The JSON syntax is a subset of the JavaScript syntax.

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

 Data is in name/value pairs

 Data is separated by commas

 Curly braces hold objects

 Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs.

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example
"name":"John"

JSON names require double quotes. JavaScript names don't.

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

1: Create an array of objects.

Use an array literal to declare an array of objects.

Give each object two properties: display and url.

Name the array myArray:

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"
}
]

2: Create a JavaScript function to display the array. 


Create a function myFunction() that loops the array objects, and display the content as HTML links:

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);

3: Use an array literal as the argument (instead of the array variable):

Call myFunction() with an array literal as argument:

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"
}
]);

4: Put the function in an external js file

Put the function in a file named myTutorials.js:

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

A Servlet is a class, which implements the javax.servlet.Servlet interface. However instead of directly


implementing the javax.servlet.Servlet interface we extend a class that has implemented the interface
like javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

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.

b) Request handling methods


There are 3 methods defined in Servlet interface: init(), service() and destroy().

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

Basic Structure of a Servlet

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
}
}

Life Cycle of Servlet

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.

Step 1: Loading of Servlet


When the web server (e.g. Apache Tomcat) starts up, the servlet container deploy and loads all the
servlets.

Step 2: Creating instance of Servlet


Once all the Servlet classes loaded, the servlet container creates instances of each servlet class.
Servlet container creates only once instance per servlet class and all the requests to the servlet are
executed on the same servlet instance.

Step 3: Invoke init() method


Once all the servlet classes are instantiated, the init() method is invoked for each instantiated servlet.
This method initializes the servlet. There are certain init parameters that you can specify in the
deployment descriptor (web.xml) file. For example, if a servlet has value >=0 then its init() method is
immediately invoked during web container startup.

You can specify the element in web.xml file like this:

<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.

Step 4: Invoke service() method


Each time the web server receives a request for servlet, it spawns a new thread that calls service()
method. If the servlet is GenericServlet then the request is served by the service() method itself, if the
servlet is HttpServlet then service() method receives the request and dispatches it to the correct
handler method based on the type of request.

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.

Step 5: Invoke destroy() method


When servlet container shuts down(this usually happens when we stop the web server), it unloads all
the servlets and calls destroy() method for each initialized servlets.

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.

Why to Learn JDBC?

JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent


connectivity between the Java programming language and a wide range of databases.

The JDBC library includes APIs for each of the tasks mentioned below that are commonly associated with
database usage.

 Making a connection to a database.


 Creating SQL or MySQL statements.

 Executing SQL or MySQL queries in the database.

 Viewing & Modifying the resulting records.

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

 Java ServerPages (JSPs)

 Enterprise JavaBeans (EJBs).

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 −

 JDBC API: This provides the application-to-JDBC Manager connection.

 JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.

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

The JDBC API provides the following interfaces and classes −

 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.

 SQLException: This class handles any errors that occur in a database application.

Creating JDBC Application

There are following six steps involved in building a JDBC application −


 Import the packages: Requires that you include the packages containing the JDBC classes
needed for database programming. Most often, using import java.sql.* will suffice.
 Register the JDBC driver: Requires that you initialize a driver so you can open a
communication channel with the database.
 Open a connection: Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with the database.
 Execute a query: Requires using an object of type Statement for building and submitting an
SQL statement to the database.
 Extract data from result set: Requires that you use the
appropriate ResultSet.getXXX() method to retrieve the data from the result set.
 Clean up the environment: Requires explicitly closing all database resources versus relying
on the JVM's garbage collection.

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");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn=DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt=conn.createStatement();
Stringsql;
sql="SELECT id, first, last, age FROM Employees";
ResultSetrs=stmt.executeQuery(sql);

//STEP 5: 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");
Stringlast=rs.getString("last");

//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:\>

You might also like