14
Register No. INTERNAL ASSESSMENT EXAMINATION - II COURSE: B.Tech. –IT IT8501 – Web Technology Sem & Class: V Sem/III-IT Date: 19.9.2019 Duration: 1 Hour 30 Mins Maximum: 50 Marks Answer ALL questions PART A - (7 X 2 = 14 marks) 1. What is the output if the following javascript program is executed by a typical web browser? Explain. var o1=new Object(); o1.j=9; var o2=o1; function test(o1){ o1.j=10; return; } test(o1); window.alert(o2.j); Output: 10. Value of Object o1 is referenced to object o2. 2. List and explain any two JavaScript built-in objects. JavaScript supports a number of built-in objects that extend the flexibility of the language. These objects are Date, Math, String, Array, and Object. JavaScript's Math object provides advanced arithmetic and trigonometric functions Ex: var pi = Math.PI; var piround = Math.round(pi); Object in javascript is a set of properties consists of a unique name with a value of one of 6 data types. var obj=new object(); obj.test=”this is a test”; SNS COLLEGE OF ENGINEERING Kurumbapalayam (Po), Coimbatore – 641 107 AN AUTONOMOUS INSTITUTION Accredited by NBA – AICTE and Accredited by NAAC – UGCwith ‘A’ Grade Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai

AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

  • Upload
    others

  • View
    7

  • Download
    0

Embed Size (px)

Citation preview

Page 1: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

Register No.

INTERNAL ASSESSMENT EXAMINATION - II

COURSE: B.Tech. –IT IT8501 – Web Technology

Sem & Class: V Sem/III-IT Date: 19.9.2019 Duration: 1 Hour 30 Mins Maximum: 50 Marks

Answer ALL questions

PART A - (7 X 2 = 14 marks)

1. What is the output if the following javascript program is executed by a typical web browser? Explain. var o1=new Object(); o1.j=9; var o2=o1; function test(o1){ o1.j=10; return; } test(o1); window.alert(o2.j);

Output: 10. Value of Object o1 is referenced to object o2.

2. List and explain any two JavaScript built-in objects.

JavaScript supports a number of built-in objects that extend the flexibility of the language. These objects are Date, Math, String, Array, and Object.

JavaScript's Math object provides advanced arithmetic and trigonometric functions Ex:

var pi = Math.PI; var piround = Math.round(pi);

Object in javascript is a set of properties consists of a unique name with a value of one of 6 data types. var obj=new object();

obj.test=”this is a test”;

SNS COLLEGE OF ENGINEERING Kurumbapalayam (Po), Coimbatore – 641 107

AN AUTONOMOUS INSTITUTION

Accredited by NBA – AICTE and Accredited by NAAC – UGCwith ‘A’ Grade

Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai

Page 2: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

3. Explain array creation in JavaScript with example. Array built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array();

The Array constructor is indirectly called if an array initializer is used. Ex: var arr1=new Array(4, false,”ok”);

4. What is meant by intrinsic event handling?

Intrinsic event handlers are ways to attach specific scripts to documents that are executed only when something happens to an HTML element

• An HTML intrinsic event attribute is used to specify a script to be called when an event occurs -Ex: onmouseover, onmousemove, onsubmit

5. Write the purpose of URL rewriting.

URL rewriting is the process of modifying Uniform Resource Locators (URLs) for various purposes. This technique is allowing an Internet user to access a Web site that has a complicated URL by entering a simpler URL into the address bar of a Web browser. (or)

Session management can be achieved by URL rewriting if cookies are disabled in a browser by the client. In URL rewriting, a token(parameter) is added at the end of the URL. The token consists of a name/value pair separated by an equal(=) sign. When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use the getParameter() method to obtain a parameter value.

6. When are cookies created? How long does a cookie last? Cookies provide a way for the website to recognize and keep track of our preferences.

Cookies are created when you use your browser to visit a website that uses cookies to keep track of your movements within the site, help you resume where you left off, remember your registered login, theme selection, preferences, and other customization functions. A cookie with no expiration date specified will expire when the browser is closed. These are often called session cookies because they are removed after the browser session ends

7. What is a Web Server? Explain its functionalities A web server is a system that delivers content or services to end users over the internet.

The primary function of a web server is to store, process and deliver web pages to clients. The communication between client and server takes place using the Hypertext Transfer Protocol (HTTP).

PART B - (3 X 12 = 36 marks)

8. a. i) Explain the java script array handling and array methods. Array built-in object can be used to construct objects with special properties and that inherit various methods

Page 3: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

var arr=new Array(); // Array Constructor length (0) - property

toString() sort() shift() – Inherited methods The Array constructor is indirectly called if an array initializer is used.

Ex: var arr1=new Array(4, false,”ok”);

• Array initializiers can be used to create multidimensional arrays Ex: var tt=[[“x”, “y”],[“y”,”z”],[“z”,”a”]];

Ex: <script> var fruits = ["Banana", "Orange", "Apple", "Papaya”,"Mango"];

var sorted = fruits.sort(); document.write(fruits + "<br>"); // Outputs: Apple,Banana,Mango,Orange,Papaya document.write(sorted); // Outputs: Apple,Banana,Mango,Orange,Papaya

</script>

ii) Discuss the following java script built-in objects. 1) Math 2) RegExp

Math object has methods and properties for performing standard mathematical calculations. All the properties and methods of Math are static and can be called by using Math as an object without creating it.

Math.sqrt(9); Math.round(4.4); Math.pow(8, 2); Math.abs(-4.7); // returns 4.7 Math.ceil(4.4); // returns 5

• Also has properties with approximate values for standard mathematical quantities, e.g., e ( Math.E ) and π (Math.PI)

Page 4: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

RegExp Object

• A regular expression is an object that describes a pattern of characters. • Used to test that a string entered in an HTML form has a certain format. • It performs powerful pattern-matching and search-and- replace functions on text. • Ex: To test whether or not a String value contained in a variable named areaCode

consists of exactly three digits: var acTest = new RegExp("ˆ\\d\\d\\d$"); if (!acTest.test(areaCode)) { window.alert(areaCode + " is not a valid area code."); }

• RegExp() begins with a caret (ˆ) and ends with a dollar sign ($) Defined with the RegExp () constructor

• var pattern = new RegExp(pattern, attributes); • pattern − A string that specifies the pattern of the regular expression or another regular expression. • attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multi-line matches, respectively. Example on patterns • -\d{3} - represents strings that begin with a - followed by three digits(shorthand notation) used. • [a-z] - set of lowercase letters • [a-zA-Z0-9]|_ “Word” character: any letter (a through z and A through Z), digit (0 through 9), or underscore _

8.(b) Explain in detail about javascript objects, its properties and methods.

Object in javascript is a set of properties consists of a unique name with a value of one of 6 data types

• There are no classes in JavaScript • Instead, properties can be created and deleted dynamically

Create an object o1 Create property testing Delete testing property � A constructor is a function – When called via new expression, a new empty Object is created and passed to the constructor along with the argument values – Constructor performs initialization on object • Can add properties and methods to object �• Can add object to an inheritance hierarchy

The Object() built-in constructor – Does not add any properties or methods directly to the object – Adds object to hierarchy that defines default toString() and valueOf() methods (used for

conversions to String and Number, resp.) Object initializer notation can be used to create an object (using Object() constructor) and one or

more properties in a single statement:

Page 5: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

Enumerating Properties :

Object Methods • JavaScript functions are stored as values of type Object • A function declaration creates a function value and stores it in a variable (property of

window) having the same name as the function • A method is an object property for which the value is a function � Creates global variable named leaf with function value

9. a) Explain DOM event handling in detail. Event instance created for each event. • Event instance properties: • type: name of event (click, mouseover, etc.) • target: Node corresponding to document element that generated the event (e.g., button element for click, img for mouseover). This is the event target. JavaScript event listener: function that is called with Event instance when a certain event occurs. • An event listener is associated with a target element by calling addEventListener() on the element

Syntax: element.addEventListener(event, function, useCapture); • The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.) • The second parameter is the function we want to call when the event occurs. • The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.

All HTML intrinsic events(by removing the prefix on from the attribute name) except keypress,

Page 6: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

keydown, keyup, and dblclick are DOM2 event types. • Also has some others that are typically targeted at the window object: error, resize, scroll. Ex: window. addEventListener(“error”, showMsg, false);

Mouse Events Events that occur when the mouse interacts with the HTML document belongs to the Mouse Event Object. • 6 DOM2 mouse events

- click - mousedown - mouseup - mousemove - mouseover - mouseout • Event instances have additional properties for mouse events apart from type and target. Event propagation

Event propagation is a way of defining the element order when an event occurs. • There are two ways of event propagation in the HTML DOM, bubbling and capturing. • If you have a <p>element inside a <div> element, and the user clicks on the <p> element, which element's "click" event should be handled first?

• In bubbling the inner most element's event is handled first and then the outer: the <p> element's click event is handled first, then the <div> element's click event.

• In capturing the outer most element's event is handled first and then the inner: the <div> element's click event will be handled first, then the <p> element's click event. Event Canceling and Form Validation For certain events on certain HTML elements, the browser provides a default event listener Example: 1. hyperlink- causing the browser to load a document 2. submit button is clicked on a form –default listener creates a query string representing the form data and submits it in an HTTP request to the URL specified for the form’s action attribute.

Canceling the browser’s default action is often used in conjunction with form validation.

• text box named requiredField within which the user is supposed to enter data before clicking submit button on a form named validatedForm

General Events: textfield.select(); - generates select event. To replace invalid data in text box , Select the contents of the text box and replace click() method – explain with example other than submit button.

Page 7: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

9 b) i) Explain the servlet life cycle with an example.

A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet.

• The servlet is initialized by calling the init() method.

• The servlet calls service() method to process a client's request.

• The servlet is terminated by calling the destroy() method.

• Finally, servlet is garbage collected by the garbage collector of the JVM.

Now let us discuss the life cycle methods in detail.

The init() Method

The init method is called only once. It is called only when the servlet is created, and not called for any user requests afterwards. So, it is used for one-time initializations, just as with the init method of applets.

The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started.

When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this −

public void init() throws ServletException { // Initialization code... }

The service() Method

The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client.

Each time the server receives a request for a servlet, the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.

Here is the signature of this method −

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { }

The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response)

Page 8: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

throws ServletException, IOException { // Servlet code }

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }

The destroy() Method

The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your

servlet a chance to close database connections, halt background threads, write cookie lists or hit counts

to disk, and perform other such cleanup activities.

After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this −

public void destroy() { // Finalization code... } ii) Justify the need for client and server side scripting. Scripting is sometimes called a program that means some code that runs on computer to perform any task. Now there are two types of scripting, 1. client side scripting 2. server side scripting.

Client side scripting

• Client side scripting is that script which runs on user browser like Firefox or Google Chrome. • Client side scripting consumes user computer resources like graphics card if any animation is

done by the script. • The client side script is interpreted by the browser.

Uses of client side scripting

Client side scripting is used when user is filling some form on web page and it is used for form validation. For example if the user not fills some fields like its phone number then script will prompt it to

Page 9: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

enter his phone number. Similarly validation of email is done by the client side script to check whether it is valid email id or not.

Why to use client side scripting

• Client side scripting is fast. • Form validation is done quickly using client side scripting. • Different animations can be drawn by the script and also different functions like displaying

system clock and date picker is done easily with client side scripting.

Example of client side scripting language Here are few example of client side scripting languages:-

• Javascript • Jscript

Server side scripting

• Server side scripting is that which runs on server side also called web servers. • The web servers are those which are provided by hosting companies like you get hosting from

different web hosting companies. • The web server understands server side languages.

Uses of server side scripting

• Use server side scripting to get data from the database. • When the user type the url in browser then a request is send to the web server, then web server

find the specific page and transfers to browser, then browser translates that web page and displays it to the user.

• Server side scripting is fully controlled by the web server and it not depends upon which browser the user is using.

• Server side scripting is sometimes slow because if the user disconnects from the internet or the web hosting is down then the script may take long time to execute.

• Complex computation is done by the server side scripting that client side scripting cannot perform easily. A technology called ajax which use server side scripting.

• Ajax displays new data on the website without reloading the page.

Why to use server side scripting

• Client side scripting is sometimes blocked by some browsers. • And user can also block client side scripting to execute. • Server side scripting is not dependent upon browser processing, all the processing is done on

server side i.e. web server. • Sometimes server side scripting is unsecure because it is used to hack a website. • Server side scripting is used to make big websites like bank websites and it involves server side

validation. • Good websites uses both client side validation and server side validation to secure their websites. • Web developers have expertise of both client side scripting language and server side scripting

languages.

Page 10: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

Examples of server side scripting

Here are few server side languages:-

• Php • Asp • Asp.net • C# • Perl • Jsp • Python • Ruby

10. a) i) Explain in detail about the dynamic content generation by a servlet with an example.

Creating dynamic web page is the one which have the capability to change the site contents according to the time or are able to generate the contents according to the request received by the client.

Java Servlets generate dynamic web pages.

Servlets are the Java programs that runs on the Java-enabled web server or application server.

They are used to handle the request obtained from the web server, process the request, produce the response, then send response back to the web server.

Properties of Servlets :

• Servlets work on the server-side.

• Servlets capable of handling complex request obtained from web server.

Execution of Servlets : Execution of Servlets involves the six basic steps:

1. The clients send the request to the web server.

2. The web server receives the request.

3. The web server passes the request to the corresponding servlet.

4. The servlet processes the request and generate the response in the form of output.

5. The servlet send the response back to the web server.

6. The web server sends the response back to the client and the client browser displays it on the screen.

Follow the simple example for generating dynamic content in the next slide

To output the number of times the servlet has been visited since the server hosting the servlet was already started.

Page 11: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

ii) Explain how java servlets perform session handling.

Session simply means a particular interval of time. • Session-id is passed between the browser and server while processing the information. This method of keeping track of all the information between server and browser using session-id is called session tracking(used to recognize the particular user) • Http protocol is a stateless protocol so we need to maintain state using session tracking techniques.

Creating a session HttpSession session= request.getSession(); Session attribute methods:

Page 12: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

– setAttribute(String name, Object value): is a method which assigns the value passed as the object value to the attribute name – Object getAttribute(String name): returns the value associated with name, or returns null if this session does not have an attribute with this name By default, each session expires if a server-determined length of time elapses between a session’s HTTP requests – Server destroys the corresponding session object • Servlet code can: – Terminate a session by calling invalidate() method on session object – Set the expiration time-out duration (secs) by calling setMaxInactiveInterval(int) 10. b. i) Explain about Servlet architecture & methods. Servlet Architecture

1. When server starts, it instantiates servlets. 2. Server receives HTTP request, determines need for dynamic response 3. Server selects the appropriate servlet to generate the response, creates request/response

objects(HttpServletRequest, HttpSevletResponse) and passes them to a method on the servlet instance

4. Servlet adds information to response object via method calls 5. Server generates HTTP response based on information stored in response object by the servlet

The doGet() and doPost() are most frequently used methods with in each service request. Here is the signature of these two methods.

The doGet() Method

A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }

Page 13: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

The doPost() Method

A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method.

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } 10. b. ii) What is a cookie and what are the advantages and disadvantages of cookie? How to create and delete a cookie? Illustrate with an example. A cookie is a small piece of text file stored on user's computer in the form of name-value pair. Cookies are used by websites to keep track of visitors e.g. to keep user information like username etc. Advantages of using cookies Some of the advantages of using cookies to store session state. · Cookies are simple to use and implement. · Occupies less memory, do not require any server resources and are stored on the user's computer so no extra burden on server. · User can configure cookies to expire when the browser session ends (session cookies) or they can exist for a specified length of time on the client’s computer (persistent cookies). · Cookies persist a much longer period of time than Session state. Disadvantages of using cookies Some of the disadvantages:

• Cookies are not secure as they are stored in clear text they may pose a possible security risk as anyone can open and tamper with cookies. User can manually encrypt and decrypt cookies, but it requires extra coding and can affect application performance because of the time that is required for encryption and decryption

• Several limitations exist on the size of the cookie text(4kb in general), number of cookies(20 per site in general), etc.

• User has the option of disabling cookies on his computer from browser’s setting. • Cookies will not work if the security level is set to high in the browser. • Users can delete a cookies. • Users browser can refuse cookies,so user code has to anticipate that possibility. • Complex type of data not allowed (e.g. dataset etc). It allows only plain text (i.e. cookie allows

only string content) Servlets can set cookies explicitly

o Cookie class used to represent cookies o request.getCookies() returns an array of Cookie instances representing cookie data in

HTTP request o response.addCookie(Cookie) adds a cookie to the HTTP response

Page 14: AN AUTONOMOUS INSTITUTION - SNS CoursewareArray built-in object can be used to construct objects with special properties and that inherit various methods var arr=new Array(); The Array

Simple code to create cookie. Cookie ck=new Cookie("user","sonu");//creating cookie object

response.addCookie(ck);//adding cookie in the response

Simple code to delete cookie. It is mainly used to logout or signout the user. Cookie ck=new Cookie("user","");//deleting value of cookie

ck.setMaxAge(0);//changing the maximum age to 0 seconds response.addCookie(ck);//adding cookie in the response