1 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING IMPORTANT QUESTIONS & ANSWERS JUNE – NOV.2015 CS6501 – INTERNET PROGRAMMING Year/Sem : IV/VIII Branch : COMPUTER SCIENCE AND ENGINEERING Faculty : V.KARTHIK SYLLABUS CS6501 INTERNET PROGRAMMING LTPC/3104 OBJECTIVES: The student should be made to:  Learn Java Programming.  Understand different Internet Technologies.  Be exposed to java specific web services architecture. UNIT I JAVA PROGRAMMING An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding websites and web servers: Understanding Internet – Difference between websites and web server- Internet technologies Overview – Understanding the difference between internet and intranet; HTML and CSS: HTML 5.0 , XHTML, CSS 3. UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,- Regular Expressions- Exception Handling- Validation-Built-in objects-Event Handling- DHTML with JavaScript. Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions- Session Handling- Understanding Cookies- Installing and Configuring Apache Tomcat Web Server;- DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding Java Server Pages-JSP Standard Tag Library (JSTL)-Creating HTML forms by embedding JSP code.
2 UNIT IV PHP and XML An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-Connecting to Database – Using Cookies-Regular Expressions; XML: Basic XML- Document Type Definition-XML Schema DOM and Presenting XML, XML Parsers and Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM). UNIT V INTRODUCTION TO AJAX and WEB SERVICES AJAX: Ajax Client Server Architecture- XML Http Request Object-Call Back Methods; Web Services: Introduction- Java web services Basics – Creating, Publishing, Testing and Describing a Web services (WSDL)-Consuming a web service, Database Driven web service from an application – SOAP. TOTAL (L: 45+T: 15): 60 PERIODS OUTCOMES:  At the end of the course, the student should be able to:  Implement Java programs.  Create a basic website using HTML and Cascading Style Sheets.  Design and implement dynamic web page with validation using JavaScript objects and by applying different event handling mechanisms.  Design rich client presentation using AJAX.  Design and implement simple web page in PHP, and to present data in XML format.  Design and implement server side programs using Servlets and JSP. TEXT BOOKS: 1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖, Prentice Hall, 5th Edition, 2011. 2. Herbert Schildt, ―Java-The Complete Reference‖, Eighth Edition, Mc Graw Hill Professional,2011. REFERENCES: 1. Stephen Wynkoop and JohnBurke ―Running a Perfect Website‖, QUE,2nd Edition,1999. 2. Chris Bates, Web Programming – Building Intranet Applications, 3 rd Edition, Wiley Publications, 2009. 3. Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖, Pearson Education, 2011. 4. Gopalan N.P. and Akilandeswari J., ―Web Technology‖, Prentice Hall of India, 2011. 5. Paul Dietel and Harvey Deitel, ―Java How to Program‖,8 th Edition Prentice Hall of India. 6. Mahesh P. Matha, ―Core Java A Comprehensive Study‖, Prentice Hall of India, 2011. 7. Uttam K.Roy, ―Web Technologies‖, Oxford University Press, 2011.
3 SECTION B: QUESTIONS UNIT –I JAVA PROGRAMMING PART -A 1. What is a Class and Object? 2. What is final modifier? 3. What is meant by abstraction? 4. What are methods and how are they defined? 5. What is an Object and how do you allocate memory to it? 6. Explain the usage of Java packages. 7. What is method overloading and method overriding? 8.What is static variable and static method? 9. What is array? Give an example. 10.What is a package? 11.Explain working of Java Virtual Machine (JVM)? 12. What is meant by Inheritance and what are its advantages? 13. What are inner class and anonymous class? 14. What is an Interface? 15.What is interface and its use? 16. What are the types of Exceptions in Java 17. Whatis the difference between String and String Buffer? 18.What are different types of access modifiers (Access specifiers)? 19. What is multithreading? 20. What is an applets? PART -B 1. Explain in detail about operator in java with example? (16) 2. i) Discuss in detail the access specifiers available in Java.(8) ii)What is Array? How to declare array?Discuss the methods under array class. (8) 3. Explain Packages in detail with example. (16) 4. Explain the concept of inheritance and its types. (16) 5. Explain the different ways to handle exceptions in java. (16) 6.Explain in detail about Multithreading in java. (16)
4 UNIT –II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 PART-A 1. What are the necessities of using HTML forms? 2. Define HTML. 3. What do you understand about DOCTYPE in HTML? 4. What are the Hyperlink, Anchors and Link in the HTML? 5. How you define HTML Style Attribute in HTML? 6. HTML is case sensitive or not? 7. How to use form‘s action attribute and submit button in html? 8. How to use Line Break and Horizontal Line tags in HTML? 9. What are Style Sheets? 10. List down the ways of including style information in a document. 11. What are the style precedence rules when using multiple approaches? 12. Give the syntax to specify a characteristic in linked style sheet. 13. List down font characteristics permitted in style sheets. 14. How to toggle display an HTML element? 15. What is the HTML DOM? PART –B 1. Explain Basic internet protocols and HTTP message format?(16) 2. To create a web page that displays college information using various styles (16) 3. Explain XHTML Syntax and semantics with example.(16) 4. i)Design a HTML Form for aRailwaay Reservation System? (8) ii)Explain about different types of XHTML DTD(8) 5.i)Explain about internet and intranet with difference.(8) ii) Design a HTML document using relative positioning to nudge text to the left.(8)
5 UNIT –III CLIENT SIDE AND SERVER SIDE PROGRAMMING PART-A 1. How to create an Object in JavaScript? 2. What is the result of below given line of code in Java Script? 5+4+‖7‖ 3.What is undefined value means in JavaScript? 4. Which method is used to Clear an array using JavaScript? 5.What will be the Output of the following using JavaScript, document.Write(Math.Round(6.7)); 6.What should appear at the very end of your JavaScript? 7.What is a JSP and what is it used for? 8. What is difference between custom JSP tags and beans? 9. What are the implicit objects? 10. Compare Client side vs. server side scripting. 11. State the Servlet life cycle 12. What is JavaScript? 13. What is the purpose of cookies? 14. What are the steps needs to establish JDBC connectivity? 15. What is the difference between GET and POST method? 16. What is different between web server and application server? 17. What are different methods of session management in servlets? 18. What is difference between GenericServlet and HttpServlet? PART –B 1. Explain javascript variables and debuggers in detail (16) 2. Discuss JavaScript Array object in detail. (16) 3. Write java script to perform all arithmetic operation (16) 4. Explain DOM event handling in detail.(16) 5. Write java servlet programs to conduct online examination and to display student mark list available in a database (16)
6 UNIT-IV PHP and XML PART –A 1. Mention the rules of well-formed XML. 2. What is the DOM? 3. What is the XML DOM? 4. What is the XMLHttpRequest Object? 5. What is XSL-FO? 6. What is XSL-FO Documents? Explain XSL-FO Documents structure 7. What is XSL-FO Processors? 8. Explain XML Attributes with an example 9. XML Elements vs. Attributes. 10. What are the problems with using XML attributes? 11. What is XSLT? 12. What are the roles of XSLT? 13.What is XSLT? Explain its relationships with XSL 14.What is XSLT style sheet? 15.Discuss the role of XPATH 16.Explain the XSLT data model 17.Why the need for XHTML? 18.What is XQuery language? 19.Explain the Relation between RSS and XML 20. Define. DOM PART –B 1. Given an XSLT document and a source XML document explain the XSLT transformation process that produces a single result XML document. (16) 2.Write a program to display student information using XSLT in XML document (16) 3. i)Explain the role XML namespaces with an example.(8) (ii)Explain the feature of XML path.(8) 4. Explain the model view controller architecture pattern in detail. (16) 5. Write Programs using XML – Schema – XSLT/XSL (16)
7 UNIT V – INTRODUCTION TO AJAX and WEB SERVICES PART –A 1. What is DTD? Explain it with example. 2. What is AJAX? 3.What is a web service? 4.What is SOAP? 5. What is SOAP and how it will be utilized in web-components? 6. Explain about the role of XML in SOAP? 7.What are the elements which should be contained in SOAP message? 8. What is SOAP? 9. Explain web services architecture. 10. What is WSDL? 11. Differentiate between AJAX and Java Script 12. What are the advantages of AJAX ? 13. Define Web Service? 14. Brief few drawbacks of using GET and POST methods to communicate with the web service? 15. Differentiate between a SOA and a Web service? PART –B 1. Describe the significance and working of WSDL with an example(16) 2. Describe the major elements of SOAP (16) 3. Explain about AJAX Http Request Object (16) 4. Explain in details about Web Services Conceptual Architecture (16) 5. Write a program to run and implement the web service (16)
8 SECTION C: QUESTIONS AND ANSWER UNIT –I PART A 1. What is a Classand Object? Class is a template for a set of objects that share a common structureand a common behavior. Object is an instance of a class. It has state, behavior and identity. It isalso called as an instance of a class. 2. What is final modifier? The final modifier keyword makes that the programmer cannotchange the value anymore. The actual meaning depends on whether it isapplied to a class, a variable, or a method. final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized. final Methods- A final method cannot be overridden by subclasses. 3. What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. It‘s the process of focusing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model 4. What are methods and how are they defined? Methods are functions that operate on instances of classesin which they are defined. Objects can communicate with each other usingmethods and can call methods in other classes. Method definition has fourparts. They are name of the method, type of object or primitive type themethod returns, a list of parameters and the body of the method. A method‘s signature is a combination of the first three parts mentionedabove. 5. What is an Object and how do you allocate memory to it? Object is an instance of a class and it is a software unit that combines astructured set of data with a set of operations for inspecting and manipulatingthat data. When an object is created using new operator, memory is allocated toit. 6. Explain the usage of Java packages. This is a way to organize files when a project consists of multiplemodules. It also helps resolve naming conflicts when different packages haveclasses with the same names. Packages access level also allows you toprotect data from being used by the non- authorized classes. 7. What is method overloading and method overriding? Method overloading: When a method in a class having the same methodname with different arguments is said to be method overloading. Methodoverriding: When a method in a class having the same method name withsame arguments is said to be method overriding.
9 8.What is static variable and static method? Static variable is a class variable which value remains constant for theentire class. Static method is the one which can be called with the class itself and can holdonly the static variables. 9. What is array? Give an example. An array is a group of like-typed variables that are referred to by a common name. Arrays ofany type can be created and may have one or more dimensions. A specific element in an arrayis accessed by its index. Arrays offer a convenient means of grouping related information. Syntax: array-var = new type[size];example:month_days = new int[12]; 10.What is a package? A package is a collection of classes and interfaces that provides ahigh-level layer of access protection and name space management. 11.Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computingmachine which first converts .java file into .class file by using Compiler (.class isnothing but byte code file.) and Interpreter reads byte codes 12. What is meant by Inheritance and what are its advantages? Inheritance is the process of inheriting all the features from a class.The advantages of inheritance are reusability of code and accessibility ofvariables and methods of the super class by subclasses. 13. What are inner class and anonymous class? Inner class: classes defined in other classes, includingthose defined in methods are called inner classes. An inner class canhave any accessibility including private. Anonymous class: Anonymousclass is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors 14. What is an Interface? Interface is an outside view of a class or object which emphasizes itsabstraction while hiding its structure and secrets of its behavior. 15.What is interface and its use? Interface is similar to a class which may contain method‘ssignature only but not bodies and it is a formal set of method and constantdeclarations that must be defined by the class that implements it.Interfaces are useful for: a) Declaring methods that one or moreclasses are expected to implement b) Capturing similarities betweenunrelated classes without forcing a class relationship. c) Determining anobject‘s programming interface without revealing the actual body of the class
10 16. What are the types of Exceptions in Java There are two types of exceptions in Java, unchecked exceptions andchecked exceptions. Checked exceptions: A checked exception is some subclass of Exception (orException itself), excluding class Runtime Exception and its subclasses. Eachmethod must either handle all checked exceptions by supplying a catchclause or list each unhandled checked exception as a thrown exception. Unchecked exceptions: All Exceptions that extend the Runtime Exceptionclass are unchecked exceptions. Class Error and its subclasses also areunchecked. 17. Whatis the difference between String and String Buffer? a) String objects are constants and immutable whereas String Buffer objects are not. b) String class supports constant strings whereas String Buffer class supports grow able and modifiablestrings. 18.What are different types of access modifiers (Access specifiers)? Access specifiers are keywords that determine the type of accessto the member of a class. These keywords are for allowingprivileges to parts of a program such as functions and variables. Theseare: Public: Anything declared as public can be accessed from anywhere. Private: Anything declared as private can‘t be seen outside of its class. Protected: Anything declared as protected can be accessed by classes inthe same package and subclasses in the other packages. Default modifier : Can be accessed only to classes in thesame package. 19. What is multithreading? Java provides built-in support for multithreadedprogramming. A multithreaded program contains two or more parts that can runconcurrently. Each part of such a program is called a thread, and each thread definesa separate path of execution. Thus, multithreading is a specialized form of multitasking. 20. What is an applets? Applets are small applications that are accessed on anInternet server, transported over the Internet, automatically installed, and run as part of a webdocument. After an applet arrives on the client, it has limited access to resources so that itcan produce a graphical user interface and run complex computations without introducingthe risk of viruses or breaching data integrity.
11 SECTION C: QUESTIONS & ANSWERS UNIT –I JAVA PROGRAMMING 1. Explain in detail about operator in java with example? (16) Java provides a rich operator environment. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations. Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Operator | Result: + Addition – Subtraction (also unary minus) * Multiplication / Division % Modulus ++ Increment += Addition assignment –= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment – – Decrement The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is,essentially, a subset of int. class BasicMath { public static void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b / 4; int d = c - a; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e);
12 The Bitwise Operators Java defines several bitwise operators that can be applied to the integer types, long, int, short,char, and byte. These operators act upon the individual bits of their operands. They aresummarized in the following table: The Bitwise Logical Operators The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation. The Bitwise OR The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1, as shown here: The Bitwise XOR
13 // Demonstrate the bitwise logical operators. class BitLogic { public static void main(String args[]) { String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" }; int a = 3; // 0 + 2 + 1 or 0011 in binary int b = 6; // 4 + 2 + 0 or 0110 in binary int c = a | b; int d = a & b; int e = a ^ b; int f = (~a & b) | (a & ~b); int g = ~a & 0x0f; System.out.println(" a = " + binary[a]); System.out.println(" b = " + binary[b]); System.out.println(" a|b = " + binary[c]); System.out.println(" a&b = " + binary[d]); System.out.println(" a^b = " + binary[e]); System.out.println("~a&b|a&~b = " + binary[f]); System.out.println(" ~a = " + binary[g]); } } output from this program: a = 0011 b = 0110 a|b = 0111 a&b = 0010 a^b = 0101 ~a&b|a&~b = 0101 ~a = 1100 Relational Operators The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here:
14 Example: int a = 4; int b = 1; boolean c = a < b; Boolean Logical Operators The Boolean logical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value. The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and !false == true. The following table shows the effect of each logical operation: // Demonstrate the boolean logical operators. class BoolLogic { public static void main(String args[]) { boolean a = true; boolean b = false; boolean c = a | b; boolean d = a & b; boolean e = a ^ b; boolean f = (!a & b) | (a & !b); boolean g = !a; System.out.println(" a = " + a);
15 System.out.println(" b = " + b); System.out.println(" a|b = " + c); System.out.println(" a&b = " + d); System.out.println(" a^b = " + e); System.out.println("!a&b|a&!b = " + f); System.out.println(" !a = " + g); } } O/P: a = true b = false a|b = true a&b = false a^b = true a&b|a&!b = true !a = false The Assignment Operator The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other computer language. It has this general form: var = expression; Here, the type of var must be compatible with the type of expression. For example, int x, y, z; x = y = z = 100; // set x, y, and z to 100 The ? Operator Ternary (three-way) operator that can replace certain types of if-then-else Statements .The ? has this general form: expression1? expression2:expression3 Here, expression1 can be any expression that evaluates to a boolean value. If expression1 istrue, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?operation is that of the expression evaluated. Both expression2 and expression3 are requiredto return the same type, which can‘t be void. Example: ratio = denom == 0 ? 0 : num / denom;
16 2. i) Discuss in detail the access specifiers available in Java.(8) ii)What is Array? How to declare array?Discuss the methods under array class. (8) i) Discuss in detail the access specifiers available in Java.(8) Java‘s four level of access protection:  Public  Private  Protected  Default Some aspects of access control are related mostly to inheritance or package. (A package is,essentially, a grouping of classes) protected is applied only when inheritance is invoked. : Public Access: When a member of a class is modified by public specifier, then that member can be accessed by any other code. Now you can understand why main () has always been preceded by the public specifier.it is called by code that is outside the program that is by java run time system Private Access: when a member of class is specified as private, then that member can only be accessed by other members of its class. protected: Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. Default Access: when no specifier is used then by default the member of class is public within its own package, but cannot be accessed outside of its package.in the classes development so far ,all members of a class have use the default access mode .which is essentially public. This access specifier is also known as friendly access. table showing all the access specifiers and theiraccessibility in the class, package, subclasses andother packages.
17 Example of public & private /* Program to demonstrate Access Protection */ class Demo { int p; // default access public int q; // public access private int r; // private access // methods to access r void setr(int i) { // set r's value r = i; } int getr() { // get r's value return r; } } class AccessProDemo { public static void main(String args[]) { Demo d= new Demo(); // OK : 'p' and 'q' may be accessed directly d.p=300; d.q=400; // NOT OK : 'r' cannot be accessed outside the class, hence will cause an error // d.r=50; // You must access 'r' through its methods d.setr(500); //OK System.out.println(" p, q, and r = "+d.p+", "+d.q+", and "+d.getr()); } } o/p:- P, q, and r =300,400, and 500
18 2.ii) What is Array? How to declare array?Discuss the methods under array class. An array is a data structure that stores a collection of values of the same type. You access each individualvalue through an integer index. Array Name [index] Integer constant, variable, or expression For Instance we can define an array name salary to represent a set of salaries of a group of employees. Aparticular value is indicated by writing a number called index in brackets after the array name. salary [10] it represents the salary of the 10th employee. Types of arrays One dimensional arrays Two dimensional arrays One Dimensional arrays A list of items can be given one variable name using only one subscript and such a variable iscalled single - subscripted of one dimensional array. The subscript can also start from 0. ie x[0]. If we want to represent a set of five numbers, say (35,40,20,57,19) by an array variable number,then we have to create the variable number as follows int number [ ] = new int [5 ]; The value to the array elements can be assigned as follows Number[0] =35; Number [1] =40; Number [2] =20; Number [3] =57; Number [4] =19; This would cause the array number to store the values shown as follows; Creating an array Declaring the array Creating memory locations Putting values into the memory locations. Declaring the Array Array in java can be declared in two forms Form 1 type arrayname [ ]; Form 2 type [ ] arrayname; Creation of arrays arrayname = new type [ size ]; Eg; number = new int [5] ; average = new float[10]; it is also possible to combine declaration and creation. int number [ ] = new int [5]; Initialization of arrays
19 The final step is to put values into the array created. This process is known as initialization usingthe array subscripts as shown below. arrayname[subscript] = value ; Eg number[0] = 15; we can also initialize by following way typearrayname [ ] = { list of values } Array Length All array store the allocated size in an variable named length. We can obtain the length of array ausing a.length Eg: intasize = a.length; Sample Code for array manipulation Two Dimensional arrary: Usage :intmyArray [ ] [ ]; myArray= new int [3] [4]; or initmyArray [ ] [ ] = new int [3][4] This creates a table that can store 12 integer values, four across and three down. Strings: Series of characters represents a string, and easiest way to represent the string is array Eg: Char charArray [ ] = new char [2] ; charArray[0] = „j‟ ; charArray[1] = „a‟ ; String can be declared and created in the following way string stringname; stringname = new string (―string‖); Operations on string int m = stringname.length() //will return the length of the string string city = ―New‖ + ―Delhi‖// will return New Delhi ,string concatenating Sample Code forstring Manipulation 3. Explain Packages in detail with example. (16) Packages are java‟s way of grouping a variety of classes and/or interfaces together. Packages are container for the classes. It is stored in a hierarichical manner. If we want to use the packages in a class, we want to import it. The two types of packages are: 1. System package. 2. User defined package. Uses of Packages: Packages reduce the complexity of the software because a large number of classes can be grouped into a limited number of packages.
20 We can create classes with same name in different packages. Using packages we can hide classes. We may like to use many of the classes contained in a package.it can be achieved by Import packagename .classname Or Import packagename.* Creating the package To create our own packages packagefirstpackage;// package declaration public class FirstClass //class definition {..... (body of class) .......} The file is saved as FirstClass.java,located at firstpackage directory. when it is compiled .class file will be created in same ditectory. Access a package The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching class is a as follows. Import package1 [.package2] [.package3].classname; Using the package package package1 ; public class classA { public void displayA() { System.out.println(―class A‖); } } Adding a class to package Define the class and make it public Place the package statement Package P1 Before the class definition as follows Package p1; Public class B Package name { // body of B } Example: Package college Class student {
21 intregno; String name; Student(intr,stringna); { Regno=r Name=na } Public void print() { System.out.println(―Regno‖+regno ); System.out.println(―Name‖+name ); } } Package Course Class engineering { Intregno; String branch; String year; Engineering(int r, string br, string yr) { Regno=br; Branch=br; Year=yr; } public void print() { Systems.out.println(―Regno‖+regno); Systems.out.println(― Branch‖+branch); Systems.out.println(―Year‖+year); } } import college.*; import course.*; Class demo { Public static void main(string args[]) { Student sl=new Engineering(1,‖CSE‖,‖III Year‖); Sl.print(); El.print(); } }
22 4. Explain the concept of inheritance and its types. (16) There exist basically three types of inheritance.  Multilevel inheritance  Multiple inheritance  Hierarchical inheritance 1. In single inheritance, one class extends one class only. In multilevel inheritance, the ladder of single inheritance increases. 2. In multiple inheritance, one class directly extends more than one class. 3. In hierarchical inheritance one class is extended by more than one class. 1. Single Inheritance When a single derived class is created from a single base class then the inheritance is called as single inheritance. 1. Multilevel Inheritance In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance, but one class extends only one. The lowermost subclass can make use of all its super classes' members. Multilevel inheritance is an indirect way of implementing multiple inheritance. Following program explains. class Aves { public void nature() { System.out.println("Generally, Aves fly"); } } class Bird extends Aves { public void eat() { System.out.println("Eats to live"); } }
23 public class Parrot extends Bird { public void food() { System.out.println("Parrot eats seeds and fruits"); } public static void main(String args[]) { Parrot p1 = new Parrot(); p1.food(); // calling its own p1.eat(); // calling super class Bird method p1.nature(); // calling super class Aves method } } Now, Parrot has two super classes Bird and Aves; but extended one-to-one. Parrot can make use of the methods of Bird and Aves. Bird can make use of the methods of Aves, but Parrot as a super class cannot access subclass members. Following figure gives a schematic representation of the multilevel hierarchy with the classes involved in the program. 2. Multiple Inheritance In multiple inheritance, one class extends multiple classes. Java does not support multiple inheritance but C++ supports. The above program can be modified to illustrate multiple inheritance. The following program does not work. calss Aves { } class Bird { }
24 publicclass Parrot extends Aves, Bird { } In the above code, Parrot extends both Aves and Bird. This is not supported by Java and the above code raises compilation error. Following is the schematic representation. Note: Java supports multiple inheritance partially through interfaces. 3. Hierarchical Inheritance In hierarchical type of inheritance, one class is extended by many subclasses. It is one- to-many relationship. A realtime example is available at dynamic binding. class Aves { publicvoid fly() { System.out.println("Generally, aves fly"); } } class Parrot extends Aves { publicvoid eat() { System.out.println("Parrot eats fruits and seeds"); } } class Vulture extends Aves { publicvoid vision() { System.out.println("Vulture can see from high altitudes"); } } publicclass FlyingCreatures { publicstaticvoid main(String args[]) { // all the following code is composition for FlyingCreatures Parrot p1 = new Parrot(); p1.eat(); // calling its own member p1.fly();
25 // calling super class member by inheritance Vulture v1 = new Vulture(); v1.vision(); // calling its own member v1.fly(); // calling super class member by inheritance }} Output screen of FlyingCreatures.java In the above code, Aves class is extended by two classes – Parrot and Vulture. Both classes can make use of the methods of Aves. Even though the Parrot and Vulture are subclasses of the same class Aves, but still they cannot make use of each other members. Parrot and Vulture are known as "siblings". Siblings are disjoint and they cannot make use of other members as between them no inheritance is involved (like two sons of a father; one son's property cannot be shared by other but both can share the property of father). Following is the schematic representation of the classes involved. Dynamic binding and dynamic polymorphism use hierarchical inheritance. Disadvantages of Inheritance 1. Both classes (super and subclasses) are tightly-coupled. 2. As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other. 3. Changing the code in super class method also affects the subclass functionality. 4. If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.
26 5. Explain the different ways to handle exceptions in java. (16) An exception is a problem that arises during the execution of a program. An exception can occur formany different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out ofmemory. Some of these exceptions are caused by user error, others by programmer error, and others byphysical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories ofexceptions: Checked exceptions: A checked exception is an exception that is typically a user error or aproblem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignoredat the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely doanything about an error. For example, if a stack overflow occurs, an error will arise. They are alsoignored at the time of compilation. Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is asubclass of the Throwable class. Other than the exception class there is another subclass calledError which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case ofsevere failures, which are not handled by the java programs. Errors are generated to indicate errorsgenerated by the runtime environment. Example : JVM is out of Memory. Normally programs cannotrecover from errors. The Exception class has two main subclasses: IOException class and RuntimeException Class.
27 Here is a list of most common checked and unchecked Java's Built-in Exceptions. Exceptions Methods: Following is the list of important medthods available in the Throwable class. Methods with Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message isinitialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage() 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error outputstream. 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0represents the top of the call stack, and the last element in the array represents themethod at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to anyprevious information in the stack trace. Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catchblock is placed around the code that might generate an exception. Code within a try/catch block isreferred to as protected code, and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block
28 } A catch statement involves declaring the type of exception you are trying to catch. If an exceptionoccurs in protected code, the catch block (or blocks) that follows the try is checked. If the type ofexception that occurred is listed in a catch block, the exception is passed to the catch block muchas an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd elementof the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks likethe following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of themafter a single try. If an exception occurs in the protected code, the exception is thrown to the firstcatch block in the list. If the data type of the exception thrown matches ExceptionType1, it getscaught there. If not, the exception passes down to the second catch statement. This continuesuntil the exception either is caught or falls through all
29 catches, in which case the current methodstops execution and the exception is thrown down to the previous method on the call stack. Example: Here is code segment showing how to use multiple try/catch statements. try { file = new FileInputStream(fileName); x = (byte) file.read(); }catch(IOException i) { i.printStackTrace(); return -1; }catch(FileNotFoundException f) //Not valid! { f.printStackTrace(); return -1; } The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throwskeyword. throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, byusing the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException: import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws aRemoteException and an InsufficientFundsException: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation }
30 //Remainder of class definition } The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of codealways executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, nomatter what happens in the protected code.A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. } Example: public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Note the following:
31 A catch clause cannot exist without a try statement.It is not compulsory to have finally clauses when ever a try/catch block is present.The try block cannot be present without either catch clause or finally clause.Any code cannot be present in between the try, catch, finally blocks. Declaring you own Exception: You can create your own exceptions in Java. Keep the following points in mind when writing your ownexception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a userdefinedexception that extends the Exception class, making it a checked exception. An exceptionclass is like any other class, containing useful fields and methods. Example: // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains awithdraw() method that throws an InsufficientFundsException. // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; }
32 public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods ofCheckingAccount. // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("nWithdrawing $100..."); c.withdraw(100.00); System.out.println("nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount());
33 e.printStackTrace(); } } } Compile all the above three files and run BankDemo, this would produce the following result: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM.Examples:NullPointerException,ArrayIndexOutOfBoundsException, ClassCastException, Programmatic exceptions: - These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException 6.Explain in detail about Multithreading in java. (16) Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates, because idle time is common. For example, the transmission rate of data over a network is much slower than the rate at which the computer can process it. Even local file system resources are read and written at a much slower pace than they can be processed by the CPU. And, of course, user input is much slower than the computer The Thread Class and the Runnable Interface Java‘s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. Since you can‘t directly refer to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it. To create a new thread, your program will either extend Thread or implement the Runnable interface. The Thread class defines several methods that help manage threads. The ones that will be used in this chapter are shown here:
34 The Main Thread When a Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons: • It is the thread from which other ―child‖ threads will be spawned. • Often, it must be the last thread to finish execution because it performs various shutdown actions. Creating a Thread In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished: • You can implement the Runnable interface. • You can extend the Thread class, itself. The following two sections look at each method, in turn. Implementing Runnable The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) Inside run( ), you will define the code that constitutes the new thread. It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run( ) returns. Here is an example that creates a new thread and starts it running: // Create a second thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() {
35 try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Inside NewThread‘s constructor, a new Thread object is created by the following statement: t = new Thread(this, "Demo Thread"); o/p: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
36 Creating Multiple Threads So far, you have been using only two threads: the main thread and one child thread. However, your program can spawn as many threads as it needs. For example, the following program creates three child threads: // Create multiple threads. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } The output from this program is shown here: New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] One: 5
37 Two: 5 Three: 5 One: 4 Two: 4 Three: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Main thread exiting.
38 UNIT –II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 PART-A: 1. What are the necessities of using HTML forms? Gathering user information Conducting Surveys Interactive services 2. Define HTML. It is a simple page description language, which enables document creation for the web. 3. What do you understand about DOCTYPE in HTML? A Document Type Declaration, or DOCTYPE, is an instruction that associates a particular SGML or XML document (for example, a web page) with a Document Type Definition(DTD) (for example, the formal definition of a particular version of HTML). It manifests as a short string of markup that conforms to a particular syntax. 4. What are the Hyperlink, Anchors and Link in the HTML? The <a> tag can be used in two ways: 1.To create a link to another document, by using the href attribute 2.To create a bookmark inside a document, by using the name attribute <a href="url">Link text</a> - The href attribute specifies the destination of a link. 5. How you define HTML Style Attribute in HTML? The <style> tag is used to define style information for an HTML document. Inside the style element you specify how HTML elements should render in a browser. The required type attribute defines the content of the style element. The only possible value is "text/css". The style element always goes inside the head section. <head> <styletype="text/css"> h1 {color:red}</style> </head> 6. HTML is case sensitive or not? Html is not a case sensitive language. <P> means the same as <p>.But a combination of upper and lower case letters must not be used. 7. How to use form’s action attribute and submit button in html? The required action attribute specifies where to send the form-data when a form is submitted. <form action="form_action.asp" method="get"> ,, </form> <input type="submit" /> defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. <input type="submit" value="Submit" /> 8. How to use Line Break and Horizontal Line tags in HTML? The <br> tag inserts a single line break. It‘s a empty tag, i.e. it has no end tag. The <hr> tag creates a horizontal line in the html page, and can be used to separate the contents in a html page. It is also an empty tag with no empty tag.
39 9. What are Style Sheets? CSS stands for Cascading Style Sheets. Styles define how to display HTML elements. Styles were added to HTML 4.0 to solve a problem. External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files. 10. List down the ways of including style information in a document. There are three main ways to include styles into a document namely, external style sheets, embedded style sheets and inline styles. 11. What are the style precedence rules when using multiple approaches? Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:  Browser default  External style sheet  Internal style sheet (in the head section)  Inline style (inside an HTML element) So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value). 12. Give the syntax to specify a characteristic in linked style sheet. {Characteristic:Value;} Multiple Characteristic/Values should be separated by semicolons. 13. List down font characteristics permitted in style sheets. Font – family, font – size, font – weight, font- style and font – variant. 14. How to toggle display an HTML element? An element in HTML can be toggle displayed using the style. Display parameter inside a separate toggle function. 15. What is the HTML DOM? The HTML DOM is: A standard object model for HTML A standard programming interface for HTML Platform- and language-independent A W3C standard The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.
40 UNIT-II PART -B 1. Explain Basic internet protocols and HTTP message format?(16) Internet Protocol: The Internet protocols are the world‘s most popular open-system (nonproprietary) protocol suite because they can be used to communicate across any set of interconnected networks and are equally well suited for LAN and WAN communications. The Internet protocols consist of a suite of communication protocols, of which the two best known are the Transmission Control Protocol (TCP) and the Internet Protocol (IP). The Internet protocol suite not only includes lower-layer protocols (such as TCP and IP), but it also specifies common applications such as electronic mail, terminal emulation, and file transfer. Internet protocols were first developed in the mid-1970s, when the Defense Advanced Research Projects Agency (DARPA) became interested in establishing a packet-switched network that would facilitate communication between dissimilar computer systems at research institutions. With the goal of heterogeneous connectivity in mind, DARPA funded research by Stanford University and Bolt, Beranek, and Newman (BBN). The result of this development effort was the Internet protocol suite, completed in the late 1970s. TCP/IP later was included with Berkeley Software Distribution (BSD) UNIX and has since become the foundation on which the Internet and the World Wide Web (WWW) are based
41 Internet Protocol (IP) The Internet Protocol (IP) is a network-layer (Layer 3) protocol that contains addressing information and some control information that enables packets to be routed. IP is documented in RFC 791 and is the primary network-layer protocol in the Internet protocol suite. Along with the Transmission Control Protocol (TCP), IP represents the heart of the Internet protocols. IP has two primary responsibilities: providing connectionless, best-effort delivery of datagram‘s through an internetwork; and providing fragmentation and reassembly of datagrams to support data links with different maximum-transmission unit (MTU) sizes. IP Packet Format An IP packet contains several types of information, as illustrated in Figure 30-2. The following discussion describes the IP packet fields illustrated in Figure 30-2: • Version—Indicates the version of IP currently used. • IP Header Length (IHL)—Indicates the datagram header length in 32-bit words. • Type-of-Service—Specifies how an upper-layer protocol would like a current datagram to be handled, and assigns datagrams various levels of importance. • Total Length—Specifies the length, in bytes, of the entire IP packet, including the data and header. • Identification—Contains an integer that identifies the current datagram. This field is used to help piece together datagram fragments. • Flags—Consists of a 3-bit field of which the two low-order (least-significant) bits control fragmentation. The low-order bit specifies whether the packet can be fragmented. The middle bit specifies whether the packet is the last fragment in a series of fragmented packets. The third or high-order bit is not used. • Fragment Offset—Indicates the position of the fragment‘s data relative to the beginning of the data in the original datagram, which allows the destination IP process to properly reconstruct the original datagram.
42 • Time-to-Live—Maintains a counter that gradually decrements down to zero, at which point the datagram is discarded. This keeps packets from looping endlessly. • Protocol—Indicates which upper-layer protocol receives incoming packets after IP processing is complete. • Header Checksum—Helps ensure IP header integrity. • Source Address—Specifies the sending node. • Destination Address—Specifies the receiving node. •Options—Allows IP to support various options, such as security. •Data—Contains upper-layer information HTTP message format: HyperText Transfer Protocol (HTTP) HTTP (Hypertext Transfer Protocol) is perhaps the most popular application protocol used in the Internet (or The WEB). HTTP is an asymmetric request-response client-server protocol as illustrated. An HTTP client sends a request message to an HTTP server. The server, in turn, returns a response message. In other words, HTTP is a pull protocol, the client pulls information from the server (instead of server pushes information down to the client).  HTTP is a stateless protocol. In other words, the current request does not know what has been done in the previous requests.  HTTP permits negotiating of data type and representation, so as to allow systems to be built independently of the data being transferred.  Quoting from the RFC2616: "The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. It is a generic, stateless, protocol which can be used for many tasks beyond its use for hypertext, such as name servers and distributed object management systems, through extension of its request methods, error codes and headers."
43 HTTP Request and Response Messages HTTP client and server communicate by sending text messages. The client sends a request message to the server. The server, in turn, returns a response message. An HTTP message consists of a message header and an optional message body, separated by a blank line, as illustrated below: HTTP Request Message The format of an HTTP request message is as follow: Request Line The first line of the header is called the request line, followed by optional request headers. The request line has the following syntax: request-method-name request-URI HTTP-version
44  request-method-name: HTTP protocol defines a set of request methods, e.g., GET, POST, HEAD, and OPTIONS. The client can use one of these methods to send a request to the server.  request-URI: specifies the resource requested.  HTTP-version: Two versions are currently in use: HTTP/1.0 and HTTP/1.1. Examples of request line are: GET /test.html HTTP/1.1 HEAD /query.html HTTP/1.0 POST /index.html HTTP/1.1 Request Headers The request headers are in the form of name:value pairs. Multiple values, separated by commas, can be specified. request-header-name: request-header-value1, request-header-value2, ... Examples of request headers are: Host: www.xyz.com Connection: Keep-Alive Accept: image/gif, image/jpeg, */* Accept-Language: us-en, fr, cn Example The following shows a sample HTTP request message: HTTP Response Message The format of the HTTP response message is as follows:
45 Status Line The first line is called the status line, followed by optional response header(s). The status line has the following syntax: HTTP-version status-code reason-phrase  HTTP-version: The HTTP version used in this session. Either HTTP/1.0 and HTTP/1.1.  status-code: a 3-digit number generated by the server to reflect the outcome of the request.  reason-phrase: gives a short explanation to the status code.  Common status code and reason phrase are "200 OK", "404 Not Found", "403 Forbidden", "500 Internal Server Error". Examples of status line are: HTTP/1.1 200 OK HTTP/1.0 404 Not Found HTTP/1.1 403 Forbidden Response Headers The response headers are in the form name:value pairs: response-header-name: response-header-value1, response-header-value2, ... Examples of response headers are: Content-Type: text/html Content-Length: 35 Connection: Keep-Alive Keep-Alive: timeout=15, max=100 The response message body contains the resource data requested. Example The following shows a sample response message: HTTP Request Methods HTTP protocol defines a set of request methods. A client can use one of these request methods to send a request message to an HTTP server. The methods are:  GET: A client can use the GET request to get a web resource from the server.  HEAD: A client can use the HEAD request to get the header that a GET request would have obtained. Since the header contains the last-modified date of the data, this can be used to check against the local cache copy.  POST: Used to post data up to the web server.
46  PUT: Ask the server to store the data.  DELETE: Ask the server to delete the data.  TRACE: Ask the server to return a diagnostic trace of the actions it takes.  OPTIONS: Ask the server to return the list of request methods it supports.  CONNECT: Used to tell a proxy to make a connection to another host and simply reply the content, without attempting to parse or cache it. This is often used to make SSL connection through the proxy.  Other extension methods. "GET" Request Method GET is the most common HTTP request method. A client can use the GET request method to request (or "get") for a piece of resource from an HTTP server. A GET request message takes the following syntax: GET request-URI HTTP-version (optional request headers) (blank line) (optional request body)  The keyword GET is case sensitive and must be in uppercase.  request-URI: specifies the path of resource requested, which must begin from the root "/" of the document base directory.  HTTP-version: Either HTTP/1.0 or HTTP/1.1. This client negotiates the protocol to be used for the current session. For example, the client may request to use HTTP/1.1. If the server does not support HTTP/1.1, it may inform the client in the response to use HTTP/1.0.  The client uses the optional request headers (such as Accept, Accept-Language, and etc) to negotiate with the server and ask the server to deliver the preferred contents (e.g., in the language that the client preferred).  GET request message has an optional request body which contains the query string (to be explained later). Response Status Code The first line of the response message (i.e., the status line) contains the response status code, which is generated by the server to indicate the outcome of the request. The status code is a 3-digit number:  1xx (Informational): Request received, server is continuing the process.  2xx (Success): The request was successfully received, understood, accepted and serviced.  3xx (Redirection): Further action must be taken in order to complete the request.  4xx (Client Error): The request contains bad syntax or cannot be understood.  5xx (Server Error): The server failed to fulfill an apparently valid request. Some commonly encountered status codes are:  100 Continue: The server received the request and in the process of giving the response.  200 OK: The request is fulfilled.  301 Move Permanently: The resource requested for has been permanently moved to a new location. The URL of the new location is given in the response header
47 called Location. The client should issue a new request to the new location. Application should update all references to this new location.  302 Found & Redirect (or Move Temporarily): Same as 301, but the new location is temporarily in nature. The client should issue a new request, but applications need not update the references.  304 Not Modified: In response to the If-Modified-Since conditional GET request, the server notifies that the resource requested has not been modified.  400 Bad Request: Server could not interpret or understand the request, probably syntax error in the request message.  401 Authentication Required: The requested resource is protected, and require client‘s credential (username/password). The client should re-submit the request with his credential (username/password).  403 Forbidden: Server refuses to supply the resource, regardless of identity of client.  404 Not Found: The requested resource cannot be found in the server.  405 Method Not Allowed: The request method used, e.g., POST, PUT, DELETE, is a valid method. However, the server does not allow that method for the resource requested.  408 Request Timeout:  414 Request URI too Large:  500 Internal Server Error: Server is confused, often caused by an error in the server-side program responding to the request.  501 Method Not Implemented: The request method used is invalid (could be caused by a typing error, e.g., "GET" misspell as "Get").  502 Bad Gateway: Proxy or Gateway indicates that it receives a bad response from the upstream server.  503 Service Unavailable: Server cannot response due to overloading or maintenance. The client can try again later.  504 Gateway Timeout: Proxy or Gateway indicates that it receives a timeout from an upstream server.
48 2. To create a web page that displays college information using various styles HTML CODE: <html> <head><h1><center>ALL STYLE SHEETS</center></h1> <title>USE of INTERNAL and EXTERNAL STYLESHEETS </title> <link rel="stylesheet" href="xyz.css" type="text/css"> <style type="text/css"> .vid{font-family:verdana;font-style:italic;color:red;text-align:center} .ani{font-family:tahoma;font-style:italic;font-size:20;text-align:center;} font{font-family:georgia;color:blue;font-size:20} ul{list-style-type:circle} </style> </head> <body> <ol style="list-style-type:lower-alpha"> <b>PERI GROUP OF COLLEGES</b><br><br><br> <li>Raj Engineering College <li>PERI University and Research Institute <li> College of Engineering, Bangalore <li>Tamilnadu College of Arts and Science </ol> <p style="font-size:20pt;color:purple">A.C.S GROUP OF COLLEGES</p> <p class="ani">CSS Group of colleges is owned by XXX.<br>It is approved by International Council It is affliated to JKK University.<br></p> <h2 class="vid">DES College of Engg</h2> <br> <font>It is an ISO certified Institution</font><br> <br> <font> <h2>List of Courses offered</h2> <ul> <li>Computer Science and Engineering</li> <li>Ece</li> <li>mech</li> <li>eee</li> </ul> </font> <h3>Results of cse students</h3> <table width="100%" cellspacing="2" cellpadding="2" border="5">
49 <tr> <th>S.NAME</th> <th>MARKS</th> <th>RESULT</th> </tr> <tr> <td align="center">Dinesh</td> <td align="center">100</td> <td align="center">pass</td> </tr> <tr> <td align="center">Bala</td> <td align="center">99</td> <td align="center">pass</td> </tr> <tr> <td align="center">Gopi</td> <td align="center">98</td> <td align="center">pass</td> </tr> </table> </body> </html> XYZ.CSS: h3{font-family:arial;font-size:20;color:cyan} table{border-color:green} td{font-size:20pt;color:magenta}
50 3. Explain XHTML Syntax and semantics with example.(16) XHTML – EXtensible HyperText Markup Language  is HTML defined as an XML application  is a stricter and cleaner HTML  is compatible to HTML 4.01 and supported by all browsers  is a W3C recommendation Why XHTML ? the following, ―bad‖ html document will work fine in most browser even if it does not follow HTML rules: <html> <head> <body> <p>a paragraph…<br> <a href=―#‖>test </html>  but browsers running on hand-held devices (e.g. mobile phones) have small computing power and can not interpret ―bad‖ markup language  HTML is designed to structure (and display) data and XML is designed to describe and structure data  XHTML specifies that everything must be marked up correctly  XHTML – base syntactic rules  XHTML elements must be properly nested <b><i> Italic and bold text </b></i> <b><i> Italic and bold text </i></b>  XHTML elements must always be closed <p> A paragraph… <br> <img src=―foo.jpg‖> <p> A paragraph…</p> <br /> <img src=―foo.jpg‖ />  XHTML elements must be in lowercase  XHTML elements must have one <html> root element (which contains a <head> and a <body>) XHTML – other syntactic rules  attribute names must be in lower case  attribute values must be quoted <table width=300px> <table width=―300px‖>  the ―id‖ attribute replaces the ―name‖ attribute  XHTML DTD defines mandatory elements  attribute minimization is forbidden <input checked>
51 <input disabled> <input checked=―checked‖ /> <input disabled=―disabled‖ /> General format of an XHTML document <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>…</title> </head> <body> … </body> </html> <!Doctype>,<html>,<head>,<title>,<body> are mandatory DTD – Document Type Definition  a DTD specifies the syntax of a document written in a SGML language (HTML, XHTML, XML) it specifies: o the hierarchical structure of the document, o element names and types o element content type o and attributes names and values o XML 1.0 has 3 DTDs: Strict, Transitional and Frameset DTD example (internal to XHTML file) <!DOCTYPE course [ <!ELEMENT course (lecture+)> <!ELEMENT lecture (title,bibliography,notes,examples)> <!ELEMENT title (#PCDATA)> <!ELEMENT bibliography (#PCDATA)> <!ELEMENT notes (#PCDATA)> <!ELEMENT examples (#PCDATA)> <!ATTLIST course professor CDATA #REQUIRED> <!ATTLIST course title CDATA #REQUIRED> <!ATTLIST course yearofstudy CDATA #REQUIRED> <!ATTLIST course date CDATA #IMPLIED> ]> XHTML validation  a valid XHTML document is an XHTML document which obeys the rules of the DTD specified by the <!Doctype> tag.  the official W3C XHTML validator:  http://validator.w3.org/check/referer  XHTML DTD is split in 28 modules
52 3. i)Design a HTML Form for aRailwaay Reservation System? (8) ii)Explain about different types of XHTML DTD(8) Design a HTML Form for aRailwaay Reservation System? <FOTRM METHOD=º Postº ACTION=http://server name/directory name/Script name><HR> PASSENGER NAME: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR> ADDRESS: <INPUT TYPE=º Textº Name=º addº MAXLENGTH=º 24º <BR> CITY: <INPUT TYPE=º Textº Name=º cityº MAXLENGTH=º 24º <BR> STATE: <INPUT TYPE=º Textº Name=º stateº MAXLENGTH=º 24º ZIP: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR> </HR> <INPUT TYPE=º submitº value=º reserveº ></FORM> ii)Explain about different types of XHTML DTD(8) Document Type Definitions (DTD) A DTD specifies the syntax of a web page in SGML DTDs are used by SGML applications, such as HTML, to specify rules for documents of a particular type, including a set of elements and entity declarations An XHTML DTD describes in precise, computer-readable language, the allowed syntax of XHTML markup There are three XHTML DTDs: STRICT TRANSITIONAL FRAMESET XHTML 1.0 Strict <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Use the strict DOCTYPE when you want really clean markup, free of presentational clutter. Use it together with CSS. XHTML 1.0 Transitional <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Use the transitional DOCTYPE when you want to still use HTML's presentational features. XHTML 1.0 Frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
53 4. Explain Style sheets syntax and types of css with example. Cascading Style Sheets (CSS) are a method of web design that formats web page content according to a presentation style specified by the web page author. There are several advantages to using CS to format the presentation elements of a web page. CSS essentially separates document content from the manner in which it is presented, thus allowing for more fluid transitions between various browser platforms. CSS also provides for more precise control for spacing, alignment, and positioning of content without relying on the need for layout tables or frames. Font style, color, and font size can all be manipulated using CSS as well. The basic CSS Syntax Selector: is the hook used to choose what part(s) of your HTML to apply the CSS to. It indicates the element to which the rule is applied. Following the selector is the... •Declaration Block:Everything within the curly brackets, ―{‖ and ―}‖, is called the declaration block •Declaration: Inside a declaration block you can have as many declarations as you want and each declaration is a combination of a CSS Property and a value. •Property:is one of the CSS Properties used to tell what part of the selector will be changed (or styled). It specifies a characteristic, such as color, font-family, position, and is followed by a colon (:) •Value:assigns a value to the property. Types of selectors CSS has several types of selectors. Explaining all of them in detail would take too long. We will just introduce you with two most commonly used selectors. For a really in depth study, you should look into the W3C specification for selectors. Class and ID selectors With the class selector you can define different styles for the same type of HTML element.In our example, the class selector would look like this: P.blue {color: blue;}
54 ID selector The W3C defines CSS ID as "a unique identifier to an element". IDs are commonly used for Layout and Uniqueness. Standards specify that any given ID name can only be referenced once within a page or document. From our experience, IDs are most commonly used correctly in CSS layouts. This makes sense because there are usually only one menu per page, one banner, and usually only one content pane. Grouping You can group selectors. Separate each selector with a comma H1, H2, H3, H4, H5, H6 {color: blue ;} Positioning The CSS positioning properties allow you to position an element. There are five different layout properties available in CSS: position: static, position: relative, position: absolute, and float. Three ways to insert CSS  Inline CSS  Internal Style Sheets  External Style Sheets Inline CSS The first way is called Inline Cascading Style Sheets. You can add CSS directly into the elements in your markup with the ―style‖ attribute. <div style=‖color:red;‖><p style=‖font-size:12px;‖> ―Style‖ is a ―Core HTML Attribute‖ so you can apply it to any visual HTML/XHTML elements. This may seem to be the easiest way of using CSS, but it is not recommended as it completely ignores the best parts of Cascading Style Sheets. Internal Style Sheets The second way adds CSS to a single document or web page by adding the following code into the <head> of your document using the <style> element. <style type="text/css"> hr {color: sienna} p {margin-left:20px} body {background-image:url("images/back40.gif")} </style> As you can see, <style> is an HTML element that is opened and closed. Within the <style> element is the CSS that will be applied to that page. There is no limit to the amount of CSS you can put inside the <style> element. You would enter this code in the <head> area of your web page (anywhere after <head> and before </head> in your HTML document) and that would apply this CSS to the elements of that web page. External Style Sheets The third and most advantageous way to embed CSS into a document uses External Cascading Style Sheets (or External Style Sheets). An external CSS file is simply a text file with a ―.css‖ extension. This file can then be included into many different pages.
55 This allows you to make one document that has the styling for your entire website. Then you include that file into every page of your website. This is the recommended way of using CSS in your website as it lets you make global visual changes (to an entire website) by only tweaking one file. For Example, let‘s say you have a website where all the paragraphs are black, and you want to change them to grey. Since you have an external Style Sheet, you just open up that one CSS file and change the style for paragraphs to: color:grey; Now all the paragraphs on your website are grey! Here is the code you need to link the css fileto your webpages‖: <link rel=“stylsheet” type="text/css" href=“style.css”> Media Types There are about 10 different media types in CSS, but most common types are Screen and Print. CSS today allows you to link to more than one style sheet in your web page. 5.i)Explain about internet and intranet with difference.(8) ii) Design a HTML document using relative positioning to nudge text to the left. Internet It is a worldwide system which has the following characteristics: Internet is a world-wide / global system of interconnected computer networks. Internet uses the standard Internet Protocol (TCP/IP) Every computer in internet is identified by a unique IP address. IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer‘s location. A special computer DNS (Domain Name Server) is used to give name to the IP Address so that user can locate a computer by a name.For example, a DNS server will resolve a name http://www.periit.com to a particular IP address to uniquely identify the computer on which this website is hosted. Internet is accessible to every user all over the world.
56 Intranet Intranet is system in which multiple PCs are connected to each other. PCs in intranet are not available to the world outside the intranet. Usually each company or organization has their own Intranet network and members/employees of that company can access the computers in their intranet. Each computer in Intranet is also identified by an IP Address which is unique among the computers in that Intranet. Similarities in Internet and Intranet Intranet uses the internet protocols such as TCP/IP and FTP. Intranet sites are accessible via web browser in similar way as websites in internet. But only members of Intranet network can access intranet hosted sites. In Intranet, own instant messengers can be used as similar to yahoo messenger/ gtalk over the internet. Differences in Internet and Intranet Internet is general to PCs all over the world whereas Intranet is specific to few PCs. Internet has wider access and provides a better access to websites to large population whereas Intranet is restricted. Internet is not as safe as Intranet as Intranet can be safely privatized as per the need. ii) Design a HTML document using relative positioning to nudge text to the left <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>
57 RelativePos.html </title> <style type="text/css"> .right { position:relative; right:0.25em } </style> </head> <body> <p> <span style="background-color:red">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Red</span> <span style="background-color:yellow">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Yellow</span> <span style="background-color:lime">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Green</span> </p> </body> </html>
58 UNIT –III CLIENT SIDE AND SERVER SIDE PROGRAMMING PART-A 1. How to create an Object in JavaScript? An object is just a special kind of data, with a collection of properties and methods. You can add properties to an object by simply giving it a value. The sytax: objName.propName 2. What is the result of below given line of code in Java Script? 5+4+”7” The answer is 97. Here 5 and 4 are integers, bt since 7 is enclosed within quotes, its considered as a string, and hence is not added. 3.What is undefined value means in JavaScript? Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist. 4. Which method is used to Clear an array using JavaScript? Clear() method is used to clear all the defined array. we use the clear() method which removes all elements from an Array instance. After removing the array by clear() method, the resulting array's length will become zero. 5.What will be the Output of the following using JavaScript document.Write(Math.Round(6.7)); The output will be 7. The math.round function is used to round off the value to the nearest higher integer value. 6.What should appear at the very end of your JavaScript? The <script LANGUAGE="JavaScript">tag 7.What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. 8. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: The tag handler class that defines the tag's behavior the tag library descriptor file that maps the XML element names to the tag implementations the JSP file that uses the tag library
59 9. What are the implicit objects? Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: –request ,response, pageContext, session application , out , config ,page ,exception 10. Compare Client side vs. server side scripting. Website scripts run in one of two places – the client side, also called the front-end, or the server side, also called the back-end. The client of a website refers to the web browser that is viewing it. The server of a website is the server that hosts it. Client side: JavaScript. Server side: PHP ,Ruby on Rails, ASP.NET 11. State the Servlet life cycle 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. 12. What is JavaScript? JavaScript is a programming language used to make web pages interactive. It runs on your visitor's computer and doesn't require constant downloads from your website. JavaScript is often used to create polls and quizzes 13. What is the purpose of cookies? Cookies make the interaction between users and websites faster and easier. Without cookies, it would be very difficult for a website to allow a visitor to fill up a shopping cart or to remember the user's preferences or registration details for a future visit. 14. What are the steps needs to establish JDBC connectivity? The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps −  Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code.  Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.  Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect.  Create Connection Object: Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection. 15. What is the difference between GET and POST method?  GET is a safe method (idempotent) where POST is non-idempotent method.
60  We can send limited data with GET method and it‘s sent in the header request URL whereas we can send large amount of data with POST because it‘s part of the body.  GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can‘t bookmark it.  GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.  Hyperlinks in a page uses GET method. 16. What is different between web server and application server? A web server responsibility is to handler HTTP requests from client browsers and responds with HTML response. A web server understands HTTP language and runs on HTTPprotocol. Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat. Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications. 17. What are different methods of session management in servlets? Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. Some of the common ways of session management in servlets are: 1. User Authentication 2. HTML Hidden Field 3. Cookies 4. URL Rewriting 5. Session Management API 18. What is difference between GenericServlet and HttpServlet? GenericServlet is protocol independent implementation of Servlet interface whereas HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that‘s why we extend HttpServlet class. HttpServlet class extends GenericServlet and also provide some other methods specific to HTTP protocol.
61 UNIT –III PART –B 1. Explain javascript variables and debuggers in detail . (16) JavaScript Variables JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names: Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character Because JavaScript is case-sensitive, variable names are case-sensitive. Declaring (Creating) JavaScript Variables Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var keyword: var x; var carname; After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them: var x=5; var carname="Volvo"; After the execution of the statements above, the variable x will hold the value 5, and carname will hold the valueVolvo. Assigning Values to Undeclared JavaScript Variables If you assign values to variables that have not yet been declared, the variables will automatically be declared. These statements: x=5; carname="Volvo"; have the same effect as: var x=5;
62 var carname="Volvo"; Redeclaring JavaScript Variables If you redeclare a JavaScript variable, it will not lose its original value. var x=5; var x; After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it. The Lifetime of JavaScript Variables If you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed 2. Discuss JavaScript Array object in detail. (16) JavaScript Arrays •Arrays are used to store lists or collections of items •Arrays in JavaScript are indexed by numbers from 0 •Array elements can be any type, even arrays or objects •An array‘s elements do not have to have the same type Creating Arrays Arrays can be created with the new keyword var(myArray(=(new(Array(); var(myArray(=(new(Array(―one‖,―two‖,(3); or with array literal syntax var(myArray(=([]; var(myArray(=([―one‖,(―two‖,(3]; Updating Array Elements Insert by index myArray[5](=(―new(item‖; Stack/queue-like interface myArray.push(―new(item‖); var(lastItem(=(myArray.pop(); var(firstItem(=(myArray.shift();
63 Iterating Over Arrays var$myArray$=$[]; var$i; myArray.push(―one‖); myArray.push(―two‖); myArray.push(―three‖); for$(i=0;$i<myArray.length();$i+=1)${ console.log(myArray[i]); } Other Array Methods var arrayLength = myArray.length(); myArray.length = 4; myArray.reverse(); myArray.sort(); myArray.indexOf(―this item‖); myArray.lastIndexOf(―this item‖); JavaScript Objects •Most things in JavaScript is an object - even functions •Objects have properties and methods •This distinction is vague, as functions are ‗first class‘ •Prototypes rather than class-based inheritance •The this keyword refers to the current object Creating Objects var(obj1(=(new(Object(); var(emptyObject(=({}; var(myObject(=({ ((((val1:(3, ((((val2:(―x‖, ((((func:(function()({ ((((((((console.log(this.val1(+(―(―(+ ((((((((((((((((((((this.val2); ((((} } Aside: Anonymous Functions •The value assigned to this.func may look a little odd •It is an an anonymous function, a function with no name •This is much the same as any other function, but it doesn‘t have a name •Anonymous functions can have parameters, and are commonly used when a function will be used just once •This simplifies code and reduces namespace clutter
64 Using Objects •You can dynamically add and update properties •myObj.newVal(=(―New(property‖; •myObj.val1(=(5; •You can call methods (properties which are functions) •myObj.func; Object Constructors function(MyConstructor()({ ((((this.val1(=(3; ((((this.val2(=(―x‖; ((((this.func(=(function()({ ((((((((console.log(this.val1(+(―(―(+ ((((((((((((((((((((this.val2); ((((} } var(myObject(=(new(MyConstructor(); The this Keyword •Note that the constructor assigns properties to this •What exactly this is depends on the context •In a constructor, this is the new object •In an object‘s method, this is the object itself •In a callback, this is the object that was triggered •In a browser, this is the window object by default Array-Like Objects •Some JavaScript objects look like arrays (but aren‘t) •document.getElementsByTagName(―p‖); •They can be indexed with [] and have .length •They don‘t have sort, push, etc. •If you add elements then .length doesn‘t change •What‘s going on here? •Objects can be indexed using [] as associative maps •Property names are given inside the brackets •And length is just another property var$obj$=${length:$2}; obj[0]$=$―one‖;$obj[1]$=$―two‖; obj.length$=$2; var$obj2$=${0:―one‖,$1:―two‖,$length:2};
65 3. Write java script to perform all arithmetic operation (16) <html> <head> <title> Arithmatic Operation </title> <script type="text/javascript"> var n1,n2,r; function add() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1+n2; document.myform.result.value=r; } function sub() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1-n2; document.myform.result.value=r; } function mul() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1*n2; document.myform.result.value=r; } function divide() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1/n2; document.myform.result.value=r; } </script> </head> <body> <form name="myform">
66 <h1 align="center"> Arithmatic Operations</h1> <hr color="red"> <center><u>Enter a number in each text box </u><br><br> Number 1:<input type="text" name="n1" value=""> <br><br> Number 2:<input type="text" name="n2" value=""> <br><br> <input type="button" value="Add" onClick="add()"> <input type="button" value="Subtract" onClick="sub()"> <input type="button" value="Multiply" onClick="mul()" > <input type="button" value="Divide" onClick="divide()"><br><br> <font color="red">Result is: <input type="text" name="result" value=""></center></font> </form> </body> </html> Output:
67 4. Explain DOM event handling in detail.(16) Document Object Model (DOM) ●Standard way of referring to an XML and HTML documents ●Returns to the notion of XML/HTML as a tree of nodes ●Sound familiar? ●Languages like JavaScript, implement the DOM to refer to the document root and its children as objects ● Once accessed, possible to manipulate the document structure <aside> DOM Support ●Proprietary at first ● W3C standardized ● Modern browsers support at least DOM Level 2 document Object ● Type HTMLDocument ● Always refers to the document root ● Properties ● offsetWidth/offsetHeight – dimensions of document ● Methods ● getElementById( id ) – return an Element object matching the given id ●createElement(tagName ) – create an Element instance, which may be later added to the document tree window Object ● Type Window ● Refers to the actual browser window ● Properties ●screen – provides information about the user's display ●Methods ●resizeTo(x, y) – resizes the window DOM Element Objects ●Actual HTML/XML elements ●Properties ●childNodes – array of element's children, including text nodes if any ●attributes – array of attribute-value pairs ●innerHTML – inner content of an element, read/write ●Methods ●appendChild(node) – Inserts a node at the end of the current node DOM Text Nodes ●Text content is treated as a node in the tree ●Typically seen as a child of another Element object
68 CSS Properties ●All CSS properties can be manipulated through the DOM ●Use the style property ●CSS properties are camelCase ●document.body.style.fontFamily = ―Verdana‖; DOM Events ●JavaScript can be triggered in response to events ●Done by implementing event listeners, called when events fire ●Event triggers ●User-driven (mouse/keyboard events) ●Document/Window (load, resize, scroll...) ●Form submissions Event Handling ●Find the element object ●Register the event handler ●element.onclick = foo; ●Many other triggers exist... ●Write the event handler ●function foo(e) { if (!e) var e = window.event; // Required for IE /* Do stuff */ } ●Could be an anonymous function! <aside> Inline Event Handling ●Some may have seen something like <body onload=‖foo()‖> ●Run into same maintenance issues as with CSS! ●Event handling within the script itself is always preferred Event Objects ●Whenever an event fires, information about the triggering event is passed to the event handler via an Event object ●Properties of this object can be checked for more information if needed ●type – Type of triggering event (mouseover, click, etc) ●timeStamp – When the event occurred ●Not all are compatible cross-browser! Event Propagation ●If an element and its child share an event handler, which fires first? ●Used to depend heavily on the browser... ●Netscape: ―The parent!‖ (Event Capturing) ●Microsoft: ―No, the child!‖ (Event Bubbling) ●W3C: ―...Fine. You're both right!‖
69 W3C Event Propagation ●Event Capturing Phasehappens first ●Resolve in parent->child order ●Events are captured as they decend the DOM ●Event capturing ends when the target node is reached ●Event Bubbling Phasehappens next ●Resolve in child->parent order ●Events bubble upthrough the DOM W3C Event Propagation ●The developer can choose whether their event fires during event capturing or event bubbling ●By default, element.onclick = foo; syntax uses event bubbling 5. Write java servlet programs to conduct online examination and to display student mark list available in a database (16) SERVLET CODE: import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class StudentServlet3 extends HttpServlet { String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5; int Total=0; Connection connect; Statement stmt=null; ResultSet rs=null; public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletExcep- tion,IOException { try { String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connect=DriverManager.getConnection(url," "," "); message="Thank you for participating in online Exam"; } catch(ClassNotFoundException cnfex){ cnfex.printStackTrace(); } catch(SQLException sqlex){ sqlex.printStackTrace(); } catch(Exception excp){ excp.printStackTrace(); } Seat_no=request.getParameter("Seat_no"); Name=request.getParameter("Name"); ans1=request.getParameter("group1"); ans2=request.getParameter("group2"); ans3=request.getParameter("group3"); ans4=request.getParameter("group4"); ans5=request.getParameter("group5"); if(ans1.equals("True")) Total+=2; if(ans2.equals("False")) Total+=2; if(ans3.equals("True"))
70 Total+=2; if(ans4.equals("False")) Total+=2; if(ans5.equals("False")) Total+=2; try { Statement stmt=connect.createStatement(); String query="INSERT INTO student("+"Seat_no,Name,Total"+") VAL- UES('"+Seat_no+"','"+Name+"','"+Total+"')"; int result=stmt.executeUpdate(query); stmt.close(); }catch(SQLException ex){ } response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body bgcolor=cyan>"); out.println("<center>"); out.println("<h1>"+message+"</h1>n"); out.println("<h3>Yours results stored in our database</h3>"); out.print("<br><br>"); out.println("<b>"+"Participants and their Marks"+"</b>"); out.println("<table border=5>"); try { Statement stmt=connect.createStatement(); String query="SELECT * FROM student"; rs=stmt.executeQuery(query); out.println("<th>"+"Seat_no"+"</th>"); out.println("<th>"+"Name"+"</th>"); out.println("<th>"+"Marks"+"</th>"); while(rs.next()) { out.println("<tr>"); out.print("<td>"+rs.getInt(1)+"</td>"); out.print("<td>"+rs.getString(2)+"</td>"); out.print("<td>"+rs.getString(3)+"</td>"); out.println("</tr>"); } out.println("</table>"); } catch(SQLException ex){ } finally { try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(connect!=null) connect.close(); } catch(SQLException e){ } } out.println("</center>"); out.println("</body></html>"); Total=0; } }
71 HTML CODE: <html> <head><title>Database Test</title></head> <body> <center> <h1>Online Examination</h1> </center> <form action="StudentServlet3.view" method="POST"> <div align="left"><br></div> <b>Seat Number:</b> <input type="text" name="Seat_no"> <div align="Right"> <b>Name:</b> <input type="text" name="Name" size="50"><br> </div> <br><br> <b>1. Every host implements transport layer.</b><br/> <input type="radio" name="group1" value="True">True <input type="radio" name="group1" value="False">False<br> <b>2. It is a network layer's responsibility to forward packets reliably from source to destina- tion</b><br/> <input type="radio" name="group2" value="True">True <input type="radio" name="group2" value="False">False<br> <b>3. Packet switching is more useful in bursty traffic</b><br/> <input type="radio" name="group3" value="True">True <input type="radio" name="group3" value="False">False<br> <b>4. A phone network uses packet switching</b><br/> <input type="radio" name="group4" value="True">True <input type="radio" name="group4" value="False">False<br> <b>5. HTML is a Protocol for describing web contents</b><br/> <input type="radio" name="group5" value="True">True <input type="radio" name="group5" value="False">False<br> <br><br><br> <center> <input type="submit" value="Submit"><br><br> </center> </form> </body> </html>
72
73 UNIT-IV PHP and XML PART –A 1.Mention the rules of well-formed XML. All XML Elements Must Have a Closing Tag XML Tags are Case Sensitive XML Elements Must be Properly Nested XML Documents Must Have a Root Element XML Attribute Values Must be Quoted the white-space in a document is not truncated. 2.What is the DOM? The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. The DOM defines a standard for accessing documents like HTML and XML: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." 3. What is the XML DOM? The XML DOM defines the objects and properties of all XML elements, and the methods (interface) to access them. 4. What is the XMLHttpRequest Object? The XMLHttpRequest object is used to exchange data with a server behind the scenes. The XMLHttpRequest object is a developer's dream, because you can:  Update a web page without reloading the page  Request data from a server after the page has loaded  Receive data from a server after the page has loaded  Send data to a server in the background 5. What is XSL-FO? XSL-FO is about formatting XML data for output.  XSL-FO is a language for formatting XML data  XSL-FO stands for Extensible Stylesheet Language Formatting Objects  XSL-FO is based on XML  XSL-FO is a W3C Recommendation  XSL-FO is now formally named XSL 6. What is XSL-FO Documents? Explain XSL-FO Documents structure XSL-FO documents are XML files with output information. XSL-FO documents are stored in files with a .fo or a .fob file extension. You can also store XSL-FO documents with an .xml extension (to make them more accessible to XML editors).
74 ?xml version="1.0" encoding="ISO-8859-1"?> <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="A4"> <!-- Page template goes here --> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="A4"> <!-- Page content goes here --> </fo:page-sequence> </fo:root> XSL-FO documents are XML documents, and must always start with an XML declaration: The <fo:root> element is the root element of XSL-FO documents. The root element also declares the namespace for XSL-FO: The <fo:layout-master-set> element contains one or more page templates: Each <fo:simple-page-master> element contains a single page template. Each template must have a unique name (master-name): One or more <fo:page-sequence> elements describe the page contents. The master- reference attribute refers to the simple-page-master template with the same name: 7. What is XSL-FO Processors? An XSL-FO processor is a software program for formatting XSL documents for output. Most XSL-FO processors can output HTML, PDF documents and quality print. 8. Explain XML Attributes with an example Attributes often provide information that is not a part of the data. Attribute values must always be quoted. Either single or double quotes can be used Some of the problems with using attributes are:  attributes cannot contain multiple values (elements can)  attributes cannot contain tree structures (elements can)  attributes are not easily expandable (for future changes) Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data. 9. XML Elements vs. Attributes. <person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> <person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
75 In the first example sex is an attribute. In the last, sex is an element. Both examples provide the same information. There are no rules about when to use attributes or when to use elements. Attributes are handy in HTML. But in XML it is better to use elements. 10. What are the problems with using XML attributes? Some of the problems with using attributes are:attributes cannot contain multiple values (elements can)attributes cannot contain tree structures (elements can)attributes are not easily expandable (for future changes) 11. What is XSLT? XSLT is the recommended style sheet language of XML. XSLT (eXtensible Stylesheet Language Transformations) is far more sophisticated than CSS. XSLT can be used to transform XML into HTML. 12. What are the roles of XSLT? The roles of XSLT are: XSLT is used to transform an XML document into another XML document such as HTML, etc. XSLT can be used to add or remove elements and attributes to or from the output file. XSLT can also be used for rearranging and sorting elements.It can also be used for performing tests and making decisions about hiding and displaying of elements 13.What is XSLT? Explain its relationships with XSL XSLT stands for eXtensible Stylesheet Language Transformations. It is a language used to convert XML documents to XHTML or other XML documents. This conversion is done by transforming each XML element into an (X)HTML element.. it uses XPath to find information in a XML document. XSLT is nothing but transforming XSL‘s. Xpath defines the parts of the source document that must match one or more predefined templates. Once a match is found, XSLT will transform the match into the result document. 14.What is XSLT stylesheet? XSL stylesheet is just like a XML document used as a program text or a source. It contains sets of rules and instructions used for transformations. XSLT stylesheet along with the XML source documents are the inputs to the XSLT processor. The template rule contains two parts: a pattern used to match the nodes in the source document and a template which can be instantiated to form part of the result tree. A stylesheet is represented by an xsl:stylesheet element in an XML document. 15.Discuss the role of XPATH XPATH is used to scan the XML document for navigation of elements and attributes. It contains a library of standard functions string ad numeric values. For navigation, XPATH makes use of path expressions to select nodes or sets of nodes in a XML document.
76 16.Explain the XSLT data model XSLT shares the same data model of XPATH with some additions. XSLT accepts a XSLT stylesheet as an input and output is another XML, text or another document. The model is based on text nodes. These text nodes are embedded within element nodes. The model is a hierarchical structure like a tree. The tree has a variety of nodes like- text nodes, attribute nodes, element nodes, comment nodes, and processing instruction nodes. For every node type there is a way of determining a string-value for a node of that type. 17.Why the need for XHTML? If a script in an HTML document is not well formed, small devices like mobile phones fail to display the content properly. Also, upgrading all the browsers to support XML is a timely affair. An intermediate solution is XHTML that is a combination of HTML and XML. In XTML the content has to be well formed so that there is no bad HTML 18.What is XQuery language? XQuery is a way to query the XML data, It is built on XPath expressions and is supported by quite a few database engines. It can find and extract elements and attributes from XML documents. 19.Explain the Relation between RSS and XML XML or Extensible Markup Language is used to organize generic information with tags in a structured document. Really Simple Syndication is an extension of XML is used to o organize headlines of news. RSS formats are specified using XML and can be considered as an extended schemas of XML. 20. Define. DOM The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use. The public interface of a DOM is specified in its application programming interface (API).
77 UNIT-IV PART –B 1. Given an XSLT document and a source XML document explain the XSLT transformation process that produces a single result XML document. (16) XSL XSL is stands for eXtensible Style sheet Language which is an xml vocabulary. It contains two types of information: Template data: Which is text that is copied to output xml document with change or no change. XSL markup: which controls transformation process. It uses two namespaces: o http://www.w3.org/1999/xsl/Transform is the namespace name for xsl namespace o http://www.w3.org/1999/xhtml is the xhtml namesapce name XSL components: Three components 1. XSLT 2. XPATH 3. XSL-FO XSLT – XSL Transformations (XSLT) is a language to specify transformations of XML documents. A transformation expressed in XSLT describes rules for transforming a source tree into a result tree XPATH- is used to find information in an XML document. It navigates through elements and attributes in XML documents. XSL-FO is a XSL Formatter an xml vocabulary for defining style properties of xml document. To transform xml document the following things are required: a. Source xml document b. Xslt style sheet that defines the information of source xml program to be transformed c. Xslt processor that performs transformation The following program illustrates that.
78 The JAXP is a tool which is used as XSLT processor. The XSLT processor receives xslt and xml program as its input and generates another xml program as its output where we can see the content retrieved from source xml program You can refer lab experiment also Example for XSLT Step 1. Create an XML file and save as The code for the emp.xml file is given below: <?xml version = "1.0" ? > <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Nisha </Emp_Name> <Emp_E-mail> Nisha1@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit</Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail> Step 2: Create an XSLT Stylesheetand save as myXSL.xsl extension <?xml version="1.0" ?> <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html><head><title> XSL for Transforamtion </title> <body><p> <xsl:for-each select="Employee"> <xsl:value-of select="child::Emp_Id"/> <xsl:value-of select="child::Emp_Name"/> <xsl:value-of select="child::Emp_E-mail"/> </xsl:for-each> </p></body></html> </xsl:template> </xsl:stylesheet> Step 3: Create XML Transformer program in java and give input both .xml and .xsl file import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.Source; import javax.xml.transform.Result; import javax.xml.transform.OutputKeys; public class XMLwithXSLT { public static void main(String[] args) throws Exception { Sourcesource= new StreamSource("myXML.xml"); Source xsl= new StreamSource("myXSL.xsl");
79 TransformerFactoryfactory= TransformerFactory.newInstance(); Transformertransformer= factory.newTransformer(xsl); new StreamResult(System.out); } } Output of the program:- The following figure illustrates how the xslt transformer constructs the source tree from source xml document and by using that with the help of xsl program how the result tree is constructed. Result tree is constructed base on the following definitions given in xsl style sheet <html> <head><title> XSL for Transforamtion </title> <body><p> <xsl:for-each select="Employee"> <xsl:value-of select="child::Emp_Id"/> <xsl:value-of select="child::Emp_Name"/> <xsl:value-of select="child::Emp_E-mail"/> </xsl:for-each> </p></body> </html> </xsl:template>
80 2.Write a program to display student information using XSLT in XML document (16) Step no. Details of the step 1 Start the program 2 Create an XML document with the details of the student such as name, address, standard and mark. 3 Import an XSL file to the xml file. 4 The XSL file imported puts the details of the students given in the xml file in a table and gets the details of each student from the xml file using the value-of attribute. 5 The output in the browser would be the details from the XML file with the style specified in XSL applied to it. 6 Stop the program. Info.XML: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="detail.xsl"?> <student> <personal_info> <name>gokila</name> <addr>neyveli</addr> <std>3rd yr</std> <mark>98</mark> </personal_info> <personal_info> <name>sivamani</name> <addr>andimadam</addr> <std>3rd yr</std> <mark>95</mark> </personal_info> <personal_info> <name>sivasangari</name> <addr>kumbakonam</addr> <std>3rd yr</std> <mark>98</mark> </personal_info> <personal_info> <name>sangeetha</name> <addr>pennadam</addr> <std>3rd yr</std>
81 <mark>88</mark> </personal_info> </student> Detail.XSL: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body bgcolor="pink"> <center><h2>student database</h2></center> <center> <table bgcolor="aqua" border="7" width="650" height="400"> <tr> <th>name</th> <th>addr</th> <th>std</th> <th>mark</th> </tr> <xsl:for-each select="student/personal_info"> <xsl:sort select="mark"/> <tr> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="addr"/></td> <td><xsl:value-of select="std"/></td> <td><xsl:value-of select="mark"/></td> </tr> </xsl:for-each> </table> </center> </body> </html> </xsl:template> </xsl:stylesheet>
82 3. i)Explain the role XML namespaces with an example.(8) (ii)Explain the feature of XML path.(8) XML namespace provide a method to avoid elemwnt name conflicts.It is a collection of element and attribute names associated with a particular XML vocabulary through an absolute URI known as namespace name. Default namespace: <html xmlns=‖http:// www.w3.org/1999/xhtml‖> <element name xmlns:prefix=‖namespace identifier ―> Another form of xml attribute known as namespace declaration XML document 1 <table> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table> XML document2 <table> <name> Coffee Table</name> <width>80</width> <length>120</length> </table> If these XML fragments were added together, there would be a name conflict. Both contain a <table> element, but the elements have different content and meaning. Such name conflicts in XML can easily be avoided using a name prefix as shown below: <h:table> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI" For example, <h:table xmlns:h="http://www.w3.org/table"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="http://www.w3.org/furniture"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table>
83 Default namespace Default xml namespace uri for elements of a Document is: xmlns:‖http://www.w3.org/1999/xhtml‖ (ii)Explain the feature of XML path. (8) XPATH Is the syntax for specifying a collection of elements on other info contained within xml doc. XPATH expression will be applied to parse the xml doc. which constructs a tree like representation of xml doc. similar to DOM tree. The root of the XPath parse tree is ‗document‘ Location Paths <xsl:template match="/"> which represents the XPath document root. An XPath expression such as this represents one or more nodes within XPath parse tree is known as location path. This location path consists a ‗location step‘ Location step has two parts: An axis name followed by (::) Node test child::Emp_Id is an example of a location step and has two parts: Axis name specifies the direction to which we can search a node Node test specifies an element name selected for transformation Axis name: The following are several axis names uses to search a particular element in the xml doc Predicate: XPath uses some predicate which constructs the node test. Predicate can be either child::<element name> (Or) Attribute::<value> XPAth last() function always returns the no of nodes in the list being filtered, the value of position() function depends on the axis of the location step. Some XPXath predicates: 1.related node exists child::title node has child element of type title. 2. Attribute exists attribute::display node has attribute named display.
84 Location path: It can consists of several location steps separated by / characters , as in Child :: para/child:: strong First the leftmost location step is evaluated, producing a node list. Given example evaluation of the given location path with respect to the following XML document. <body> <para id=‖p1‖> This is <strong id =‖s1‖> important </strong> to know <strong id=‖s2‖> important </strong> </para> <para id =‖p2‖> This is not as important. <em> <strong id=‖s3‖> Is this? </strong></em> </para> </body> Absolute and Relative Location Path A location path can consists of several location steps separated by / character. For example, The difference between these two types of paths is that an absolute path begins with a slash(/) while a relative path doesnot.specifically a relative location path defines a set of nodes relative to the context node, while an absolute location path defines a set of nodes relative to the document root. Combining Node lists The pipe symbol(|) can be used to represent a node set produced by taking the union of the nodes sets returned by multiple location path. Thus ,The XPATH expression Child :: strong |descendant :: emph Represents a node set containing all of the strong children of the context node as well as all of its emph descendants.
85 4. Explain the model view controller architecture pattern in detail. (16) Many web applications are based on the Model-View-Controller (MVC) architecture pattern. That is, web apps contains three parts: 1) business logic 2) presentation and 3) request processing The key motivation behind the MVC approach is the desire to separate the code that creates and manipulates the data (i.e business logic) from the code that presents the data (i.e presentation) and the code that process the request (i.e controller) Business logic means the codeapplied for manipulation of application data and presentation refers the code written for look and feel of the web page such as background color, font style, placing of form controls and so on. Controller means that process the request message. According to MVC, the Model corresponds to business logic, the View corresponds to presentation and the Controller corresponds to request processing Typical JSP implementation of MVC
86 Java servlet program is the Controller component that receives the request from the browser. Java bean class is the Modelcomponent that processes the business logic which can use the data source for that. Jsp is the View component that presents theresult of the business logic to the browser with the help of controller. The following program also illustrates that. In this architecture, JSP is used for creating the view for the application. A centralized Servlet is used to handle the entire request for the application. The Servlet works as the controller for the application. It then uses the Java beans for processing the business logic and getting the (Model) from the database. Finally it uses the JSP to render the view which is displayed to the user. Advantage of using MVC - MVC allows the developer to keep the separation between business logic, presentation and request processing. Due to this separation, any changes to the presentation can be made easy without disturbing business logic data 5. Write Programs using XML – Schema – XSLT/XSL (16) <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>two of our famous Belgian Waffles with plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name>
87 <price>$7.95</price> <description>light Belgian waffles covered with strawberries and whipped cream</description> <calories>900</calories> </food> <food> <name>Berry-Berry Belgian Waffles</name> <price>$8.95</price> <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> <calories>900</calories> </food><food> <name>French Toast</name> <price>$4.50</price> <description>thick slices made from our homemade sourdough bread</description> <calories>600</calories> </food> <food> <name>Homestyle Breakfast</name> <price>$6.95</price> <description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> <calories>950</calories> </food> </breakfast_menu> XSLT File <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE"> <xsl:for-each select="breakfast_menu/food"> <div style="background-color:teal;color:white;padding:4px"> <span style="font-weight:bold"><xsl:value-of select="name"/></span> <xsl:value-of select="price"/> </div> <div style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <xsl:value-of select="description"/> <span style="font-style:italic"> <xsl:value-of select="calories"/> (calories per serving) </span> </div> </xsl:for-each> </body> </html>
88 UNIT V – INTRODUCTION TO AJAX and WEB SERVICES PART –A 1. What is DTD? Explain it with example. The purpose of a DTD (Document Type Definition) is to define the legal building blocks of an XML document. A DTD is a set of rules that specifies how to use XML markup. It contains Specifications. For each element, including what the element's attributes are, what values the attributes ca take on and what elements can be contained in others. A DTD defines the document structure with a list of legal elements and attributes. If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the following syntax: <!DOCTYPE root-element [element-declarations]> With a DTD, each of your XML files can carry a description of its own format. With a DTD, independent groups of people can agree to use a standard DTD for interchanging data. Your application can use a standard DTD to verify that the data you receive from the outside world is valid. You can also use a DTD to verify your own data. 2. What is AJAX? Ajax shorthand for Asynchronous JavaScript and XML) is a group of interrelated web development methods used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the ackground without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object. 3.What is a web service? Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system. XML is used to encode all communications to a Web service. 4.What is SOAP? SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another. 5. What is SOAP and how it will be utilized in web-components? SOAP stands for Simple Access protocol. SOAP was first offered in 1990's and has been introduced to W3C in 2000. The main purpose of SOAP to be able to send request to invoke programs on remote computers using XML wrappers.
89 6. Explain about the role of XML in SOAP? XML is chosen as a standard format because it was already in use by many large companies and immensely due to its open source nature. A wide variety of tools are available on helves which ease the process of transition to SOAP. XML can significantly reduce the speed and efficiency but binary XML is being considered as a format for future. 7.What are the elements which should be contained in SOAP message? Following elements are contained in the SOAP message. 1) An envelope element which identifies and translates the XML document into a SOAP message. 2) A header element is a must as it should contain header message. 3) A body is required which should contain call and response message. 4) Fault element is required which can communicate about the errors occurred during the process 8. What is SOAP? SOAP: Simple Object Access Protocol is a protocol that is used to exchange structured information at the time of implementing a web service. SOAP is relied on XML. Message format of SOAP usually relies on another protocol of different application layers. Among these the most notable application layer is Remote Procedure Call and HTTP. SOAP forms the foundation layer for web services protocol stack. This stack provides the basic framework for messaging on which the web services are built. 9. Explain web services architecture. Web Services are based on three operations: publish, find, and bind. Service providers publish services to a service broker. Service requesters find required services using a service broker and bind to them. 10. What is WSDL? Web Services Description Language (WSDL) is a format for describing a Web Services interface. It is a way to describe services and how they should be bound to specific network addresses
90 11. Differentiate between AJAX and Java Script AJAX JavaScript AJAX allows the coder send request data asynchronously in order load new data without changing the web page. JavaScript is a client side scripting language that allows the creation of dynamic web pages by providing a new level of interactivity. AJAX supports the server side scripting Language. JavaScript provides support to the client side scripting language. AJAX can load the web page after it is been loaded for the first time. JavaScript cannot load the pages after it is once loaded. AJAX does not install Trojan in the computer. JavaScript can install Trojan in the computer 12. What are the advantages of AJAX ?  XMLHttpRequest: The XMLHttpRequest of Ajax provides support to different kinds of HTTP request types. AJAX XMLHttpRequest can be used to send request for non-AJAX pages as well.  IFrame: The IFrame feature in AJAX supports every modern browser and asynchronous file uploads. AJAX can make request by both POST and GET methods.  Cookies: Even though there is an implementation difference between the browsers, the cookies in AJAX provides support for more number of browsers.  Interface: The interface in AJAX is very responsive. The required section of the page is transferred at a point of time rather than transferring the whole page.  Waiting Time: The waiting time in AJAX has been reduced.  Traffic: In AJAX, the traffic which occurs during the ‗To‘ and ‗From‘ process in the server has been reduced. 13. Define Web Service? A web service is a kind of software that is accessible on the Internet. It makes use of the XML messaging system and offers an easy to understand, interface for the end users. 14. Brief few drawbacks of using GET and POST methods to communicate with the web service? These methods are less secure and inhibit users to pass structures and objects as arguments. Also, it doesn‘t allow users to pass ByRef arguments. 15. Differentiate between a SOA and a Web service? SOA is a design and architecture to implement other services. SOA can be easily implemented using various protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP, RPC etc. While Web service, itself is an implemented technology. In fact one can implement SOA using the web service.
91 UNIT –V PART –B 1. Describe the significance and working of WSDL with an example WSDL stands for Web Services Description Language. It is the standard format for describing a web service. WSDL was developed jointly by Microsoft and IBM. Features of WSDL  WSDL is an XML-based protocol for information exchange in decentralized and distributed environments.  WSDL definitions describe how to access a web service and what operations it will perform.  WSDL is a language for describing how to interface with XML-based services.  WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an XML-based worldwide business registry.  WSDL is the language that UDDI uses.  WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'. WSDL Usage WSDL is often used in combination with SOAP and XML Schema to provide web services over the Internet. A client program connecting to a web service can read the WSDL to determine what functions are available on the server. Any special datatypes used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL. The three major elements of WSDL that can be defined separately are:  Types  Operations  Binding A WSDL document has various elements, but they are contained within these three main elements, which can be developed as separate documents and then they can be combined or reused to form complete WSDL files. WSDL Elements A WSDL document contains the following elements:  Definition : It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.  Data types : The data types to be used in the messages are in the form of XML schemas.  Message : It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.  Operation : It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.  Port type : It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings.  Binding : It is the concrete protocol and data formats for the operations and messages defined for a particular port type.
92  Port : It is a combination of a binding and a network address, providing the target address of the service communication.  Service : It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.In addition to these major elements, the WSDL specification also defines the following utility elements:  Documentation: This element is used to provide human-readable documentation and can be included inside any other WSDL element.  Import : This element is used to import other WSDL documents or XML Schemas. The WSDL Document Structure The main structure of a WSDL document looks like this: <definitions> <types> definition of types........ </types> <message> definition of a message.... </message> <portType> <operation> definition of a operation....... </operation> </portType> <binding> definition of a binding.... </binding> <service> definition of a service.... </service> </definitions> A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document Example Contents of HelloService.wsdl file: <definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
93 xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <message name="SayHelloRequest"> <part name="firstName" type="xsd:string"/> </message> <message name="SayHelloResponse"> <part name="greeting" type="xsd:string"/> </message> <portType name="Hello_PortType"> <operation name="sayHello"> <input message="tns:SayHelloRequest"/> <output message="tns:SayHelloResponse"/> </operation> </portType> <binding name="Hello_Binding" type="tns:Hello_PortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="sayHello"> <soap:operation soapAction="sayHello"/> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/> </input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/> </output> </operation> </binding> <service name="Hello_Service"> <documentation>WSDL File for HelloService</documentation> <port binding="tns:Hello_Binding" name="Hello_Port"> <soap:address location="http://www.examples.com/SayHello/" /> </port> </service> </definitions>
94 2. Describe the major elements of SOAP (16) SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification. A SOAP message is an ordinary XML document containing the following elements −  Envelope − Defines the start and the end of the message. It is a mandatory element.  Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.  Body − Contains the XML data comprising the message being sent. It is a mandatory element.  Fault − An optional Fault element that provides information about errors that occur while processing the message. All these elements are declared in the default namespace for the SOAP envelope − SOAP Message Structure The following block depicts the general structure of a SOAP message − <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap- envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Header> ... ... </SOAP-ENV:Header> <SOAP-ENV:Body> ... ... <SOAP-ENV:Fault> ... ... </SOAP-ENV:Fault> ... </SOAP-ENV:Body> </SOAP_ENV:Envelope> Example: SOAP request − POST /Quotation HTTP/1.0 Host: www.xyz.org Content-Type: text/xml; charset=utf-8 Content-Length: nnn <?xml version="1.0"?>
95 <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap- envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding" > <SOAP-ENV:Body xmlns:m="http://www.xyz.org/quotations" > <m:GetQuotation> <m:QuotationsName>MiscroSoft</m:QuotationsName> </m:GetQuotation> </SOAP-ENV:Body> </SOAP-ENV:Envelope> A corresponding SOAP response looks like − HTTP/1.0 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: nnn <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap- envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding" > <SOAP-ENV:Body xmlns:m="http://www.xyz.org/quotation" > <m:GetQuotationResponse> <m:Quotation>Here is the quotation</m:Quotation> </m:GetQuotationResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
96 3. Explain about AJAX Http Request Object (16) XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side. The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text. XMLHttpRequest Methods  abort() Cancels the current request.  getAllResponseHeaders() Returns the complete set of HTTP headers as a string.  getResponseHeader( headerName ) Returns the value of the specified HTTP header.  open( method, URL ) open( method, URL, async ) open( method, URL, async, userName ) open( method, URL, async, userName, password ) Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications) may be possible. The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing. send( content ) Sends the request. setRequestHeader( label, value ) Adds a label/value pair to the HTTP header to be sent. XMLHttpRequest Properties onreadystatechange An event handler for an event that fires at every state change. readyState The readyState property defines the current state of the XMLHttpRequest object. The following table provides a list of the possible values for the readyState property: State Description 0 The request is not initialized. 1 The request has been set up. 2 The request has been sent. 3 The request is in process. 4 The request is completed.
97 readyState = 0 After you have created the XMLHttpRequest object, but before you have called the open() method. readyState = 1 After you have called the open() method, but before you have called send(). readyState = 2 After you have called send(). readyState = 3 After the browser has established a communication with the server, but before the server has completed the response. readyState = 4 After the request has been completed, and the response data has been completely received from the server. responseText Returns the response as a string. responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties. status Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK"). statusText Returns the status as a string (e.g., "Not Found" or "OK"). Here is a list of some famous web applications that make use of AJAX. Google Maps A user can drag an entire map by using the mouse, rather than clicking on a button.  http://maps.google.com/ Google Suggest As you type, Google will offer suggestions. Use the arrow keys to navigate the results.  http://www.google.com/webhp?complete=1&hl=en Gmail Gmail is a webmail, built on the idea that email can be more intuitive, efficient and useful.  http://gmail.com/ Yahoo Maps (new) Now it's even easier and more fun to get where you're going!  http://maps.yahoo.com/
98 4. Explain in details about Web Services Conceptual Architecture (16) The Web Services Model The Web Services architecture is based upon the interactions between three roles: service provider, service registry and service requestor. The interactions involve the publish, find and bind operations. Together, these roles and operations act upon the Web Services artifacts: the Web service software module and its description. In a typical scenario, a service provider hosts a network-accessible software module (an implementation of a Web service). The service provider defines a service description for the Web service and publishes it to a service requestor or service registry. The service requestor uses a find operation to retrieve the service description locally or from the service registry and uses the service description to bind with the service provider and invoke or interact with the Web service implementation. Service provider and service requestor roles are logical constructs and a service can exhibit characteristics of both. Figure 1 illustrates these operations, the components providing them and their interactions Roles in a Web Services Architecture • Service provider. From a business perspective, this is the owner of the service. From an architectural perspective, this is the platform that hosts access to the service. • Service requestor. From a business perspective, this is the business that requires certain functions to be satisfied. From an architectural perspective, this is the application that is looking for and invoking or initiating an interaction with a service. The service requestor role can be played by a browser driven by a person or a program without a user interface, for example another Web service • Service registry. This is a searchable registry of service descriptions where service providers publish their service descriptions. Service requestors find services and obtain binding information (in the service descriptions) for services during development for static binding or during execution for dynamic binding. For statically bound service requestors, the service registry is an optional role in the architecture, because a service provider can send the description directly to service requestors. Likewise, service requestors can obtain a service description from other sources besides a service registry, such as a local file, FTP site, Web site, Advertisement and Discovery of Services (ADS) or Discovery of Web Services (DISCO).
99 Operations in Web Service Architecture For an application to take advantage of Web Services, three behaviors must take place: Publication of service descriptions, lookup or finding of service descriptions, and binding or invoking of services based on the service description. These behaviors can occur singly or iteratively. In detail, these operations are: • Publish. To be accessible, a service description needs to be published so that the service requestor can find it. Where it is published can vary depending upon the requirements of the application (see ―Service Publication‖ for more details). • Find. In the find operation, the service requestor retrieves a service description directly or queries the service registry for the type of service required (see ―Service Discovery‖ for more details). The find operation can be involved in two different lifecycle phases for the service requestor: at design time to retrieve the service‘s interface description for program development, and at runtime to retrieve the service‘s binding and location description for invocation. • Bind. Eventually, a service needs to be invoked. In the bind operation the service requestor invokes or initiates an interaction with the service at runtime using the binding details in the service description to locate, contact and invoke the service. The development lifecycle can have four phases: 1. Build The build phase of the lifecycle includes development and testing of the Web service implementation, the definition of the service interface description and the definition of the service implementation description. Web service implementations can be provided by creating new Web Services, transforming existing applications into Web Services, and composing new Web Services from other Web Services and applications. 2. Deploy The deploy phase includes the publication of the service interface and service implementation definition to a service requestor or service registry and deployment of the executables for the Web service into an execution environment (typically, a Web application server). 3. Run During the run phase, the Web service is available for invocation. At this point, the Web service is fully deployed, operational and network-accessible from the service provider. Now the service requestor can perform the find and bind operations. 4. Manage The manage phase covers ongoing management and administration of the Web service application. Security, availability, performance, quality of service and business processes must all be addressed The Web Services Stack To perform the three operations of publish, find and bind in an interoperable manner, there must be a Web Services stack that embraces standards at each level. Figure 2 shows a conceptual Web Services stack. The upper layers build upon the capabilities provided by the lower layers. The vertical towers represent requirements that must be addressed at every level of the stack. The text on the left represents standard technologies that apply at that layer of the stack.
100 5. Write a program to run and implement the web service (16) NewWebService.java: /*To change this template, choose Tools | Templates and open the template in the editor. */ package pack1; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import java.sql.*; /***@author SREC*/ @WebService() public class NewWebService { @WebMethod (operationName="get") public String[] get(@WebParam(name="from")String from,@WebParam (name="to")String to) { String hello[]=new String[6]; int i=0; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String filename = "d:/data1.mdb"; String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=true}"; Connection con = DriverManager.getConnection( database ,"",""); Statement s = con.createStatement(); s.execute("select * from details "); ResultSet rs = s.getResultSet(); if (rs != null) while ( rs.next() ) {
101 hello[i]= rs.getString("name"); i++; hello[i]= rs.getString("date"); i++; } } catch (Exception e) { System.out.println("Error: " + e); } return hello; }} Index.jsp: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <form name="air" action="action.jsp" method="post"> From<input type="text" name="from" id="from"><br/> To<input type="text" name="to" id="to"><br/> <input type="submit" value="GetDtails"> </form> </body> </html> Action.jsp: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <% String from1=request.getParameter("from"); String to1=request.getParameter("to"); %> <%-- start web service invocation --%><hr/> <% try {
102 pack1.NewWebServiceService service = new pack1.NewWebServiceService(); pack1.NewWebService port = service.getNewWebServicePort(); // TODO initialize WS operation arguments here java.lang.String from = from1; java.lang.String to = to1; // TODO process result here java.util.List<java.lang.String> result = port.get(from, to); out.println("Result = "+result); } catch (Exception ex) { // TODO handle custom exceptions here }%> <%-- end web service invocation --%><hr/> </body> </html>
103 UNIVERSITY QUESTION PAPER
104
105
106
107
108
109
110
111 CS6501- INTERNET PROGRAMMING UNIT WISE UNIVERSITY QUESTIONS UNIT I –JAVA PROGRAMMING PART A 1. Which method is used to set a priority for a thread? List out its priorities. (JUNE 2007) 2. How does one import a single package? (DEC 2010) 3. Define Objects and classes in java. (DEC 2010) 4. What is the difference between the static and non-static variables? (DEC 2010) 5. List out the Type of Arrays? (May 2014) 6. In java what is the use of Interfaces? (DEC 2010) 7. Can an abstract class be final? Why? (DEC 2010) 8. What is the difference between the String and String Buffer classes? ? (DEC 2010) 9. What is an anonymous inner class? ? (DEC 2010) 10. What are three ways in which a thread can enter the waiting state? ? (DEC 2010) 11. What are the different states in thread? (DEC 2010) 12. What is meant by Inheritance Hierarchy? Give an Example. (DEC 2010,Nov 2013,May 2011) 13. Define objects and object variable. (May 2012) 14. Define class.(Nov 2013) 15. Define interface and write the syntax of the Interface? (May 2014, NOV 2013) 16. Define Static inner classes? (May 2012) 17. What are threads? (May 2012) 18. What do you mean by Threads in java? (Nov 2013) 19. What is multithreading? (Nov 2013 , Nov2014) 20. What is the use of Final keyword? (May 2014) 21. What is Thread Safe? (May 2014 ) 22. List access specifiers used in Java. ( Nov2014) 23. What is meant by java package. ( Nov2014) 24. What is meant by abstract class. ( Nov2014) 25. Write the properties of thread. ( Nov2014) PART B 1. Write java application program for generating 4 threads to do the following operations. (JUNE 2007) (i) getting n numbers (ii) printing even numbers (iii) printing odd numbers (iv) printing average of a numbers 2. What is class? How do you define a class in java? (DEC 2010) 3. Explain the following in Strings : (1) Concatenation (2) Substrings. (DEC 2010) 4. Explain any four methods available in string handling. (DEC 2010)
112 5. What is a Package? How does a complier locate packages? (DEC 2010) 6. Explain arrays in java. (DEC 2010) 7. What is a Package? What are the benefits of using packages? Write down the steps in creating a package and using it in a java program with an example? (DEC 2010) 8. What is a thread? Explain its states and methods and Explain thread properties. (DEC 2010) 9. Explain how to create threads. Write a java program that prints numbers from 1 to 10 line by line after every 5 seconds. (DEC 2010) 10. Define package. Explain type of package with its importance.(8) (Nov 2011) 11. Explain any four string operations in java. With suitable example.(8) (Nov 2012) 12. State the properties of interfaces?(8) (Nov 2012) 13. Explain various state of thread (8) (Nov 2012) 14. Write in java program to iiustrate multithreaded programming(10) (May 2013,May 2014) 15. Explain how threads are created in java.(8) (May 2013) 16. Write about various threads states in java(8) (May 2013) 17. Explain the concept of inheritance with suitable example in java(8) (May 2013) 18. Explain Access specifier (8) (Nov 2013) 19. Explain packages with examples? (16) (May 2014) 20. Discuss about String(8) (May 2014) 21. Write in detail about the the following: (May 2014) i)Abstact Classes(8) ii) interfaces(8) UNIT-II: WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 PART-A 1. Give the syntax of a CSS rule. (Nov/Dec 2011) 2. Mention the need for cascading style sheets. (Apr/May 2011) 3. Give the core syntax of CSS. (May/June 2012) 4. Give example for inline style sheet? (May/June 2013) 5. What are the style sheets? (Nov/Dec 2013) 6. How external style sheet is useful in web page design. (May/June 2014) 7. List some HTML intrinsic attributes. (Apr/May 2011) PART-B: 1. Explain any eight CSS text properties. (8) (Nov/Dec 2011) 2. Explain in detail CSS border and CSS outline. (8) (Nov/Dec 2011) 3. Explain the features of cascading style sheets. (8) (Apr/May 2011) 4. Explain the CSS box model in detail. (8) (May/June 2012) 5. Write a CSS which adds bachground images and indentation? (8) (May/June 2013) 6. Explain external style sheet with an example? (8) (May/June 2013) 7. Discuss the various features of CSS with an example. (May/June 2014)
113 UNIT-III: CLIENT SIDE AND SERVER SIDE PROGRAMMING PART-A 1. What is a JavaScript statement? Give an example. (Nov/Dec 2011) 2. Explain array creation in Java script with example. (Apr/May 2011) 3. List and Explain any two java script built in objects. (May/June 2012) 4. Write down the purpose of Java script debuggers. (Nov/Dec 2012) 5. Deñne DOM. (Nov/Dec 2012) 6. List the different methods defined in document and window object of java script? (May/June 2013) 7. Mention the advantages of java/java scipt. (Nov/Dec 2013) 8. Write a java script to print ―GOOD DAY‖ using IF-ELSE condition. (May/June 2014) 9. Write code to return the full URL of a document. (Nov/Dec 2011) 10. How is session tracking achieved by URL rewriting? (Nov/Dec 2011) 11. Explain in brief the interaction between a web server and a Servlet. (Apr/May 2011) 12. What is meant by intrinsic event handling? (May/June 2012) 13. Compare Client side vs. server side scripting. (Nov/Dec 2012) 14. State the Servlet life cycle. (Nov/Dec 2012) 15. List the different life cycle methods of java servlets ? (May/June 2013) 16. What is the purpose of cookies? (May/June 2013) 17. List any two keyboard events. (Nov/Dec 2013) 18. What are servlets? (Nov/Dec 2013) 19. Which parser is best in parsing large documents?why? (May/June 2014) 20. What is servlet container? Specify its functions. (May/June 2014) 21. Explain in brief about Java scriptlet. (Apr/May 2011) 22. Give the advantages of using JSP for server side programming. (May/June 2012) 23. Write down the syntax JDBC. (Nov/Dec 2012) 24. Write 2 basic differences between JSP and servlet? (May/June 2013) 25. What do you mean by cookies? (Nov/Dec 2012) PART-B: 1. Discuss JavaScript Array object in detail. (8) (Nov/Dec 2011) 2. Discuss about JavaScript debugging. (8) (Nov/Dec 2011) 3. List and explain in detail the various selector strings.(8)(Apr/May 2011) 4. State and explain the types of statements in Java script. (8) (Apr/May 2011) 5. Explain how functions can be written in Java script with an example.(8)(Apr/May 2011) 6. List and explain in detail the types of selector strings. (8) (May/June 2012) 7. Explain the way in which java script handles arrays with example. (8) (May/June 2012) 8. Explain how local and global functions can be written using java script. (8) (May/June 2012)
114 9. Using RegExp instance,wríte a Java Script function isValid( ) that accepts a string argument and returns true if the argument matches one of the following phone- number formats and returns false otherwise: (16) (Nov/Dec 2012) (044) 234-56'î8 (044) 234-5678 044/234-5678 044 234 0442345678. 10. Discuss about the nodes in a document tree with an example. (16)(Nov/Dec 2012) 11. Write java script to find factorial of a given number? (8) (May/June 2013) 12. Write Java script to find sum offirst N even number and display the result . Get the value of n from user? (8) (May/June 2013) 13. Develop a simple online shopping using java script.(Nov/Dec 2013) 14. Write a java script program to develop a arithmetic calculator. (Nov/Dec 2013) 15. Discuss the data types, functions and objects used in java script with an example. (May/June 2014) 16. Explain in detail DOM event handling. Also explain with an example of creating a context menu. [Note: A context menu is one that that is shown when the user right-clicks anywhere in the document]. (16) (Nov/Dec 2011) 3 17. What is a session? Explain how client state is maintained using session and also explain about session tracking and session management using an example. (16) (Nov/Dec 2011) 3 18. Explain about the document tree in detail. (8) (Apr/May 2011) 3 19. Explain DOM event handling in detail. (8) (Apr/May 2011) 3 20. 3. Explain the Servlet operation in detail with a sample Servlet program.(16) (Apr/May 2011) 3 21. Explain the document tree in detail.(8) (May/June 2012) 3 22. Explain DOM event handling in detail. (8) (May/June 2012) 3 23. Explain in detail with an example the dynamic content generation by a servlet. (8) (May/June 2012) 24. Explain how java servlets perform session handling.(8) (May/June 2012) 25. Write a servlet program for Blogging appîicatíon, One servlet for login, second one for Prevíewíng fadding entry to the blog, third one for viewing the blog that generates HTML document. (16) (Nov/Dec 2012) 26. Write an ASP code to display different image each time a user visite a page. (8) (Nov/Dec 2012) 27. Write a JSP to demonstrate the usage of page and include directives. (8) (Nov/Dec 2012) 28. Write a servlet to illustrate the principles of cookies and explain? (16) (May/June 2013) 29. Explain about architecture of servlet? (6) (May/June 2013) 30. Explain the purpose of the following DOM methods and properties? (10) (May/June 2013) i ) getElementById ii)createElement
115 iii)createTextNode iv)appendChild v)parentNode 31. Explain the concepts of servlets with an example program. (Nov/Dec 2013) 32. Explain about JSP actions with example. (Nov/Dec 2013) 33. Write the code for converting currencies to US dollars using java servlets. (May/June 2014) 34. Explain the following with an example (May/June 2014) i.cookies ii.URL rewriting 35. What is a JavaBeans component? How will you use the JSP language elements for accessing Beans in your JSP pages? (16) (Nov/Dec 2011) 36. State and explain the information in a JSP document in detail. (16)(Apr/May 2011) 37. Explain the use of Java beans classes in JSP with examples. (8) (May/June 2012) 38. Write a client server JSP program to find simple interest and display the result in the client? (10) (May/June 2013) 39. Write about the JSP tag Libraries?(6) (May/June 2013) 40. Describe the basic java bean classes and JSP tag libraries. (May/June 2014) 41. Explain the JDBC database access in detail. (8)(Apr/May 2011) 42. Write a java servlet to display net salary of employee, use JDBC connectivity to get a employee details from database? (16) (May/June 2013) UNIT-IV: PHP AND XML PART-A 1. How is XML parsing done with SAX? (Nov/Dec 2011) 2. What is the purpose of XSLT? (Nov/Dec 2011) 3. What is meant by a XML namespace? (Apr/May 2011) 4. What does XSLT mean? (May/June 2012) 5. State the role of XML parser. (Nov/Dec 2012) 6. Compare DOM and SAX in XML processing? (May/June 2013) 7. What is the use of XML namespace? (Nov/Dec 2013) 8. What are the XSLT elements? (Nov/Dec 2013) 9. When the namespace is called in XML?why? 10. What is XPATH? 11. What is the speciality in PHP? (Nov/Dec 2012) 12. What is the purpose of XML schema? (May/June 2013) PART-B: 1. Explain XPATH nodes in detail. (8) (Nov/Dec 2011) 2. Explain about the object that helps AJAX reload parts of a web page without reloading the whole page. (8) (Nov/Dec 2011) 3. List and explain the XML syntax rules in detail. (8) (Apr/May 2011) 4. Explain how a XML document can be displayed on a browser. (8) (Apr/May 2011)
116 5. Explain the role XML name spaces with examples. (8) (May/June 2012) 6. Explain the features of XML path language. (8) (May/June 2012) 7. Explain the model view controller architecture pattern in detail.(8) (May/June 2012) 13. Explain on how template based transformation made in XML. (8) (Nov/Dec 2012) 14. Create a XML document for students mark list preparation and a DTD for that then valídate the XML document. (16) (Nov/Dec 2012) 15. Write XSLT code to display employee details in a table form which is stored in XML?(16) (May/June 2013) 16. What is DTD? Explain it with example. (Nov/Dec 2013) 17. Explain how XSLT transforms a document from one type to other. (May/June 2014) 18. Explain in detail the XML schema, built in and user defined data type in detail. (16)(Apr/May 2011) 19. Explain the role of XML schema in building web services in detail. (16) (May/June 2012) UNIT-V: INTRODUCTION TO AJAX AND WEB SERVICES PART-A 1. What is meant by WSDL? (Apr/May 2011) 2. List some examples of web services. (May/June 2012) 3. State the use of WSDL. (May/June 2012) 4. Define the need for SOAP? (May/June 2013) 5. What is the use of web services? (Nov/Dec 2013) 6. What is WSDL? (Nov/Dec 2013) PART-B 1. Describe the significance and working of WSDL with an example. (16) (Nov/Dec 2011) 2. Describe the major elements of SOAP. (16) (Nov/Dec 2011) 3. Explain the SOAP elements in detail. (8) (Apr/May 2011) 4. Explain the creation of a java web service in detail with examples. (16) (May/June 2012) 5. Illustrate the principles of WSDL , XML and SOAP and their interaction between them in web service applications?(16) (May/June 2013) 6. Explain web service architecture. (Nov/Dec 2013) 7. Write a program for any two web services. (Nov/Dec 2013) 8. Explain the WSDL structure and its elements. (May/June 2014)

CS6501 - Internet programming

  • 1.
    1 DEPARTMENT OF COMPUTERSCIENCE AND ENGINEERING IMPORTANT QUESTIONS & ANSWERS JUNE – NOV.2015 CS6501 – INTERNET PROGRAMMING Year/Sem : IV/VIII Branch : COMPUTER SCIENCE AND ENGINEERING Faculty : V.KARTHIK SYLLABUS CS6501 INTERNET PROGRAMMING LTPC/3104 OBJECTIVES: The student should be made to:  Learn Java Programming.  Understand different Internet Technologies.  Be exposed to java specific web services architecture. UNIT I JAVA PROGRAMMING An overview of Java – Data Types – Variables and Arrays – Operators – Control Statements – Classes – Objects – Methods – Inheritance - Packages – Abstract classes – Interfaces and Inner classes – Exception handling - Introduction to Threads – Multithreading – String handling – Streams and I/O – Applets. UNIT II WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 Web 2.0: Basics-RIA Rich Internet Applications - Collaborations tools - Understanding websites and web servers: Understanding Internet – Difference between websites and web server- Internet technologies Overview – Understanding the difference between internet and intranet; HTML and CSS: HTML 5.0 , XHTML, CSS 3. UNIT III CLIENT SIDE AND SERVER SIDE PROGRAMMING Java Script: An introduction to JavaScript–JavaScript DOM Model-Date and Objects,- Regular Expressions- Exception Handling- Validation-Built-in objects-Event Handling- DHTML with JavaScript. Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST actions- Session Handling- Understanding Cookies- Installing and Configuring Apache Tomcat Web Server;- DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example - JSP: Understanding Java Server Pages-JSP Standard Tag Library (JSTL)-Creating HTML forms by embedding JSP code.
  • 2.
    2 UNIT IV PHPand XML An introduction to PHP: PHP- Using PHP- Variables- Program control- Built-in functions-Connecting to Database – Using Cookies-Regular Expressions; XML: Basic XML- Document Type Definition-XML Schema DOM and Presenting XML, XML Parsers and Validation, XSL and XSLT Transformation, News Feed (RSS and ATOM). UNIT V INTRODUCTION TO AJAX and WEB SERVICES AJAX: Ajax Client Server Architecture- XML Http Request Object-Call Back Methods; Web Services: Introduction- Java web services Basics – Creating, Publishing, Testing and Describing a Web services (WSDL)-Consuming a web service, Database Driven web service from an application – SOAP. TOTAL (L: 45+T: 15): 60 PERIODS OUTCOMES:  At the end of the course, the student should be able to:  Implement Java programs.  Create a basic website using HTML and Cascading Style Sheets.  Design and implement dynamic web page with validation using JavaScript objects and by applying different event handling mechanisms.  Design rich client presentation using AJAX.  Design and implement simple web page in PHP, and to present data in XML format.  Design and implement server side programs using Servlets and JSP. TEXT BOOKS: 1. Deitel and Deitel and Nieto, ―Internet and World Wide Web - How to Program‖, Prentice Hall, 5th Edition, 2011. 2. Herbert Schildt, ―Java-The Complete Reference‖, Eighth Edition, Mc Graw Hill Professional,2011. REFERENCES: 1. Stephen Wynkoop and JohnBurke ―Running a Perfect Website‖, QUE,2nd Edition,1999. 2. Chris Bates, Web Programming – Building Intranet Applications, 3 rd Edition, Wiley Publications, 2009. 3. Jeffrey C and Jackson, ―Web Technologies A Computer Science Perspective‖, Pearson Education, 2011. 4. Gopalan N.P. and Akilandeswari J., ―Web Technology‖, Prentice Hall of India, 2011. 5. Paul Dietel and Harvey Deitel, ―Java How to Program‖,8 th Edition Prentice Hall of India. 6. Mahesh P. Matha, ―Core Java A Comprehensive Study‖, Prentice Hall of India, 2011. 7. Uttam K.Roy, ―Web Technologies‖, Oxford University Press, 2011.
  • 3.
    3 SECTION B: QUESTIONS UNIT–I JAVA PROGRAMMING PART -A 1. What is a Class and Object? 2. What is final modifier? 3. What is meant by abstraction? 4. What are methods and how are they defined? 5. What is an Object and how do you allocate memory to it? 6. Explain the usage of Java packages. 7. What is method overloading and method overriding? 8.What is static variable and static method? 9. What is array? Give an example. 10.What is a package? 11.Explain working of Java Virtual Machine (JVM)? 12. What is meant by Inheritance and what are its advantages? 13. What are inner class and anonymous class? 14. What is an Interface? 15.What is interface and its use? 16. What are the types of Exceptions in Java 17. Whatis the difference between String and String Buffer? 18.What are different types of access modifiers (Access specifiers)? 19. What is multithreading? 20. What is an applets? PART -B 1. Explain in detail about operator in java with example? (16) 2. i) Discuss in detail the access specifiers available in Java.(8) ii)What is Array? How to declare array?Discuss the methods under array class. (8) 3. Explain Packages in detail with example. (16) 4. Explain the concept of inheritance and its types. (16) 5. Explain the different ways to handle exceptions in java. (16) 6.Explain in detail about Multithreading in java. (16)
  • 4.
    4 UNIT –II WEBSITESBASICS, HTML 5, CSS 3, WEB 2.0 PART-A 1. What are the necessities of using HTML forms? 2. Define HTML. 3. What do you understand about DOCTYPE in HTML? 4. What are the Hyperlink, Anchors and Link in the HTML? 5. How you define HTML Style Attribute in HTML? 6. HTML is case sensitive or not? 7. How to use form‘s action attribute and submit button in html? 8. How to use Line Break and Horizontal Line tags in HTML? 9. What are Style Sheets? 10. List down the ways of including style information in a document. 11. What are the style precedence rules when using multiple approaches? 12. Give the syntax to specify a characteristic in linked style sheet. 13. List down font characteristics permitted in style sheets. 14. How to toggle display an HTML element? 15. What is the HTML DOM? PART –B 1. Explain Basic internet protocols and HTTP message format?(16) 2. To create a web page that displays college information using various styles (16) 3. Explain XHTML Syntax and semantics with example.(16) 4. i)Design a HTML Form for aRailwaay Reservation System? (8) ii)Explain about different types of XHTML DTD(8) 5.i)Explain about internet and intranet with difference.(8) ii) Design a HTML document using relative positioning to nudge text to the left.(8)
  • 5.
    5 UNIT –III CLIENTSIDE AND SERVER SIDE PROGRAMMING PART-A 1. How to create an Object in JavaScript? 2. What is the result of below given line of code in Java Script? 5+4+‖7‖ 3.What is undefined value means in JavaScript? 4. Which method is used to Clear an array using JavaScript? 5.What will be the Output of the following using JavaScript, document.Write(Math.Round(6.7)); 6.What should appear at the very end of your JavaScript? 7.What is a JSP and what is it used for? 8. What is difference between custom JSP tags and beans? 9. What are the implicit objects? 10. Compare Client side vs. server side scripting. 11. State the Servlet life cycle 12. What is JavaScript? 13. What is the purpose of cookies? 14. What are the steps needs to establish JDBC connectivity? 15. What is the difference between GET and POST method? 16. What is different between web server and application server? 17. What are different methods of session management in servlets? 18. What is difference between GenericServlet and HttpServlet? PART –B 1. Explain javascript variables and debuggers in detail (16) 2. Discuss JavaScript Array object in detail. (16) 3. Write java script to perform all arithmetic operation (16) 4. Explain DOM event handling in detail.(16) 5. Write java servlet programs to conduct online examination and to display student mark list available in a database (16)
  • 6.
    6 UNIT-IV PHP andXML PART –A 1. Mention the rules of well-formed XML. 2. What is the DOM? 3. What is the XML DOM? 4. What is the XMLHttpRequest Object? 5. What is XSL-FO? 6. What is XSL-FO Documents? Explain XSL-FO Documents structure 7. What is XSL-FO Processors? 8. Explain XML Attributes with an example 9. XML Elements vs. Attributes. 10. What are the problems with using XML attributes? 11. What is XSLT? 12. What are the roles of XSLT? 13.What is XSLT? Explain its relationships with XSL 14.What is XSLT style sheet? 15.Discuss the role of XPATH 16.Explain the XSLT data model 17.Why the need for XHTML? 18.What is XQuery language? 19.Explain the Relation between RSS and XML 20. Define. DOM PART –B 1. Given an XSLT document and a source XML document explain the XSLT transformation process that produces a single result XML document. (16) 2.Write a program to display student information using XSLT in XML document (16) 3. i)Explain the role XML namespaces with an example.(8) (ii)Explain the feature of XML path.(8) 4. Explain the model view controller architecture pattern in detail. (16) 5. Write Programs using XML – Schema – XSLT/XSL (16)
  • 7.
    7 UNIT V –INTRODUCTION TO AJAX and WEB SERVICES PART –A 1. What is DTD? Explain it with example. 2. What is AJAX? 3.What is a web service? 4.What is SOAP? 5. What is SOAP and how it will be utilized in web-components? 6. Explain about the role of XML in SOAP? 7.What are the elements which should be contained in SOAP message? 8. What is SOAP? 9. Explain web services architecture. 10. What is WSDL? 11. Differentiate between AJAX and Java Script 12. What are the advantages of AJAX ? 13. Define Web Service? 14. Brief few drawbacks of using GET and POST methods to communicate with the web service? 15. Differentiate between a SOA and a Web service? PART –B 1. Describe the significance and working of WSDL with an example(16) 2. Describe the major elements of SOAP (16) 3. Explain about AJAX Http Request Object (16) 4. Explain in details about Web Services Conceptual Architecture (16) 5. Write a program to run and implement the web service (16)
  • 8.
    8 SECTION C: QUESTIONSAND ANSWER UNIT –I PART A 1. What is a Classand Object? Class is a template for a set of objects that share a common structureand a common behavior. Object is an instance of a class. It has state, behavior and identity. It isalso called as an instance of a class. 2. What is final modifier? The final modifier keyword makes that the programmer cannotchange the value anymore. The actual meaning depends on whether it isapplied to a class, a variable, or a method. final Classes- A final class cannot have subclasses. final Variables- A final variable cannot be changed once it is initialized. final Methods- A final method cannot be overridden by subclasses. 3. What is meant by abstraction? Abstraction defines the essential characteristics of an object that distinguish it from all other kinds of objects. Abstraction provides crisply-defined conceptual boundaries relative to the perspective of the viewer. It‘s the process of focusing on the essential characteristics of an object. Abstraction is one of the fundamental elements of the object model 4. What are methods and how are they defined? Methods are functions that operate on instances of classesin which they are defined. Objects can communicate with each other usingmethods and can call methods in other classes. Method definition has fourparts. They are name of the method, type of object or primitive type themethod returns, a list of parameters and the body of the method. A method‘s signature is a combination of the first three parts mentionedabove. 5. What is an Object and how do you allocate memory to it? Object is an instance of a class and it is a software unit that combines astructured set of data with a set of operations for inspecting and manipulatingthat data. When an object is created using new operator, memory is allocated toit. 6. Explain the usage of Java packages. This is a way to organize files when a project consists of multiplemodules. It also helps resolve naming conflicts when different packages haveclasses with the same names. Packages access level also allows you toprotect data from being used by the non- authorized classes. 7. What is method overloading and method overriding? Method overloading: When a method in a class having the same methodname with different arguments is said to be method overloading. Methodoverriding: When a method in a class having the same method name withsame arguments is said to be method overriding.
  • 9.
    9 8.What is staticvariable and static method? Static variable is a class variable which value remains constant for theentire class. Static method is the one which can be called with the class itself and can holdonly the static variables. 9. What is array? Give an example. An array is a group of like-typed variables that are referred to by a common name. Arrays ofany type can be created and may have one or more dimensions. A specific element in an arrayis accessed by its index. Arrays offer a convenient means of grouping related information. Syntax: array-var = new type[size];example:month_days = new int[12]; 10.What is a package? A package is a collection of classes and interfaces that provides ahigh-level layer of access protection and name space management. 11.Explain working of Java Virtual Machine (JVM)? JVM is an abstract computing machine like any other real computingmachine which first converts .java file into .class file by using Compiler (.class isnothing but byte code file.) and Interpreter reads byte codes 12. What is meant by Inheritance and what are its advantages? Inheritance is the process of inheriting all the features from a class.The advantages of inheritance are reusability of code and accessibility ofvariables and methods of the super class by subclasses. 13. What are inner class and anonymous class? Inner class: classes defined in other classes, includingthose defined in methods are called inner classes. An inner class canhave any accessibility including private. Anonymous class: Anonymousclass is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors 14. What is an Interface? Interface is an outside view of a class or object which emphasizes itsabstraction while hiding its structure and secrets of its behavior. 15.What is interface and its use? Interface is similar to a class which may contain method‘ssignature only but not bodies and it is a formal set of method and constantdeclarations that must be defined by the class that implements it.Interfaces are useful for: a) Declaring methods that one or moreclasses are expected to implement b) Capturing similarities betweenunrelated classes without forcing a class relationship. c) Determining anobject‘s programming interface without revealing the actual body of the class
  • 10.
    10 16. What arethe types of Exceptions in Java There are two types of exceptions in Java, unchecked exceptions andchecked exceptions. Checked exceptions: A checked exception is some subclass of Exception (orException itself), excluding class Runtime Exception and its subclasses. Eachmethod must either handle all checked exceptions by supplying a catchclause or list each unhandled checked exception as a thrown exception. Unchecked exceptions: All Exceptions that extend the Runtime Exceptionclass are unchecked exceptions. Class Error and its subclasses also areunchecked. 17. Whatis the difference between String and String Buffer? a) String objects are constants and immutable whereas String Buffer objects are not. b) String class supports constant strings whereas String Buffer class supports grow able and modifiablestrings. 18.What are different types of access modifiers (Access specifiers)? Access specifiers are keywords that determine the type of accessto the member of a class. These keywords are for allowingprivileges to parts of a program such as functions and variables. Theseare: Public: Anything declared as public can be accessed from anywhere. Private: Anything declared as private can‘t be seen outside of its class. Protected: Anything declared as protected can be accessed by classes inthe same package and subclasses in the other packages. Default modifier : Can be accessed only to classes in thesame package. 19. What is multithreading? Java provides built-in support for multithreadedprogramming. A multithreaded program contains two or more parts that can runconcurrently. Each part of such a program is called a thread, and each thread definesa separate path of execution. Thus, multithreading is a specialized form of multitasking. 20. What is an applets? Applets are small applications that are accessed on anInternet server, transported over the Internet, automatically installed, and run as part of a webdocument. After an applet arrives on the client, it has limited access to resources so that itcan produce a graphical user interface and run complex computations without introducingthe risk of viruses or breaching data integrity.
  • 11.
    11 SECTION C: QUESTIONS& ANSWERS UNIT –I JAVA PROGRAMMING 1. Explain in detail about operator in java with example? (16) Java provides a rich operator environment. Most of its operators can be divided into the following four groups: arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain special situations. Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators: Operator | Result: + Addition – Subtraction (also unary minus) * Multiplication / Division % Modulus ++ Increment += Addition assignment –= Subtraction assignment *= Multiplication assignment /= Division assignment %= Modulus assignment – – Decrement The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use them on char types, since the char type in Java is,essentially, a subset of int. class BasicMath { public static void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b / 4; int d = c - a; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e);
  • 12.
    12 The Bitwise Operators Javadefines several bitwise operators that can be applied to the integer types, long, int, short,char, and byte. These operators act upon the individual bits of their operands. They aresummarized in the following table: The Bitwise Logical Operators The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each operation. The Bitwise OR The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the resultant bit is a 1, as shown here: The Bitwise XOR
  • 13.
    13 // Demonstrate thebitwise logical operators. class BitLogic { public static void main(String args[]) { String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" }; int a = 3; // 0 + 2 + 1 or 0011 in binary int b = 6; // 4 + 2 + 0 or 0110 in binary int c = a | b; int d = a & b; int e = a ^ b; int f = (~a & b) | (a & ~b); int g = ~a & 0x0f; System.out.println(" a = " + binary[a]); System.out.println(" b = " + binary[b]); System.out.println(" a|b = " + binary[c]); System.out.println(" a&b = " + binary[d]); System.out.println(" a^b = " + binary[e]); System.out.println("~a&b|a&~b = " + binary[f]); System.out.println(" ~a = " + binary[g]); } } output from this program: a = 0011 b = 0110 a|b = 0111 a&b = 0010 a^b = 0101 ~a&b|a&~b = 0101 ~a = 1100 Relational Operators The relational operators determine the relationship that one operand has to the other. Specifically, they determine equality and ordering. The relational operators are shown here:
  • 14.
    14 Example: int a =4; int b = 1; boolean c = a < b; Boolean Logical Operators The Boolean logical operators shown here operate only on boolean operands. All of the binary logical operators combine two boolean values to form a resultant boolean value. The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an integer. The logical ! operator inverts the Boolean state: !true == false and !false == true. The following table shows the effect of each logical operation: // Demonstrate the boolean logical operators. class BoolLogic { public static void main(String args[]) { boolean a = true; boolean b = false; boolean c = a | b; boolean d = a & b; boolean e = a ^ b; boolean f = (!a & b) | (a & !b); boolean g = !a; System.out.println(" a = " + a);
  • 15.
    15 System.out.println(" b =" + b); System.out.println(" a|b = " + c); System.out.println(" a&b = " + d); System.out.println(" a^b = " + e); System.out.println("!a&b|a&!b = " + f); System.out.println(" !a = " + g); } } O/P: a = true b = false a|b = true a&b = false a^b = true a&b|a&!b = true !a = false The Assignment Operator The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other computer language. It has this general form: var = expression; Here, the type of var must be compatible with the type of expression. For example, int x, y, z; x = y = z = 100; // set x, y, and z to 100 The ? Operator Ternary (three-way) operator that can replace certain types of if-then-else Statements .The ? has this general form: expression1? expression2:expression3 Here, expression1 can be any expression that evaluates to a boolean value. If expression1 istrue, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the ?operation is that of the expression evaluated. Both expression2 and expression3 are requiredto return the same type, which can‘t be void. Example: ratio = denom == 0 ? 0 : num / denom;
  • 16.
    16 2. i) Discussin detail the access specifiers available in Java.(8) ii)What is Array? How to declare array?Discuss the methods under array class. (8) i) Discuss in detail the access specifiers available in Java.(8) Java‘s four level of access protection:  Public  Private  Protected  Default Some aspects of access control are related mostly to inheritance or package. (A package is,essentially, a grouping of classes) protected is applied only when inheritance is invoked. : Public Access: When a member of a class is modified by public specifier, then that member can be accessed by any other code. Now you can understand why main () has always been preceded by the public specifier.it is called by code that is outside the program that is by java run time system Private Access: when a member of class is specified as private, then that member can only be accessed by other members of its class. protected: Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.The protected access modifier cannot be applied to class and interfaces. Methods, fields can be declared protected, however methods and fields in a interface cannot be declared protected.Protected access gives the subclass a chance to use the helper method or variable, while preventing a nonrelated class from trying to use it. Default Access: when no specifier is used then by default the member of class is public within its own package, but cannot be accessed outside of its package.in the classes development so far ,all members of a class have use the default access mode .which is essentially public. This access specifier is also known as friendly access. table showing all the access specifiers and theiraccessibility in the class, package, subclasses andother packages.
  • 17.
    17 Example of public& private /* Program to demonstrate Access Protection */ class Demo { int p; // default access public int q; // public access private int r; // private access // methods to access r void setr(int i) { // set r's value r = i; } int getr() { // get r's value return r; } } class AccessProDemo { public static void main(String args[]) { Demo d= new Demo(); // OK : 'p' and 'q' may be accessed directly d.p=300; d.q=400; // NOT OK : 'r' cannot be accessed outside the class, hence will cause an error // d.r=50; // You must access 'r' through its methods d.setr(500); //OK System.out.println(" p, q, and r = "+d.p+", "+d.q+", and "+d.getr()); } } o/p:- P, q, and r =300,400, and 500
  • 18.
    18 2.ii) What isArray? How to declare array?Discuss the methods under array class. An array is a data structure that stores a collection of values of the same type. You access each individualvalue through an integer index. Array Name [index] Integer constant, variable, or expression For Instance we can define an array name salary to represent a set of salaries of a group of employees. Aparticular value is indicated by writing a number called index in brackets after the array name. salary [10] it represents the salary of the 10th employee. Types of arrays One dimensional arrays Two dimensional arrays One Dimensional arrays A list of items can be given one variable name using only one subscript and such a variable iscalled single - subscripted of one dimensional array. The subscript can also start from 0. ie x[0]. If we want to represent a set of five numbers, say (35,40,20,57,19) by an array variable number,then we have to create the variable number as follows int number [ ] = new int [5 ]; The value to the array elements can be assigned as follows Number[0] =35; Number [1] =40; Number [2] =20; Number [3] =57; Number [4] =19; This would cause the array number to store the values shown as follows; Creating an array Declaring the array Creating memory locations Putting values into the memory locations. Declaring the Array Array in java can be declared in two forms Form 1 type arrayname [ ]; Form 2 type [ ] arrayname; Creation of arrays arrayname = new type [ size ]; Eg; number = new int [5] ; average = new float[10]; it is also possible to combine declaration and creation. int number [ ] = new int [5]; Initialization of arrays
  • 19.
    19 The final stepis to put values into the array created. This process is known as initialization usingthe array subscripts as shown below. arrayname[subscript] = value ; Eg number[0] = 15; we can also initialize by following way typearrayname [ ] = { list of values } Array Length All array store the allocated size in an variable named length. We can obtain the length of array ausing a.length Eg: intasize = a.length; Sample Code for array manipulation Two Dimensional arrary: Usage :intmyArray [ ] [ ]; myArray= new int [3] [4]; or initmyArray [ ] [ ] = new int [3][4] This creates a table that can store 12 integer values, four across and three down. Strings: Series of characters represents a string, and easiest way to represent the string is array Eg: Char charArray [ ] = new char [2] ; charArray[0] = „j‟ ; charArray[1] = „a‟ ; String can be declared and created in the following way string stringname; stringname = new string (―string‖); Operations on string int m = stringname.length() //will return the length of the string string city = ―New‖ + ―Delhi‖// will return New Delhi ,string concatenating Sample Code forstring Manipulation 3. Explain Packages in detail with example. (16) Packages are java‟s way of grouping a variety of classes and/or interfaces together. Packages are container for the classes. It is stored in a hierarichical manner. If we want to use the packages in a class, we want to import it. The two types of packages are: 1. System package. 2. User defined package. Uses of Packages: Packages reduce the complexity of the software because a large number of classes can be grouped into a limited number of packages.
  • 20.
    20 We can createclasses with same name in different packages. Using packages we can hide classes. We may like to use many of the classes contained in a package.it can be achieved by Import packagename .classname Or Import packagename.* Creating the package To create our own packages packagefirstpackage;// package declaration public class FirstClass //class definition {..... (body of class) .......} The file is saved as FirstClass.java,located at firstpackage directory. when it is compiled .class file will be created in same ditectory. Access a package The import statement can be used to search a list of packages for a particular class. The general form of import statement for searching class is a as follows. Import package1 [.package2] [.package3].classname; Using the package package package1 ; public class classA { public void displayA() { System.out.println(―class A‖); } } Adding a class to package Define the class and make it public Place the package statement Package P1 Before the class definition as follows Package p1; Public class B Package name { // body of B } Example: Package college Class student {
  • 21.
    21 intregno; String name; Student(intr,stringna); { Regno=r Name=na } Public voidprint() { System.out.println(―Regno‖+regno ); System.out.println(―Name‖+name ); } } Package Course Class engineering { Intregno; String branch; String year; Engineering(int r, string br, string yr) { Regno=br; Branch=br; Year=yr; } public void print() { Systems.out.println(―Regno‖+regno); Systems.out.println(― Branch‖+branch); Systems.out.println(―Year‖+year); } } import college.*; import course.*; Class demo { Public static void main(string args[]) { Student sl=new Engineering(1,‖CSE‖,‖III Year‖); Sl.print(); El.print(); } }
  • 22.
    22 4. Explain theconcept of inheritance and its types. (16) There exist basically three types of inheritance.  Multilevel inheritance  Multiple inheritance  Hierarchical inheritance 1. In single inheritance, one class extends one class only. In multilevel inheritance, the ladder of single inheritance increases. 2. In multiple inheritance, one class directly extends more than one class. 3. In hierarchical inheritance one class is extended by more than one class. 1. Single Inheritance When a single derived class is created from a single base class then the inheritance is called as single inheritance. 1. Multilevel Inheritance In multilevel, one-to-one ladder increases. Multiple classes are involved in inheritance, but one class extends only one. The lowermost subclass can make use of all its super classes' members. Multilevel inheritance is an indirect way of implementing multiple inheritance. Following program explains. class Aves { public void nature() { System.out.println("Generally, Aves fly"); } } class Bird extends Aves { public void eat() { System.out.println("Eats to live"); } }
  • 23.
    23 public class Parrotextends Bird { public void food() { System.out.println("Parrot eats seeds and fruits"); } public static void main(String args[]) { Parrot p1 = new Parrot(); p1.food(); // calling its own p1.eat(); // calling super class Bird method p1.nature(); // calling super class Aves method } } Now, Parrot has two super classes Bird and Aves; but extended one-to-one. Parrot can make use of the methods of Bird and Aves. Bird can make use of the methods of Aves, but Parrot as a super class cannot access subclass members. Following figure gives a schematic representation of the multilevel hierarchy with the classes involved in the program. 2. Multiple Inheritance In multiple inheritance, one class extends multiple classes. Java does not support multiple inheritance but C++ supports. The above program can be modified to illustrate multiple inheritance. The following program does not work. calss Aves { } class Bird { }
  • 24.
    24 publicclass Parrot extendsAves, Bird { } In the above code, Parrot extends both Aves and Bird. This is not supported by Java and the above code raises compilation error. Following is the schematic representation. Note: Java supports multiple inheritance partially through interfaces. 3. Hierarchical Inheritance In hierarchical type of inheritance, one class is extended by many subclasses. It is one- to-many relationship. A realtime example is available at dynamic binding. class Aves { publicvoid fly() { System.out.println("Generally, aves fly"); } } class Parrot extends Aves { publicvoid eat() { System.out.println("Parrot eats fruits and seeds"); } } class Vulture extends Aves { publicvoid vision() { System.out.println("Vulture can see from high altitudes"); } } publicclass FlyingCreatures { publicstaticvoid main(String args[]) { // all the following code is composition for FlyingCreatures Parrot p1 = new Parrot(); p1.eat(); // calling its own member p1.fly();
  • 25.
    25 // calling superclass member by inheritance Vulture v1 = new Vulture(); v1.vision(); // calling its own member v1.fly(); // calling super class member by inheritance }} Output screen of FlyingCreatures.java In the above code, Aves class is extended by two classes – Parrot and Vulture. Both classes can make use of the methods of Aves. Even though the Parrot and Vulture are subclasses of the same class Aves, but still they cannot make use of each other members. Parrot and Vulture are known as "siblings". Siblings are disjoint and they cannot make use of other members as between them no inheritance is involved (like two sons of a father; one son's property cannot be shared by other but both can share the property of father). Following is the schematic representation of the classes involved. Dynamic binding and dynamic polymorphism use hierarchical inheritance. Disadvantages of Inheritance 1. Both classes (super and subclasses) are tightly-coupled. 2. As they are tightly coupled (binded each other strongly with extends keyword), they cannot work independently of each other. 3. Changing the code in super class method also affects the subclass functionality. 4. If super class method is deleted, the code may not work as subclass may call the super class method with super keyword. Now subclass method behaves independently.
  • 26.
    26 5. Explain thedifferent ways to handle exceptions in java. (16) An exception is a problem that arises during the execution of a program. An exception can occur formany different reasons, including the following: A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications or the JVM has run out ofmemory. Some of these exceptions are caused by user error, others by programmer error, and others byphysical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories ofexceptions: Checked exceptions: A checked exception is an exception that is typically a user error or aproblem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception occurs. These exceptions cannot simply be ignoredat the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compilation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely doanything about an error. For example, if a stack overflow occurs, an error will arise. They are alsoignored at the time of compilation. Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is asubclass of the Throwable class. Other than the exception class there is another subclass calledError which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case ofsevere failures, which are not handled by the java programs. Errors are generated to indicate errorsgenerated by the runtime environment. Example : JVM is out of Memory. Normally programs cannotrecover from errors. The Exception class has two main subclasses: IOException class and RuntimeException Class.
  • 27.
    27 Here is alist of most common checked and unchecked Java's Built-in Exceptions. Exceptions Methods: Following is the list of important medthods available in the Throwable class. Methods with Description 1 public String getMessage() Returns a detailed message about the exception that has occurred. This message isinitialized in the Throwable constructor. 2 public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. 3 public String toString() Returns the name of the class concatenated with the result of getMessage() 4 public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error outputstream. 5 public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0represents the top of the call stack, and the last element in the array represents themethod at the bottom of the call stack. 6 public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to anyprevious information in the stack trace. Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catchblock is placed around the code that might generate an exception. Code within a try/catch block isreferred to as protected code, and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block
  • 28.
    28 } A catch statementinvolves declaring the type of exception you are trying to catch. If an exceptionoccurs in protected code, the catch block (or blocks) that follows the try is checked. If the type ofexception that occurred is listed in a catch block, the exception is passed to the catch block muchas an argument is passed into a method parameter. Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd elementof the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks likethe following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of themafter a single try. If an exception occurs in the protected code, the exception is thrown to the firstcatch block in the list. If the data type of the exception thrown matches ExceptionType1, it getscaught there. If not, the exception passes down to the second catch statement. This continuesuntil the exception either is caught or falls through all
  • 29.
    29 catches, in whichcase the current methodstops execution and the exception is thrown down to the previous method on the call stack. Example: Here is code segment showing how to use multiple try/catch statements. try { file = new FileInputStream(fileName); x = (byte) file.read(); }catch(IOException i) { i.printStackTrace(); return -1; }catch(FileNotFoundException f) //Not valid! { f.printStackTrace(); return -1; } The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throwskeyword. throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, byusing the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException: import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws aRemoteException and an InsufficientFundsException: import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation }
  • 30.
    30 //Remainder of classdefinition } The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of codealways executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, nomatter what happens in the protected code.A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. } Example: public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6; System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } This would produce the following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Note the following:
  • 31.
    31 A catch clausecannot exist without a try statement.It is not compulsory to have finally clauses when ever a try/catch block is present.The try block cannot be present without either catch clause or finally clause.Any code cannot be present in between the try, catch, finally blocks. Declaring you own Exception: You can create your own exceptions in Java. Keep the following points in mind when writing your ownexception classes: All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class. We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a userdefinedexception that extends the Exception class, making it a checked exception. An exceptionclass is like any other class, containing useful fields and methods. Example: // File Name InsufficientFundsException.java import java.io.*; public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains awithdraw() method that throws an InsufficientFundsException. // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; }
  • 32.
    32 public void deposit(doubleamount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber() { return number; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods ofCheckingAccount. // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("nWithdrawing $100..."); c.withdraw(100.00); System.out.println("nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount());
  • 33.
    33 e.printStackTrace(); } } } Compile all theabove three files and run BankDemo, this would produce the following result: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) Common Exceptions: In Java, it is possible to define two catergories of Exceptions and Errors. JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM.Examples:NullPointerException,ArrayIndexOutOfBoundsException, ClassCastException, Programmatic exceptions: - These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException 6.Explain in detail about Multithreading in java. (16) Java provides built-in support for multithreaded programming. A multithreaded program contains two or more parts that can run concurrently. Each part of such a program is called a thread, and each thread defines a separate path of execution. Thus, multithreading is a specialized form of multitasking. Multithreading enables you to write very efficient programs that make maximum use of the CPU, because idle time can be kept to a minimum. This is especially important for the interactive, networked environment in which Java operates, because idle time is common. For example, the transmission rate of data over a network is much slower than the rate at which the computer can process it. Even local file system resources are read and written at a much slower pace than they can be processed by the CPU. And, of course, user input is much slower than the computer The Thread Class and the Runnable Interface Java‘s multithreading system is built upon the Thread class, its methods, and its companion interface, Runnable. Thread encapsulates a thread of execution. Since you can‘t directly refer to the ethereal state of a running thread, you will deal with it through its proxy, the Thread instance that spawned it. To create a new thread, your program will either extend Thread or implement the Runnable interface. The Thread class defines several methods that help manage threads. The ones that will be used in this chapter are shown here:
  • 34.
    34 The Main Thread Whena Java program starts up, one thread begins running immediately. This is usually called the main thread of your program, because it is the one that is executed when your program begins. The main thread is important for two reasons: • It is the thread from which other ―child‖ threads will be spawned. • Often, it must be the last thread to finish execution because it performs various shutdown actions. Creating a Thread In the most general sense, you create a thread by instantiating an object of type Thread. Java defines two ways in which this can be accomplished: • You can implement the Runnable interface. • You can extend the Thread class, itself. The following two sections look at each method, in turn. Implementing Runnable The easiest way to create a thread is to create a class that implements the Runnable interface. Runnable abstracts a unit of executable code. You can construct a thread on any object that implements Runnable. To implement Runnable, a class need only implement a single method called run( ), which is declared like this: public void run( ) Inside run( ), you will define the code that constitutes the new thread. It is important to understand that run( ) can call other methods, use other classes, and declare variables, just like the main thread can. The only difference is that run( ) establishes the entry point for another, concurrent thread of execution within your program. This thread will end when run( ) returns. Here is an example that creates a new thread and starts it running: // Create a second thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() {
  • 35.
    35 try { for(int i= 5; i > 0; i--) { System.out.println("Child Thread: " + i); Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } Inside NewThread‘s constructor, a new Thread object is created by the following statement: t = new Thread(this, "Demo Thread"); o/p: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.
  • 36.
    36 Creating Multiple Threads Sofar, you have been using only two threads: the main thread and one child thread. However, your program can spawn as many threads as it needs. For example, the following program creates three child threads: // Create multiple threads. class NewThread implements Runnable { String name; // name of thread Thread t; NewThread(String threadname) { name = threadname; t = new Thread(this, name); System.out.println("New thread: " + t); t.start(); // Start the thread } // This is the entry point for thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println(name + ": " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println(name + "Interrupted"); } System.out.println(name + " exiting."); } } class MultiThreadDemo { public static void main(String args[]) { new NewThread("One"); // start threads new NewThread("Two"); new NewThread("Three"); try { // wait for other threads to end Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Main thread Interrupted"); } System.out.println("Main thread exiting."); } } The output from this program is shown here: New thread: Thread[One,5,main] New thread: Thread[Two,5,main] New thread: Thread[Three,5,main] One: 5
  • 37.
    37 Two: 5 Three: 5 One:4 Two: 4 Three: 4 One: 3 Three: 3 Two: 3 One: 2 Three: 2 Two: 2 One: 1 Three: 1 Two: 1 One exiting. Two exiting. Three exiting. Main thread exiting.
  • 38.
    38 UNIT –II WEBSITESBASICS, HTML 5, CSS 3, WEB 2.0 PART-A: 1. What are the necessities of using HTML forms? Gathering user information Conducting Surveys Interactive services 2. Define HTML. It is a simple page description language, which enables document creation for the web. 3. What do you understand about DOCTYPE in HTML? A Document Type Declaration, or DOCTYPE, is an instruction that associates a particular SGML or XML document (for example, a web page) with a Document Type Definition(DTD) (for example, the formal definition of a particular version of HTML). It manifests as a short string of markup that conforms to a particular syntax. 4. What are the Hyperlink, Anchors and Link in the HTML? The <a> tag can be used in two ways: 1.To create a link to another document, by using the href attribute 2.To create a bookmark inside a document, by using the name attribute <a href="url">Link text</a> - The href attribute specifies the destination of a link. 5. How you define HTML Style Attribute in HTML? The <style> tag is used to define style information for an HTML document. Inside the style element you specify how HTML elements should render in a browser. The required type attribute defines the content of the style element. The only possible value is "text/css". The style element always goes inside the head section. <head> <styletype="text/css"> h1 {color:red}</style> </head> 6. HTML is case sensitive or not? Html is not a case sensitive language. <P> means the same as <p>.But a combination of upper and lower case letters must not be used. 7. How to use form’s action attribute and submit button in html? The required action attribute specifies where to send the form-data when a form is submitted. <form action="form_action.asp" method="get"> ,, </form> <input type="submit" /> defines a submit button. A submit button is used to send form data to a server. The data is sent to the page specified in the form's action attribute. <input type="submit" value="Submit" /> 8. How to use Line Break and Horizontal Line tags in HTML? The <br> tag inserts a single line break. It‘s a empty tag, i.e. it has no end tag. The <hr> tag creates a horizontal line in the html page, and can be used to separate the contents in a html page. It is also an empty tag with no empty tag.
  • 39.
    39 9. What areStyle Sheets? CSS stands for Cascading Style Sheets. Styles define how to display HTML elements. Styles were added to HTML 4.0 to solve a problem. External Style Sheets can save a lot of work. External Style Sheets are stored in CSS files. 10. List down the ways of including style information in a document. There are three main ways to include styles into a document namely, external style sheets, embedded style sheets and inline styles. 11. What are the style precedence rules when using multiple approaches? Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:  Browser default  External style sheet  Internal style sheet (in the head section)  Inline style (inside an HTML element) So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value). 12. Give the syntax to specify a characteristic in linked style sheet. {Characteristic:Value;} Multiple Characteristic/Values should be separated by semicolons. 13. List down font characteristics permitted in style sheets. Font – family, font – size, font – weight, font- style and font – variant. 14. How to toggle display an HTML element? An element in HTML can be toggle displayed using the style. Display parameter inside a separate toggle function. 15. What is the HTML DOM? The HTML DOM is: A standard object model for HTML A standard programming interface for HTML Platform- and language-independent A W3C standard The HTML DOM defines the objects and properties of all HTML elements, and the methods (interface) to access them.
  • 40.
    40 UNIT-II PART -B 1.Explain Basic internet protocols and HTTP message format?(16) Internet Protocol: The Internet protocols are the world‘s most popular open-system (nonproprietary) protocol suite because they can be used to communicate across any set of interconnected networks and are equally well suited for LAN and WAN communications. The Internet protocols consist of a suite of communication protocols, of which the two best known are the Transmission Control Protocol (TCP) and the Internet Protocol (IP). The Internet protocol suite not only includes lower-layer protocols (such as TCP and IP), but it also specifies common applications such as electronic mail, terminal emulation, and file transfer. Internet protocols were first developed in the mid-1970s, when the Defense Advanced Research Projects Agency (DARPA) became interested in establishing a packet-switched network that would facilitate communication between dissimilar computer systems at research institutions. With the goal of heterogeneous connectivity in mind, DARPA funded research by Stanford University and Bolt, Beranek, and Newman (BBN). The result of this development effort was the Internet protocol suite, completed in the late 1970s. TCP/IP later was included with Berkeley Software Distribution (BSD) UNIX and has since become the foundation on which the Internet and the World Wide Web (WWW) are based
  • 41.
    41 Internet Protocol (IP) TheInternet Protocol (IP) is a network-layer (Layer 3) protocol that contains addressing information and some control information that enables packets to be routed. IP is documented in RFC 791 and is the primary network-layer protocol in the Internet protocol suite. Along with the Transmission Control Protocol (TCP), IP represents the heart of the Internet protocols. IP has two primary responsibilities: providing connectionless, best-effort delivery of datagram‘s through an internetwork; and providing fragmentation and reassembly of datagrams to support data links with different maximum-transmission unit (MTU) sizes. IP Packet Format An IP packet contains several types of information, as illustrated in Figure 30-2. The following discussion describes the IP packet fields illustrated in Figure 30-2: • Version—Indicates the version of IP currently used. • IP Header Length (IHL)—Indicates the datagram header length in 32-bit words. • Type-of-Service—Specifies how an upper-layer protocol would like a current datagram to be handled, and assigns datagrams various levels of importance. • Total Length—Specifies the length, in bytes, of the entire IP packet, including the data and header. • Identification—Contains an integer that identifies the current datagram. This field is used to help piece together datagram fragments. • Flags—Consists of a 3-bit field of which the two low-order (least-significant) bits control fragmentation. The low-order bit specifies whether the packet can be fragmented. The middle bit specifies whether the packet is the last fragment in a series of fragmented packets. The third or high-order bit is not used. • Fragment Offset—Indicates the position of the fragment‘s data relative to the beginning of the data in the original datagram, which allows the destination IP process to properly reconstruct the original datagram.
  • 42.
    42 • Time-to-Live—Maintains acounter that gradually decrements down to zero, at which point the datagram is discarded. This keeps packets from looping endlessly. • Protocol—Indicates which upper-layer protocol receives incoming packets after IP processing is complete. • Header Checksum—Helps ensure IP header integrity. • Source Address—Specifies the sending node. • Destination Address—Specifies the receiving node. •Options—Allows IP to support various options, such as security. •Data—Contains upper-layer information HTTP message format: HyperText Transfer Protocol (HTTP) HTTP (Hypertext Transfer Protocol) is perhaps the most popular application protocol used in the Internet (or The WEB). HTTP is an asymmetric request-response client-server protocol as illustrated. An HTTP client sends a request message to an HTTP server. The server, in turn, returns a response message. In other words, HTTP is a pull protocol, the client pulls information from the server (instead of server pushes information down to the client).  HTTP is a stateless protocol. In other words, the current request does not know what has been done in the previous requests.  HTTP permits negotiating of data type and representation, so as to allow systems to be built independently of the data being transferred.  Quoting from the RFC2616: "The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. It is a generic, stateless, protocol which can be used for many tasks beyond its use for hypertext, such as name servers and distributed object management systems, through extension of its request methods, error codes and headers."
  • 43.
    43 HTTP Request andResponse Messages HTTP client and server communicate by sending text messages. The client sends a request message to the server. The server, in turn, returns a response message. An HTTP message consists of a message header and an optional message body, separated by a blank line, as illustrated below: HTTP Request Message The format of an HTTP request message is as follow: Request Line The first line of the header is called the request line, followed by optional request headers. The request line has the following syntax: request-method-name request-URI HTTP-version
  • 44.
    44  request-method-name: HTTPprotocol defines a set of request methods, e.g., GET, POST, HEAD, and OPTIONS. The client can use one of these methods to send a request to the server.  request-URI: specifies the resource requested.  HTTP-version: Two versions are currently in use: HTTP/1.0 and HTTP/1.1. Examples of request line are: GET /test.html HTTP/1.1 HEAD /query.html HTTP/1.0 POST /index.html HTTP/1.1 Request Headers The request headers are in the form of name:value pairs. Multiple values, separated by commas, can be specified. request-header-name: request-header-value1, request-header-value2, ... Examples of request headers are: Host: www.xyz.com Connection: Keep-Alive Accept: image/gif, image/jpeg, */* Accept-Language: us-en, fr, cn Example The following shows a sample HTTP request message: HTTP Response Message The format of the HTTP response message is as follows:
  • 45.
    45 Status Line The firstline is called the status line, followed by optional response header(s). The status line has the following syntax: HTTP-version status-code reason-phrase  HTTP-version: The HTTP version used in this session. Either HTTP/1.0 and HTTP/1.1.  status-code: a 3-digit number generated by the server to reflect the outcome of the request.  reason-phrase: gives a short explanation to the status code.  Common status code and reason phrase are "200 OK", "404 Not Found", "403 Forbidden", "500 Internal Server Error". Examples of status line are: HTTP/1.1 200 OK HTTP/1.0 404 Not Found HTTP/1.1 403 Forbidden Response Headers The response headers are in the form name:value pairs: response-header-name: response-header-value1, response-header-value2, ... Examples of response headers are: Content-Type: text/html Content-Length: 35 Connection: Keep-Alive Keep-Alive: timeout=15, max=100 The response message body contains the resource data requested. Example The following shows a sample response message: HTTP Request Methods HTTP protocol defines a set of request methods. A client can use one of these request methods to send a request message to an HTTP server. The methods are:  GET: A client can use the GET request to get a web resource from the server.  HEAD: A client can use the HEAD request to get the header that a GET request would have obtained. Since the header contains the last-modified date of the data, this can be used to check against the local cache copy.  POST: Used to post data up to the web server.
  • 46.
    46  PUT: Askthe server to store the data.  DELETE: Ask the server to delete the data.  TRACE: Ask the server to return a diagnostic trace of the actions it takes.  OPTIONS: Ask the server to return the list of request methods it supports.  CONNECT: Used to tell a proxy to make a connection to another host and simply reply the content, without attempting to parse or cache it. This is often used to make SSL connection through the proxy.  Other extension methods. "GET" Request Method GET is the most common HTTP request method. A client can use the GET request method to request (or "get") for a piece of resource from an HTTP server. A GET request message takes the following syntax: GET request-URI HTTP-version (optional request headers) (blank line) (optional request body)  The keyword GET is case sensitive and must be in uppercase.  request-URI: specifies the path of resource requested, which must begin from the root "/" of the document base directory.  HTTP-version: Either HTTP/1.0 or HTTP/1.1. This client negotiates the protocol to be used for the current session. For example, the client may request to use HTTP/1.1. If the server does not support HTTP/1.1, it may inform the client in the response to use HTTP/1.0.  The client uses the optional request headers (such as Accept, Accept-Language, and etc) to negotiate with the server and ask the server to deliver the preferred contents (e.g., in the language that the client preferred).  GET request message has an optional request body which contains the query string (to be explained later). Response Status Code The first line of the response message (i.e., the status line) contains the response status code, which is generated by the server to indicate the outcome of the request. The status code is a 3-digit number:  1xx (Informational): Request received, server is continuing the process.  2xx (Success): The request was successfully received, understood, accepted and serviced.  3xx (Redirection): Further action must be taken in order to complete the request.  4xx (Client Error): The request contains bad syntax or cannot be understood.  5xx (Server Error): The server failed to fulfill an apparently valid request. Some commonly encountered status codes are:  100 Continue: The server received the request and in the process of giving the response.  200 OK: The request is fulfilled.  301 Move Permanently: The resource requested for has been permanently moved to a new location. The URL of the new location is given in the response header
  • 47.
    47 called Location. Theclient should issue a new request to the new location. Application should update all references to this new location.  302 Found & Redirect (or Move Temporarily): Same as 301, but the new location is temporarily in nature. The client should issue a new request, but applications need not update the references.  304 Not Modified: In response to the If-Modified-Since conditional GET request, the server notifies that the resource requested has not been modified.  400 Bad Request: Server could not interpret or understand the request, probably syntax error in the request message.  401 Authentication Required: The requested resource is protected, and require client‘s credential (username/password). The client should re-submit the request with his credential (username/password).  403 Forbidden: Server refuses to supply the resource, regardless of identity of client.  404 Not Found: The requested resource cannot be found in the server.  405 Method Not Allowed: The request method used, e.g., POST, PUT, DELETE, is a valid method. However, the server does not allow that method for the resource requested.  408 Request Timeout:  414 Request URI too Large:  500 Internal Server Error: Server is confused, often caused by an error in the server-side program responding to the request.  501 Method Not Implemented: The request method used is invalid (could be caused by a typing error, e.g., "GET" misspell as "Get").  502 Bad Gateway: Proxy or Gateway indicates that it receives a bad response from the upstream server.  503 Service Unavailable: Server cannot response due to overloading or maintenance. The client can try again later.  504 Gateway Timeout: Proxy or Gateway indicates that it receives a timeout from an upstream server.
  • 48.
    48 2. To createa web page that displays college information using various styles HTML CODE: <html> <head><h1><center>ALL STYLE SHEETS</center></h1> <title>USE of INTERNAL and EXTERNAL STYLESHEETS </title> <link rel="stylesheet" href="xyz.css" type="text/css"> <style type="text/css"> .vid{font-family:verdana;font-style:italic;color:red;text-align:center} .ani{font-family:tahoma;font-style:italic;font-size:20;text-align:center;} font{font-family:georgia;color:blue;font-size:20} ul{list-style-type:circle} </style> </head> <body> <ol style="list-style-type:lower-alpha"> <b>PERI GROUP OF COLLEGES</b><br><br><br> <li>Raj Engineering College <li>PERI University and Research Institute <li> College of Engineering, Bangalore <li>Tamilnadu College of Arts and Science </ol> <p style="font-size:20pt;color:purple">A.C.S GROUP OF COLLEGES</p> <p class="ani">CSS Group of colleges is owned by XXX.<br>It is approved by International Council It is affliated to JKK University.<br></p> <h2 class="vid">DES College of Engg</h2> <br> <font>It is an ISO certified Institution</font><br> <br> <font> <h2>List of Courses offered</h2> <ul> <li>Computer Science and Engineering</li> <li>Ece</li> <li>mech</li> <li>eee</li> </ul> </font> <h3>Results of cse students</h3> <table width="100%" cellspacing="2" cellpadding="2" border="5">
  • 49.
    49 <tr> <th>S.NAME</th> <th>MARKS</th> <th>RESULT</th> </tr> <tr> <td align="center">Dinesh</td> <td align="center">100</td> <tdalign="center">pass</td> </tr> <tr> <td align="center">Bala</td> <td align="center">99</td> <td align="center">pass</td> </tr> <tr> <td align="center">Gopi</td> <td align="center">98</td> <td align="center">pass</td> </tr> </table> </body> </html> XYZ.CSS: h3{font-family:arial;font-size:20;color:cyan} table{border-color:green} td{font-size:20pt;color:magenta}
  • 50.
    50 3. Explain XHTMLSyntax and semantics with example.(16) XHTML – EXtensible HyperText Markup Language  is HTML defined as an XML application  is a stricter and cleaner HTML  is compatible to HTML 4.01 and supported by all browsers  is a W3C recommendation Why XHTML ? the following, ―bad‖ html document will work fine in most browser even if it does not follow HTML rules: <html> <head> <body> <p>a paragraph…<br> <a href=―#‖>test </html>  but browsers running on hand-held devices (e.g. mobile phones) have small computing power and can not interpret ―bad‖ markup language  HTML is designed to structure (and display) data and XML is designed to describe and structure data  XHTML specifies that everything must be marked up correctly  XHTML – base syntactic rules  XHTML elements must be properly nested <b><i> Italic and bold text </b></i> <b><i> Italic and bold text </i></b>  XHTML elements must always be closed <p> A paragraph… <br> <img src=―foo.jpg‖> <p> A paragraph…</p> <br /> <img src=―foo.jpg‖ />  XHTML elements must be in lowercase  XHTML elements must have one <html> root element (which contains a <head> and a <body>) XHTML – other syntactic rules  attribute names must be in lower case  attribute values must be quoted <table width=300px> <table width=―300px‖>  the ―id‖ attribute replaces the ―name‖ attribute  XHTML DTD defines mandatory elements  attribute minimization is forbidden <input checked>
  • 51.
    51 <input disabled> <input checked=―checked‖/> <input disabled=―disabled‖ /> General format of an XHTML document <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <title>…</title> </head> <body> … </body> </html> <!Doctype>,<html>,<head>,<title>,<body> are mandatory DTD – Document Type Definition  a DTD specifies the syntax of a document written in a SGML language (HTML, XHTML, XML) it specifies: o the hierarchical structure of the document, o element names and types o element content type o and attributes names and values o XML 1.0 has 3 DTDs: Strict, Transitional and Frameset DTD example (internal to XHTML file) <!DOCTYPE course [ <!ELEMENT course (lecture+)> <!ELEMENT lecture (title,bibliography,notes,examples)> <!ELEMENT title (#PCDATA)> <!ELEMENT bibliography (#PCDATA)> <!ELEMENT notes (#PCDATA)> <!ELEMENT examples (#PCDATA)> <!ATTLIST course professor CDATA #REQUIRED> <!ATTLIST course title CDATA #REQUIRED> <!ATTLIST course yearofstudy CDATA #REQUIRED> <!ATTLIST course date CDATA #IMPLIED> ]> XHTML validation  a valid XHTML document is an XHTML document which obeys the rules of the DTD specified by the <!Doctype> tag.  the official W3C XHTML validator:  http://validator.w3.org/check/referer  XHTML DTD is split in 28 modules
  • 52.
    52 3. i)Design aHTML Form for aRailwaay Reservation System? (8) ii)Explain about different types of XHTML DTD(8) Design a HTML Form for aRailwaay Reservation System? <FOTRM METHOD=º Postº ACTION=http://server name/directory name/Script name><HR> PASSENGER NAME: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR> ADDRESS: <INPUT TYPE=º Textº Name=º addº MAXLENGTH=º 24º <BR> CITY: <INPUT TYPE=º Textº Name=º cityº MAXLENGTH=º 24º <BR> STATE: <INPUT TYPE=º Textº Name=º stateº MAXLENGTH=º 24º ZIP: <INPUT TYPE=º Textº Name=º firstº MAXLENGTH=º 24º <BR> </HR> <INPUT TYPE=º submitº value=º reserveº ></FORM> ii)Explain about different types of XHTML DTD(8) Document Type Definitions (DTD) A DTD specifies the syntax of a web page in SGML DTDs are used by SGML applications, such as HTML, to specify rules for documents of a particular type, including a set of elements and entity declarations An XHTML DTD describes in precise, computer-readable language, the allowed syntax of XHTML markup There are three XHTML DTDs: STRICT TRANSITIONAL FRAMESET XHTML 1.0 Strict <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> Use the strict DOCTYPE when you want really clean markup, free of presentational clutter. Use it together with CSS. XHTML 1.0 Transitional <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> Use the transitional DOCTYPE when you want to still use HTML's presentational features. XHTML 1.0 Frameset <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
  • 53.
    53 4. Explain Stylesheets syntax and types of css with example. Cascading Style Sheets (CSS) are a method of web design that formats web page content according to a presentation style specified by the web page author. There are several advantages to using CS to format the presentation elements of a web page. CSS essentially separates document content from the manner in which it is presented, thus allowing for more fluid transitions between various browser platforms. CSS also provides for more precise control for spacing, alignment, and positioning of content without relying on the need for layout tables or frames. Font style, color, and font size can all be manipulated using CSS as well. The basic CSS Syntax Selector: is the hook used to choose what part(s) of your HTML to apply the CSS to. It indicates the element to which the rule is applied. Following the selector is the... •Declaration Block:Everything within the curly brackets, ―{‖ and ―}‖, is called the declaration block •Declaration: Inside a declaration block you can have as many declarations as you want and each declaration is a combination of a CSS Property and a value. •Property:is one of the CSS Properties used to tell what part of the selector will be changed (or styled). It specifies a characteristic, such as color, font-family, position, and is followed by a colon (:) •Value:assigns a value to the property. Types of selectors CSS has several types of selectors. Explaining all of them in detail would take too long. We will just introduce you with two most commonly used selectors. For a really in depth study, you should look into the W3C specification for selectors. Class and ID selectors With the class selector you can define different styles for the same type of HTML element.In our example, the class selector would look like this: P.blue {color: blue;}
  • 54.
    54 ID selector The W3Cdefines CSS ID as "a unique identifier to an element". IDs are commonly used for Layout and Uniqueness. Standards specify that any given ID name can only be referenced once within a page or document. From our experience, IDs are most commonly used correctly in CSS layouts. This makes sense because there are usually only one menu per page, one banner, and usually only one content pane. Grouping You can group selectors. Separate each selector with a comma H1, H2, H3, H4, H5, H6 {color: blue ;} Positioning The CSS positioning properties allow you to position an element. There are five different layout properties available in CSS: position: static, position: relative, position: absolute, and float. Three ways to insert CSS  Inline CSS  Internal Style Sheets  External Style Sheets Inline CSS The first way is called Inline Cascading Style Sheets. You can add CSS directly into the elements in your markup with the ―style‖ attribute. <div style=‖color:red;‖><p style=‖font-size:12px;‖> ―Style‖ is a ―Core HTML Attribute‖ so you can apply it to any visual HTML/XHTML elements. This may seem to be the easiest way of using CSS, but it is not recommended as it completely ignores the best parts of Cascading Style Sheets. Internal Style Sheets The second way adds CSS to a single document or web page by adding the following code into the <head> of your document using the <style> element. <style type="text/css"> hr {color: sienna} p {margin-left:20px} body {background-image:url("images/back40.gif")} </style> As you can see, <style> is an HTML element that is opened and closed. Within the <style> element is the CSS that will be applied to that page. There is no limit to the amount of CSS you can put inside the <style> element. You would enter this code in the <head> area of your web page (anywhere after <head> and before </head> in your HTML document) and that would apply this CSS to the elements of that web page. External Style Sheets The third and most advantageous way to embed CSS into a document uses External Cascading Style Sheets (or External Style Sheets). An external CSS file is simply a text file with a ―.css‖ extension. This file can then be included into many different pages.
  • 55.
    55 This allows youto make one document that has the styling for your entire website. Then you include that file into every page of your website. This is the recommended way of using CSS in your website as it lets you make global visual changes (to an entire website) by only tweaking one file. For Example, let‘s say you have a website where all the paragraphs are black, and you want to change them to grey. Since you have an external Style Sheet, you just open up that one CSS file and change the style for paragraphs to: color:grey; Now all the paragraphs on your website are grey! Here is the code you need to link the css fileto your webpages‖: <link rel=“stylsheet” type="text/css" href=“style.css”> Media Types There are about 10 different media types in CSS, but most common types are Screen and Print. CSS today allows you to link to more than one style sheet in your web page. 5.i)Explain about internet and intranet with difference.(8) ii) Design a HTML document using relative positioning to nudge text to the left. Internet It is a worldwide system which has the following characteristics: Internet is a world-wide / global system of interconnected computer networks. Internet uses the standard Internet Protocol (TCP/IP) Every computer in internet is identified by a unique IP address. IP Address is a unique set of numbers (such as 110.22.33.114) which identifies a computer‘s location. A special computer DNS (Domain Name Server) is used to give name to the IP Address so that user can locate a computer by a name.For example, a DNS server will resolve a name http://www.periit.com to a particular IP address to uniquely identify the computer on which this website is hosted. Internet is accessible to every user all over the world.
  • 56.
    56 Intranet Intranet is systemin which multiple PCs are connected to each other. PCs in intranet are not available to the world outside the intranet. Usually each company or organization has their own Intranet network and members/employees of that company can access the computers in their intranet. Each computer in Intranet is also identified by an IP Address which is unique among the computers in that Intranet. Similarities in Internet and Intranet Intranet uses the internet protocols such as TCP/IP and FTP. Intranet sites are accessible via web browser in similar way as websites in internet. But only members of Intranet network can access intranet hosted sites. In Intranet, own instant messengers can be used as similar to yahoo messenger/ gtalk over the internet. Differences in Internet and Intranet Internet is general to PCs all over the world whereas Intranet is specific to few PCs. Internet has wider access and provides a better access to websites to large population whereas Intranet is restricted. Internet is not as safe as Intranet as Intranet can be safely privatized as per the need. ii) Design a HTML document using relative positioning to nudge text to the left <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>
  • 57.
    57 RelativePos.html </title> <style type="text/css"> .right {position:relative; right:0.25em } </style> </head> <body> <p> <span style="background-color:red">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Red</span> <span style="background-color:yellow">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Yellow</span> <span style="background-color:lime">&nbsp;&nbsp;&nbsp;&nbsp; </span><span class="right">Green</span> </p> </body> </html>
  • 58.
    58 UNIT –III CLIENTSIDE AND SERVER SIDE PROGRAMMING PART-A 1. How to create an Object in JavaScript? An object is just a special kind of data, with a collection of properties and methods. You can add properties to an object by simply giving it a value. The sytax: objName.propName 2. What is the result of below given line of code in Java Script? 5+4+”7” The answer is 97. Here 5 and 4 are integers, bt since 7 is enclosed within quotes, its considered as a string, and hence is not added. 3.What is undefined value means in JavaScript? Undefined value means the variable used in the code doesnt exist or is not assigned any value or the property doesnt exist. 4. Which method is used to Clear an array using JavaScript? Clear() method is used to clear all the defined array. we use the clear() method which removes all elements from an Array instance. After removing the array by clear() method, the resulting array's length will become zero. 5.What will be the Output of the following using JavaScript document.Write(Math.Round(6.7)); The output will be 7. The math.round function is used to round off the value to the nearest higher integer value. 6.What should appear at the very end of your JavaScript? The <script LANGUAGE="JavaScript">tag 7.What is a JSP and what is it used for? Java Server Pages (JSP) is a platform independent presentation layer technology that comes with SUN s J2EE platform. JSPs are normal HTML pages with Java code pieces embedded in them. JSP pages are saved to *.jsp files. A JSP compiler is used in the background to generate a Servlet from the JSP page. 8. What is difference between custom JSP tags and beans? Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. To use custom JSP tags, you need to define three separate components: The tag handler class that defines the tag's behavior the tag library descriptor file that maps the XML element names to the tag implementations the JSP file that uses the tag library
  • 59.
    59 9. What arethe implicit objects? Implicit objects are objects that are created by the web container and contain information related to a particular request, page, or application. They are: –request ,response, pageContext, session application , out , config ,page ,exception 10. Compare Client side vs. server side scripting. Website scripts run in one of two places – the client side, also called the front-end, or the server side, also called the back-end. The client of a website refers to the web browser that is viewing it. The server of a website is the server that hosts it. Client side: JavaScript. Server side: PHP ,Ruby on Rails, ASP.NET 11. State the Servlet life cycle 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. 12. What is JavaScript? JavaScript is a programming language used to make web pages interactive. It runs on your visitor's computer and doesn't require constant downloads from your website. JavaScript is often used to create polls and quizzes 13. What is the purpose of cookies? Cookies make the interaction between users and websites faster and easier. Without cookies, it would be very difficult for a website to allow a visitor to fill up a shopping cart or to remember the user's preferences or registration details for a future visit. 14. What are the steps needs to establish JDBC connectivity? The programming involved to establish a JDBC connection is fairly simple. Here are these simple four steps −  Import JDBC Packages: Add import statements to your Java program to import required classes in your Java code.  Register JDBC Driver: This step causes the JVM to load the desired driver implementation into memory so it can fulfill your JDBC requests.  Database URL Formulation: This is to create a properly formatted address that points to the database to which you wish to connect.  Create Connection Object: Finally, code a call to the DriverManager object's getConnection( ) method to establish actual database connection. 15. What is the difference between GET and POST method?  GET is a safe method (idempotent) where POST is non-idempotent method.
  • 60.
    60  We cansend limited data with GET method and it‘s sent in the header request URL whereas we can send large amount of data with POST because it‘s part of the body.  GET method is not secure because data is exposed in the URL and we can easily bookmark it and send similar request again, POST is secure because data is sent in request body and we can‘t bookmark it.  GET is the default HTTP method whereas we need to specify method as POST to send request with POST method.  Hyperlinks in a page uses GET method. 16. What is different between web server and application server? A web server responsibility is to handler HTTP requests from client browsers and responds with HTML response. A web server understands HTTP language and runs on HTTPprotocol. Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat. Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications. 17. What are different methods of session management in servlets? Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. Some of the common ways of session management in servlets are: 1. User Authentication 2. HTML Hidden Field 3. Cookies 4. URL Rewriting 5. Session Management API 18. What is difference between GenericServlet and HttpServlet? GenericServlet is protocol independent implementation of Servlet interface whereas HttpServlet is HTTP protocol specific implementation. Most of the times we use servlet for creating web application and that‘s why we extend HttpServlet class. HttpServlet class extends GenericServlet and also provide some other methods specific to HTTP protocol.
  • 61.
    61 UNIT –III PART–B 1. Explain javascript variables and debuggers in detail . (16) JavaScript Variables JavaScript variables are used to hold values or expressions. A variable can have a short name, like x, or a more descriptive name, like carname. Rules for JavaScript variable names: Variable names are case sensitive (y and Y are two different variables) Variable names must begin with a letter or the underscore character Because JavaScript is case-sensitive, variable names are case-sensitive. Declaring (Creating) JavaScript Variables Creating variables in JavaScript is most often referred to as "declaring" variables. You can declare JavaScript variables with the var keyword: var x; var carname; After the declaration shown above, the variables are empty (they have no values yet). However, you can also assign values to the variables when you declare them: var x=5; var carname="Volvo"; After the execution of the statements above, the variable x will hold the value 5, and carname will hold the valueVolvo. Assigning Values to Undeclared JavaScript Variables If you assign values to variables that have not yet been declared, the variables will automatically be declared. These statements: x=5; carname="Volvo"; have the same effect as: var x=5;
  • 62.
    62 var carname="Volvo"; Redeclaring JavaScriptVariables If you redeclare a JavaScript variable, it will not lose its original value. var x=5; var x; After the execution of the statements above, the variable x will still have the value of 5. The value of x is not reset (or cleared) when you redeclare it. The Lifetime of JavaScript Variables If you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables. You can have local variables with the same name in different functions, because each is recognized only by the function in which it is declared. If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed 2. Discuss JavaScript Array object in detail. (16) JavaScript Arrays •Arrays are used to store lists or collections of items •Arrays in JavaScript are indexed by numbers from 0 •Array elements can be any type, even arrays or objects •An array‘s elements do not have to have the same type Creating Arrays Arrays can be created with the new keyword var(myArray(=(new(Array(); var(myArray(=(new(Array(―one‖,―two‖,(3); or with array literal syntax var(myArray(=([]; var(myArray(=([―one‖,(―two‖,(3]; Updating Array Elements Insert by index myArray[5](=(―new(item‖; Stack/queue-like interface myArray.push(―new(item‖); var(lastItem(=(myArray.pop(); var(firstItem(=(myArray.shift();
  • 63.
    63 Iterating Over Arrays var$myArray$=$[]; var$i; myArray.push(―one‖); myArray.push(―two‖); myArray.push(―three‖); for$(i=0;$i<myArray.length();$i+=1)${ console.log(myArray[i]); } OtherArray Methods var arrayLength = myArray.length(); myArray.length = 4; myArray.reverse(); myArray.sort(); myArray.indexOf(―this item‖); myArray.lastIndexOf(―this item‖); JavaScript Objects •Most things in JavaScript is an object - even functions •Objects have properties and methods •This distinction is vague, as functions are ‗first class‘ •Prototypes rather than class-based inheritance •The this keyword refers to the current object Creating Objects var(obj1(=(new(Object(); var(emptyObject(=({}; var(myObject(=({ ((((val1:(3, ((((val2:(―x‖, ((((func:(function()({ ((((((((console.log(this.val1(+(―(―(+ ((((((((((((((((((((this.val2); ((((} } Aside: Anonymous Functions •The value assigned to this.func may look a little odd •It is an an anonymous function, a function with no name •This is much the same as any other function, but it doesn‘t have a name •Anonymous functions can have parameters, and are commonly used when a function will be used just once •This simplifies code and reduces namespace clutter
  • 64.
    64 Using Objects •You candynamically add and update properties •myObj.newVal(=(―New(property‖; •myObj.val1(=(5; •You can call methods (properties which are functions) •myObj.func; Object Constructors function(MyConstructor()({ ((((this.val1(=(3; ((((this.val2(=(―x‖; ((((this.func(=(function()({ ((((((((console.log(this.val1(+(―(―(+ ((((((((((((((((((((this.val2); ((((} } var(myObject(=(new(MyConstructor(); The this Keyword •Note that the constructor assigns properties to this •What exactly this is depends on the context •In a constructor, this is the new object •In an object‘s method, this is the object itself •In a callback, this is the object that was triggered •In a browser, this is the window object by default Array-Like Objects •Some JavaScript objects look like arrays (but aren‘t) •document.getElementsByTagName(―p‖); •They can be indexed with [] and have .length •They don‘t have sort, push, etc. •If you add elements then .length doesn‘t change •What‘s going on here? •Objects can be indexed using [] as associative maps •Property names are given inside the brackets •And length is just another property var$obj$=${length:$2}; obj[0]$=$―one‖;$obj[1]$=$―two‖; obj.length$=$2; var$obj2$=${0:―one‖,$1:―two‖,$length:2};
  • 65.
    65 3. Write javascript to perform all arithmetic operation (16) <html> <head> <title> Arithmatic Operation </title> <script type="text/javascript"> var n1,n2,r; function add() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1+n2; document.myform.result.value=r; } function sub() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1-n2; document.myform.result.value=r; } function mul() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1*n2; document.myform.result.value=r; } function divide() { n1=document.myform.n1.value; n2=document.myform.n2.value; n1=parseFloat(n1); n2=parseFloat(n2); r=n1/n2; document.myform.result.value=r; } </script> </head> <body> <form name="myform">
  • 66.
    66 <h1 align="center"> ArithmaticOperations</h1> <hr color="red"> <center><u>Enter a number in each text box </u><br><br> Number 1:<input type="text" name="n1" value=""> <br><br> Number 2:<input type="text" name="n2" value=""> <br><br> <input type="button" value="Add" onClick="add()"> <input type="button" value="Subtract" onClick="sub()"> <input type="button" value="Multiply" onClick="mul()" > <input type="button" value="Divide" onClick="divide()"><br><br> <font color="red">Result is: <input type="text" name="result" value=""></center></font> </form> </body> </html> Output:
  • 67.
    67 4. Explain DOMevent handling in detail.(16) Document Object Model (DOM) ●Standard way of referring to an XML and HTML documents ●Returns to the notion of XML/HTML as a tree of nodes ●Sound familiar? ●Languages like JavaScript, implement the DOM to refer to the document root and its children as objects ● Once accessed, possible to manipulate the document structure <aside> DOM Support ●Proprietary at first ● W3C standardized ● Modern browsers support at least DOM Level 2 document Object ● Type HTMLDocument ● Always refers to the document root ● Properties ● offsetWidth/offsetHeight – dimensions of document ● Methods ● getElementById( id ) – return an Element object matching the given id ●createElement(tagName ) – create an Element instance, which may be later added to the document tree window Object ● Type Window ● Refers to the actual browser window ● Properties ●screen – provides information about the user's display ●Methods ●resizeTo(x, y) – resizes the window DOM Element Objects ●Actual HTML/XML elements ●Properties ●childNodes – array of element's children, including text nodes if any ●attributes – array of attribute-value pairs ●innerHTML – inner content of an element, read/write ●Methods ●appendChild(node) – Inserts a node at the end of the current node DOM Text Nodes ●Text content is treated as a node in the tree ●Typically seen as a child of another Element object
  • 68.
    68 CSS Properties ●All CSSproperties can be manipulated through the DOM ●Use the style property ●CSS properties are camelCase ●document.body.style.fontFamily = ―Verdana‖; DOM Events ●JavaScript can be triggered in response to events ●Done by implementing event listeners, called when events fire ●Event triggers ●User-driven (mouse/keyboard events) ●Document/Window (load, resize, scroll...) ●Form submissions Event Handling ●Find the element object ●Register the event handler ●element.onclick = foo; ●Many other triggers exist... ●Write the event handler ●function foo(e) { if (!e) var e = window.event; // Required for IE /* Do stuff */ } ●Could be an anonymous function! <aside> Inline Event Handling ●Some may have seen something like <body onload=‖foo()‖> ●Run into same maintenance issues as with CSS! ●Event handling within the script itself is always preferred Event Objects ●Whenever an event fires, information about the triggering event is passed to the event handler via an Event object ●Properties of this object can be checked for more information if needed ●type – Type of triggering event (mouseover, click, etc) ●timeStamp – When the event occurred ●Not all are compatible cross-browser! Event Propagation ●If an element and its child share an event handler, which fires first? ●Used to depend heavily on the browser... ●Netscape: ―The parent!‖ (Event Capturing) ●Microsoft: ―No, the child!‖ (Event Bubbling) ●W3C: ―...Fine. You're both right!‖
  • 69.
    69 W3C Event Propagation ●EventCapturing Phasehappens first ●Resolve in parent->child order ●Events are captured as they decend the DOM ●Event capturing ends when the target node is reached ●Event Bubbling Phasehappens next ●Resolve in child->parent order ●Events bubble upthrough the DOM W3C Event Propagation ●The developer can choose whether their event fires during event capturing or event bubbling ●By default, element.onclick = foo; syntax uses event bubbling 5. Write java servlet programs to conduct online examination and to display student mark list available in a database (16) SERVLET CODE: import java.io.*; import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; public class StudentServlet3 extends HttpServlet { String message,Seat_no,Name,ans1,ans2,ans3,ans4,ans5; int Total=0; Connection connect; Statement stmt=null; ResultSet rs=null; public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletExcep- tion,IOException { try { String url="jdbc:odbc:NEO"; Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); connect=DriverManager.getConnection(url," "," "); message="Thank you for participating in online Exam"; } catch(ClassNotFoundException cnfex){ cnfex.printStackTrace(); } catch(SQLException sqlex){ sqlex.printStackTrace(); } catch(Exception excp){ excp.printStackTrace(); } Seat_no=request.getParameter("Seat_no"); Name=request.getParameter("Name"); ans1=request.getParameter("group1"); ans2=request.getParameter("group2"); ans3=request.getParameter("group3"); ans4=request.getParameter("group4"); ans5=request.getParameter("group5"); if(ans1.equals("True")) Total+=2; if(ans2.equals("False")) Total+=2; if(ans3.equals("True"))
  • 70.
    70 Total+=2; if(ans4.equals("False")) Total+=2; if(ans5.equals("False")) Total+=2;try { Statement stmt=connect.createStatement(); String query="INSERT INTO student("+"Seat_no,Name,Total"+") VAL- UES('"+Seat_no+"','"+Name+"','"+Total+"')"; int result=stmt.executeUpdate(query); stmt.close(); }catch(SQLException ex){ } response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.println("<html>"); out.println("<head>"); out.println("</head>"); out.println("<body bgcolor=cyan>"); out.println("<center>"); out.println("<h1>"+message+"</h1>n"); out.println("<h3>Yours results stored in our database</h3>"); out.print("<br><br>"); out.println("<b>"+"Participants and their Marks"+"</b>"); out.println("<table border=5>"); try { Statement stmt=connect.createStatement(); String query="SELECT * FROM student"; rs=stmt.executeQuery(query); out.println("<th>"+"Seat_no"+"</th>"); out.println("<th>"+"Name"+"</th>"); out.println("<th>"+"Marks"+"</th>"); while(rs.next()) { out.println("<tr>"); out.print("<td>"+rs.getInt(1)+"</td>"); out.print("<td>"+rs.getString(2)+"</td>"); out.print("<td>"+rs.getString(3)+"</td>"); out.println("</tr>"); } out.println("</table>"); } catch(SQLException ex){ } finally { try { if(rs!=null) rs.close(); if(stmt!=null) stmt.close(); if(connect!=null) connect.close(); } catch(SQLException e){ } } out.println("</center>"); out.println("</body></html>"); Total=0; } }
  • 71.
    71 HTML CODE: <html> <head><title>Database Test</title></head> <body> <center> <h1>OnlineExamination</h1> </center> <form action="StudentServlet3.view" method="POST"> <div align="left"><br></div> <b>Seat Number:</b> <input type="text" name="Seat_no"> <div align="Right"> <b>Name:</b> <input type="text" name="Name" size="50"><br> </div> <br><br> <b>1. Every host implements transport layer.</b><br/> <input type="radio" name="group1" value="True">True <input type="radio" name="group1" value="False">False<br> <b>2. It is a network layer's responsibility to forward packets reliably from source to destina- tion</b><br/> <input type="radio" name="group2" value="True">True <input type="radio" name="group2" value="False">False<br> <b>3. Packet switching is more useful in bursty traffic</b><br/> <input type="radio" name="group3" value="True">True <input type="radio" name="group3" value="False">False<br> <b>4. A phone network uses packet switching</b><br/> <input type="radio" name="group4" value="True">True <input type="radio" name="group4" value="False">False<br> <b>5. HTML is a Protocol for describing web contents</b><br/> <input type="radio" name="group5" value="True">True <input type="radio" name="group5" value="False">False<br> <br><br><br> <center> <input type="submit" value="Submit"><br><br> </center> </form> </body> </html>
  • 72.
  • 73.
    73 UNIT-IV PHP andXML PART –A 1.Mention the rules of well-formed XML. All XML Elements Must Have a Closing Tag XML Tags are Case Sensitive XML Elements Must be Properly Nested XML Documents Must Have a Root Element XML Attribute Values Must be Quoted the white-space in a document is not truncated. 2.What is the DOM? The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated. The DOM defines a standard for accessing documents like HTML and XML: "The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document." 3. What is the XML DOM? The XML DOM defines the objects and properties of all XML elements, and the methods (interface) to access them. 4. What is the XMLHttpRequest Object? The XMLHttpRequest object is used to exchange data with a server behind the scenes. The XMLHttpRequest object is a developer's dream, because you can:  Update a web page without reloading the page  Request data from a server after the page has loaded  Receive data from a server after the page has loaded  Send data to a server in the background 5. What is XSL-FO? XSL-FO is about formatting XML data for output.  XSL-FO is a language for formatting XML data  XSL-FO stands for Extensible Stylesheet Language Formatting Objects  XSL-FO is based on XML  XSL-FO is a W3C Recommendation  XSL-FO is now formally named XSL 6. What is XSL-FO Documents? Explain XSL-FO Documents structure XSL-FO documents are XML files with output information. XSL-FO documents are stored in files with a .fo or a .fob file extension. You can also store XSL-FO documents with an .xml extension (to make them more accessible to XML editors).
  • 74.
    74 ?xml version="1.0" encoding="ISO-8859-1"?> <fo:rootxmlns:fo="http://www.w3.org/1999/XSL/Format"> <fo:layout-master-set> <fo:simple-page-master master-name="A4"> <!-- Page template goes here --> </fo:simple-page-master> </fo:layout-master-set> <fo:page-sequence master-reference="A4"> <!-- Page content goes here --> </fo:page-sequence> </fo:root> XSL-FO documents are XML documents, and must always start with an XML declaration: The <fo:root> element is the root element of XSL-FO documents. The root element also declares the namespace for XSL-FO: The <fo:layout-master-set> element contains one or more page templates: Each <fo:simple-page-master> element contains a single page template. Each template must have a unique name (master-name): One or more <fo:page-sequence> elements describe the page contents. The master- reference attribute refers to the simple-page-master template with the same name: 7. What is XSL-FO Processors? An XSL-FO processor is a software program for formatting XSL documents for output. Most XSL-FO processors can output HTML, PDF documents and quality print. 8. Explain XML Attributes with an example Attributes often provide information that is not a part of the data. Attribute values must always be quoted. Either single or double quotes can be used Some of the problems with using attributes are:  attributes cannot contain multiple values (elements can)  attributes cannot contain tree structures (elements can)  attributes are not easily expandable (for future changes) Attributes are difficult to read and maintain. Use elements for data. Use attributes for information that is not relevant to the data. 9. XML Elements vs. Attributes. <person sex="female"> <firstname>Anna</firstname> <lastname>Smith</lastname> </person> <person> <sex>female</sex> <firstname>Anna</firstname> <lastname>Smith</lastname> </person>
  • 75.
    75 In the firstexample sex is an attribute. In the last, sex is an element. Both examples provide the same information. There are no rules about when to use attributes or when to use elements. Attributes are handy in HTML. But in XML it is better to use elements. 10. What are the problems with using XML attributes? Some of the problems with using attributes are:attributes cannot contain multiple values (elements can)attributes cannot contain tree structures (elements can)attributes are not easily expandable (for future changes) 11. What is XSLT? XSLT is the recommended style sheet language of XML. XSLT (eXtensible Stylesheet Language Transformations) is far more sophisticated than CSS. XSLT can be used to transform XML into HTML. 12. What are the roles of XSLT? The roles of XSLT are: XSLT is used to transform an XML document into another XML document such as HTML, etc. XSLT can be used to add or remove elements and attributes to or from the output file. XSLT can also be used for rearranging and sorting elements.It can also be used for performing tests and making decisions about hiding and displaying of elements 13.What is XSLT? Explain its relationships with XSL XSLT stands for eXtensible Stylesheet Language Transformations. It is a language used to convert XML documents to XHTML or other XML documents. This conversion is done by transforming each XML element into an (X)HTML element.. it uses XPath to find information in a XML document. XSLT is nothing but transforming XSL‘s. Xpath defines the parts of the source document that must match one or more predefined templates. Once a match is found, XSLT will transform the match into the result document. 14.What is XSLT stylesheet? XSL stylesheet is just like a XML document used as a program text or a source. It contains sets of rules and instructions used for transformations. XSLT stylesheet along with the XML source documents are the inputs to the XSLT processor. The template rule contains two parts: a pattern used to match the nodes in the source document and a template which can be instantiated to form part of the result tree. A stylesheet is represented by an xsl:stylesheet element in an XML document. 15.Discuss the role of XPATH XPATH is used to scan the XML document for navigation of elements and attributes. It contains a library of standard functions string ad numeric values. For navigation, XPATH makes use of path expressions to select nodes or sets of nodes in a XML document.
  • 76.
    76 16.Explain the XSLTdata model XSLT shares the same data model of XPATH with some additions. XSLT accepts a XSLT stylesheet as an input and output is another XML, text or another document. The model is based on text nodes. These text nodes are embedded within element nodes. The model is a hierarchical structure like a tree. The tree has a variety of nodes like- text nodes, attribute nodes, element nodes, comment nodes, and processing instruction nodes. For every node type there is a way of determining a string-value for a node of that type. 17.Why the need for XHTML? If a script in an HTML document is not well formed, small devices like mobile phones fail to display the content properly. Also, upgrading all the browsers to support XML is a timely affair. An intermediate solution is XHTML that is a combination of HTML and XML. In XTML the content has to be well formed so that there is no bad HTML 18.What is XQuery language? XQuery is a way to query the XML data, It is built on XPath expressions and is supported by quite a few database engines. It can find and extract elements and attributes from XML documents. 19.Explain the Relation between RSS and XML XML or Extensible Markup Language is used to organize generic information with tags in a structured document. Really Simple Syndication is an extension of XML is used to o organize headlines of news. RSS formats are specified using XML and can be considered as an extended schemas of XML. 20. Define. DOM The Document Object Model (DOM) is a cross-platform and language-independent convention for representing and interacting with objects in HTML, XHTML and XML documents. Aspects of the DOM (such as its "Elements") may be addressed and manipulated within the syntax of the programming language in use. The public interface of a DOM is specified in its application programming interface (API).
  • 77.
    77 UNIT-IV PART –B 1.Given an XSLT document and a source XML document explain the XSLT transformation process that produces a single result XML document. (16) XSL XSL is stands for eXtensible Style sheet Language which is an xml vocabulary. It contains two types of information: Template data: Which is text that is copied to output xml document with change or no change. XSL markup: which controls transformation process. It uses two namespaces: o http://www.w3.org/1999/xsl/Transform is the namespace name for xsl namespace o http://www.w3.org/1999/xhtml is the xhtml namesapce name XSL components: Three components 1. XSLT 2. XPATH 3. XSL-FO XSLT – XSL Transformations (XSLT) is a language to specify transformations of XML documents. A transformation expressed in XSLT describes rules for transforming a source tree into a result tree XPATH- is used to find information in an XML document. It navigates through elements and attributes in XML documents. XSL-FO is a XSL Formatter an xml vocabulary for defining style properties of xml document. To transform xml document the following things are required: a. Source xml document b. Xslt style sheet that defines the information of source xml program to be transformed c. Xslt processor that performs transformation The following program illustrates that.
  • 78.
    78 The JAXP isa tool which is used as XSLT processor. The XSLT processor receives xslt and xml program as its input and generates another xml program as its output where we can see the content retrieved from source xml program You can refer lab experiment also Example for XSLT Step 1. Create an XML file and save as The code for the emp.xml file is given below: <?xml version = "1.0" ? > <Employee-Detail> <Employee> <Emp_Id> E-001 </Emp_Id> <Emp_Name> Nisha </Emp_Name> <Emp_E-mail> Nisha1@yahoo.com </Emp_E-mail> </Employee> <Employee> <Emp_Id> E-002 </Emp_Id> <Emp_Name> Amit</Emp_Name> <Emp_E-mail> Amit2@yahoo.com </Emp_E-mail> </Employee> </Employee-Detail> Step 2: Create an XSLT Stylesheetand save as myXSL.xsl extension <?xml version="1.0" ?> <xsl:transform xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0"> <xsl:template match="/"> <html><head><title> XSL for Transforamtion </title> <body><p> <xsl:for-each select="Employee"> <xsl:value-of select="child::Emp_Id"/> <xsl:value-of select="child::Emp_Name"/> <xsl:value-of select="child::Emp_E-mail"/> </xsl:for-each> </p></body></html> </xsl:template> </xsl:stylesheet> Step 3: Create XML Transformer program in java and give input both .xml and .xsl file import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.Source; import javax.xml.transform.Result; import javax.xml.transform.OutputKeys; public class XMLwithXSLT { public static void main(String[] args) throws Exception { Sourcesource= new StreamSource("myXML.xml"); Source xsl= new StreamSource("myXSL.xsl");
  • 79.
    79 TransformerFactoryfactory= TransformerFactory.newInstance(); Transformertransformer= factory.newTransformer(xsl); newStreamResult(System.out); } } Output of the program:- The following figure illustrates how the xslt transformer constructs the source tree from source xml document and by using that with the help of xsl program how the result tree is constructed. Result tree is constructed base on the following definitions given in xsl style sheet <html> <head><title> XSL for Transforamtion </title> <body><p> <xsl:for-each select="Employee"> <xsl:value-of select="child::Emp_Id"/> <xsl:value-of select="child::Emp_Name"/> <xsl:value-of select="child::Emp_E-mail"/> </xsl:for-each> </p></body> </html> </xsl:template>
  • 80.
    80 2.Write a programto display student information using XSLT in XML document (16) Step no. Details of the step 1 Start the program 2 Create an XML document with the details of the student such as name, address, standard and mark. 3 Import an XSL file to the xml file. 4 The XSL file imported puts the details of the students given in the xml file in a table and gets the details of each student from the xml file using the value-of attribute. 5 The output in the browser would be the details from the XML file with the style specified in XSL applied to it. 6 Stop the program. Info.XML: <?xml version="1.0" encoding="UTF-8"?> <?xml-stylesheet type="text/xsl" href="detail.xsl"?> <student> <personal_info> <name>gokila</name> <addr>neyveli</addr> <std>3rd yr</std> <mark>98</mark> </personal_info> <personal_info> <name>sivamani</name> <addr>andimadam</addr> <std>3rd yr</std> <mark>95</mark> </personal_info> <personal_info> <name>sivasangari</name> <addr>kumbakonam</addr> <std>3rd yr</std> <mark>98</mark> </personal_info> <personal_info> <name>sangeetha</name> <addr>pennadam</addr> <std>3rd yr</std>
  • 81.
    81 <mark>88</mark> </personal_info> </student> Detail.XSL: <?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheetversion="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:template match="/"> <html> <body bgcolor="pink"> <center><h2>student database</h2></center> <center> <table bgcolor="aqua" border="7" width="650" height="400"> <tr> <th>name</th> <th>addr</th> <th>std</th> <th>mark</th> </tr> <xsl:for-each select="student/personal_info"> <xsl:sort select="mark"/> <tr> <td><xsl:value-of select="name"/></td> <td><xsl:value-of select="addr"/></td> <td><xsl:value-of select="std"/></td> <td><xsl:value-of select="mark"/></td> </tr> </xsl:for-each> </table> </center> </body> </html> </xsl:template> </xsl:stylesheet>
  • 82.
    82 3. i)Explain therole XML namespaces with an example.(8) (ii)Explain the feature of XML path.(8) XML namespace provide a method to avoid elemwnt name conflicts.It is a collection of element and attribute names associated with a particular XML vocabulary through an absolute URI known as namespace name. Default namespace: <html xmlns=‖http:// www.w3.org/1999/xhtml‖> <element name xmlns:prefix=‖namespace identifier ―> Another form of xml attribute known as namespace declaration XML document 1 <table> <tr> <td>Apples</td> <td>Bananas</td> </tr> </table> XML document2 <table> <name> Coffee Table</name> <width>80</width> <length>120</length> </table> If these XML fragments were added together, there would be a name conflict. Both contain a <table> element, but the elements have different content and meaning. Such name conflicts in XML can easily be avoided using a name prefix as shown below: <h:table> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table> When using prefixes in XML, a so-called namespace for the prefix must be defined. The namespace is defined by the xmlns attribute in the start tag of an element. The namespace declaration has the following syntax. xmlns:prefix="URI" For example, <h:table xmlns:h="http://www.w3.org/table"> <h:tr> <h:td>Apples</h:td> <h:td>Bananas</h:td> </h:tr> </h:table> <f:table xmlns:f="http://www.w3.org/furniture"> <f:name>African Coffee Table</f:name> <f:width>80</f:width> <f:length>120</f:length> </f:table>
  • 83.
    83 Default namespace Default xmlnamespace uri for elements of a Document is: xmlns:‖http://www.w3.org/1999/xhtml‖ (ii)Explain the feature of XML path. (8) XPATH Is the syntax for specifying a collection of elements on other info contained within xml doc. XPATH expression will be applied to parse the xml doc. which constructs a tree like representation of xml doc. similar to DOM tree. The root of the XPath parse tree is ‗document‘ Location Paths <xsl:template match="/"> which represents the XPath document root. An XPath expression such as this represents one or more nodes within XPath parse tree is known as location path. This location path consists a ‗location step‘ Location step has two parts: An axis name followed by (::) Node test child::Emp_Id is an example of a location step and has two parts: Axis name specifies the direction to which we can search a node Node test specifies an element name selected for transformation Axis name: The following are several axis names uses to search a particular element in the xml doc Predicate: XPath uses some predicate which constructs the node test. Predicate can be either child::<element name> (Or) Attribute::<value> XPAth last() function always returns the no of nodes in the list being filtered, the value of position() function depends on the axis of the location step. Some XPXath predicates: 1.related node exists child::title node has child element of type title. 2. Attribute exists attribute::display node has attribute named display.
  • 84.
    84 Location path: It canconsists of several location steps separated by / characters , as in Child :: para/child:: strong First the leftmost location step is evaluated, producing a node list. Given example evaluation of the given location path with respect to the following XML document. <body> <para id=‖p1‖> This is <strong id =‖s1‖> important </strong> to know <strong id=‖s2‖> important </strong> </para> <para id =‖p2‖> This is not as important. <em> <strong id=‖s3‖> Is this? </strong></em> </para> </body> Absolute and Relative Location Path A location path can consists of several location steps separated by / character. For example, The difference between these two types of paths is that an absolute path begins with a slash(/) while a relative path doesnot.specifically a relative location path defines a set of nodes relative to the context node, while an absolute location path defines a set of nodes relative to the document root. Combining Node lists The pipe symbol(|) can be used to represent a node set produced by taking the union of the nodes sets returned by multiple location path. Thus ,The XPATH expression Child :: strong |descendant :: emph Represents a node set containing all of the strong children of the context node as well as all of its emph descendants.
  • 85.
    85 4. Explain themodel view controller architecture pattern in detail. (16) Many web applications are based on the Model-View-Controller (MVC) architecture pattern. That is, web apps contains three parts: 1) business logic 2) presentation and 3) request processing The key motivation behind the MVC approach is the desire to separate the code that creates and manipulates the data (i.e business logic) from the code that presents the data (i.e presentation) and the code that process the request (i.e controller) Business logic means the codeapplied for manipulation of application data and presentation refers the code written for look and feel of the web page such as background color, font style, placing of form controls and so on. Controller means that process the request message. According to MVC, the Model corresponds to business logic, the View corresponds to presentation and the Controller corresponds to request processing Typical JSP implementation of MVC
  • 86.
    86 Java servlet programis the Controller component that receives the request from the browser. Java bean class is the Modelcomponent that processes the business logic which can use the data source for that. Jsp is the View component that presents theresult of the business logic to the browser with the help of controller. The following program also illustrates that. In this architecture, JSP is used for creating the view for the application. A centralized Servlet is used to handle the entire request for the application. The Servlet works as the controller for the application. It then uses the Java beans for processing the business logic and getting the (Model) from the database. Finally it uses the JSP to render the view which is displayed to the user. Advantage of using MVC - MVC allows the developer to keep the separation between business logic, presentation and request processing. Due to this separation, any changes to the presentation can be made easy without disturbing business logic data 5. Write Programs using XML – Schema – XSLT/XSL (16) <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <breakfast_menu> <food> <name>Belgian Waffles</name> <price>$5.95</price> <description>two of our famous Belgian Waffles with plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name>Strawberry Belgian Waffles</name>
  • 87.
    87 <price>$7.95</price> <description>light Belgian wafflescovered with strawberries and whipped cream</description> <calories>900</calories> </food> <food> <name>Berry-Berry Belgian Waffles</name> <price>$8.95</price> <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description> <calories>900</calories> </food><food> <name>French Toast</name> <price>$4.50</price> <description>thick slices made from our homemade sourdough bread</description> <calories>600</calories> </food> <food> <name>Homestyle Breakfast</name> <price>$6.95</price> <description>two eggs, bacon or sausage, toast, and our ever-popular hash browns</description> <calories>950</calories> </food> </breakfast_menu> XSLT File <?xml version="1.0" encoding="ISO-8859-1"?> <!-- Edited by XMLSpy® --> <html xsl:version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns="http://www.w3.org/1999/xhtml"> <body style="font-family:Arial;font-size:12pt;background-color:#EEEEEE"> <xsl:for-each select="breakfast_menu/food"> <div style="background-color:teal;color:white;padding:4px"> <span style="font-weight:bold"><xsl:value-of select="name"/></span> <xsl:value-of select="price"/> </div> <div style="margin-left:20px;margin-bottom:1em;font-size:10pt"> <xsl:value-of select="description"/> <span style="font-style:italic"> <xsl:value-of select="calories"/> (calories per serving) </span> </div> </xsl:for-each> </body> </html>
  • 88.
    88 UNIT V –INTRODUCTION TO AJAX and WEB SERVICES PART –A 1. What is DTD? Explain it with example. The purpose of a DTD (Document Type Definition) is to define the legal building blocks of an XML document. A DTD is a set of rules that specifies how to use XML markup. It contains Specifications. For each element, including what the element's attributes are, what values the attributes ca take on and what elements can be contained in others. A DTD defines the document structure with a list of legal elements and attributes. If the DTD is declared inside the XML file, it should be wrapped in a DOCTYPE definition with the following syntax: <!DOCTYPE root-element [element-declarations]> With a DTD, each of your XML files can carry a description of its own format. With a DTD, independent groups of people can agree to use a standard DTD for interchanging data. Your application can use a standard DTD to verify that the data you receive from the outside world is valid. You can also use a DTD to verify your own data. 2. What is AJAX? Ajax shorthand for Asynchronous JavaScript and XML) is a group of interrelated web development methods used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the ackground without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object. 3.What is a web service? Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system. XML is used to encode all communications to a Web service. 4.What is SOAP? SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another. 5. What is SOAP and how it will be utilized in web-components? SOAP stands for Simple Access protocol. SOAP was first offered in 1990's and has been introduced to W3C in 2000. The main purpose of SOAP to be able to send request to invoke programs on remote computers using XML wrappers.
  • 89.
    89 6. Explain aboutthe role of XML in SOAP? XML is chosen as a standard format because it was already in use by many large companies and immensely due to its open source nature. A wide variety of tools are available on helves which ease the process of transition to SOAP. XML can significantly reduce the speed and efficiency but binary XML is being considered as a format for future. 7.What are the elements which should be contained in SOAP message? Following elements are contained in the SOAP message. 1) An envelope element which identifies and translates the XML document into a SOAP message. 2) A header element is a must as it should contain header message. 3) A body is required which should contain call and response message. 4) Fault element is required which can communicate about the errors occurred during the process 8. What is SOAP? SOAP: Simple Object Access Protocol is a protocol that is used to exchange structured information at the time of implementing a web service. SOAP is relied on XML. Message format of SOAP usually relies on another protocol of different application layers. Among these the most notable application layer is Remote Procedure Call and HTTP. SOAP forms the foundation layer for web services protocol stack. This stack provides the basic framework for messaging on which the web services are built. 9. Explain web services architecture. Web Services are based on three operations: publish, find, and bind. Service providers publish services to a service broker. Service requesters find required services using a service broker and bind to them. 10. What is WSDL? Web Services Description Language (WSDL) is a format for describing a Web Services interface. It is a way to describe services and how they should be bound to specific network addresses
  • 90.
    90 11. Differentiate betweenAJAX and Java Script AJAX JavaScript AJAX allows the coder send request data asynchronously in order load new data without changing the web page. JavaScript is a client side scripting language that allows the creation of dynamic web pages by providing a new level of interactivity. AJAX supports the server side scripting Language. JavaScript provides support to the client side scripting language. AJAX can load the web page after it is been loaded for the first time. JavaScript cannot load the pages after it is once loaded. AJAX does not install Trojan in the computer. JavaScript can install Trojan in the computer 12. What are the advantages of AJAX ?  XMLHttpRequest: The XMLHttpRequest of Ajax provides support to different kinds of HTTP request types. AJAX XMLHttpRequest can be used to send request for non-AJAX pages as well.  IFrame: The IFrame feature in AJAX supports every modern browser and asynchronous file uploads. AJAX can make request by both POST and GET methods.  Cookies: Even though there is an implementation difference between the browsers, the cookies in AJAX provides support for more number of browsers.  Interface: The interface in AJAX is very responsive. The required section of the page is transferred at a point of time rather than transferring the whole page.  Waiting Time: The waiting time in AJAX has been reduced.  Traffic: In AJAX, the traffic which occurs during the ‗To‘ and ‗From‘ process in the server has been reduced. 13. Define Web Service? A web service is a kind of software that is accessible on the Internet. It makes use of the XML messaging system and offers an easy to understand, interface for the end users. 14. Brief few drawbacks of using GET and POST methods to communicate with the web service? These methods are less secure and inhibit users to pass structures and objects as arguments. Also, it doesn‘t allow users to pass ByRef arguments. 15. Differentiate between a SOA and a Web service? SOA is a design and architecture to implement other services. SOA can be easily implemented using various protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP, RPC etc. While Web service, itself is an implemented technology. In fact one can implement SOA using the web service.
  • 91.
    91 UNIT –V PART–B 1. Describe the significance and working of WSDL with an example WSDL stands for Web Services Description Language. It is the standard format for describing a web service. WSDL was developed jointly by Microsoft and IBM. Features of WSDL  WSDL is an XML-based protocol for information exchange in decentralized and distributed environments.  WSDL definitions describe how to access a web service and what operations it will perform.  WSDL is a language for describing how to interface with XML-based services.  WSDL is an integral part of Universal Description, Discovery, and Integration (UDDI), an XML-based worldwide business registry.  WSDL is the language that UDDI uses.  WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'. WSDL Usage WSDL is often used in combination with SOAP and XML Schema to provide web services over the Internet. A client program connecting to a web service can read the WSDL to determine what functions are available on the server. Any special datatypes used are embedded in the WSDL file in the form of XML Schema. The client can then use SOAP to actually call one of the functions listed in the WSDL. The three major elements of WSDL that can be defined separately are:  Types  Operations  Binding A WSDL document has various elements, but they are contained within these three main elements, which can be developed as separate documents and then they can be combined or reused to form complete WSDL files. WSDL Elements A WSDL document contains the following elements:  Definition : It is the root element of all WSDL documents. It defines the name of the web service, declares multiple namespaces used throughout the remainder of the document, and contains all the service elements described here.  Data types : The data types to be used in the messages are in the form of XML schemas.  Message : It is an abstract definition of the data, in the form of a message presented either as an entire document or as arguments to be mapped to a method invocation.  Operation : It is the abstract definition of the operation for a message, such as naming a method, message queue, or business process, that will accept and process the message.  Port type : It is an abstract set of operations mapped to one or more end-points, defining the collection of operations for a binding; the collection of operations, as it is abstract, can be mapped to multiple transports through various bindings.  Binding : It is the concrete protocol and data formats for the operations and messages defined for a particular port type.
  • 92.
    92  Port :It is a combination of a binding and a network address, providing the target address of the service communication.  Service : It is a collection of related end-points encompassing the service definitions in the file; the services map the binding to the port and include any extensibility definitions.In addition to these major elements, the WSDL specification also defines the following utility elements:  Documentation: This element is used to provide human-readable documentation and can be included inside any other WSDL element.  Import : This element is used to import other WSDL documents or XML Schemas. The WSDL Document Structure The main structure of a WSDL document looks like this: <definitions> <types> definition of types........ </types> <message> definition of a message.... </message> <portType> <operation> definition of a operation....... </operation> </portType> <binding> definition of a binding.... </binding> <service> definition of a service.... </service> </definitions> A WSDL document can also contain other elements, like extension elements and a service element that makes it possible to group together the definitions of several web services in one single WSDL document Example Contents of HelloService.wsdl file: <definitions name="HelloService" targetNamespace="http://www.examples.com/wsdl/HelloService.wsdl" xmlns="http://schemas.xmlsoap.org/wsdl/" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
  • 93.
    93 xmlns:tns="http://www.examples.com/wsdl/HelloService.wsdl" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> <message name="SayHelloRequest"> <part name="firstName"type="xsd:string"/> </message> <message name="SayHelloResponse"> <part name="greeting" type="xsd:string"/> </message> <portType name="Hello_PortType"> <operation name="sayHello"> <input message="tns:SayHelloRequest"/> <output message="tns:SayHelloResponse"/> </operation> </portType> <binding name="Hello_Binding" type="tns:Hello_PortType"> <soap:binding style="rpc" transport="http://schemas.xmlsoap.org/soap/http"/> <operation name="sayHello"> <soap:operation soapAction="sayHello"/> <input> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/> </input> <output> <soap:body encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" namespace="urn:examples:helloservice" use="encoded"/> </output> </operation> </binding> <service name="Hello_Service"> <documentation>WSDL File for HelloService</documentation> <port binding="tns:Hello_Binding" name="Hello_Port"> <soap:address location="http://www.examples.com/SayHello/" /> </port> </service> </definitions>
  • 94.
    94 2. Describe themajor elements of SOAP (16) SOAP is an acronym for Simple Object Access Protocol. It is an XML-based messaging protocol for exchanging information among computers. SOAP is an application of the XML specification. A SOAP message is an ordinary XML document containing the following elements −  Envelope − Defines the start and the end of the message. It is a mandatory element.  Header − Contains any optional attributes of the message used in processing the message, either at an intermediary point or at the ultimate end-point. It is an optional element.  Body − Contains the XML data comprising the message being sent. It is a mandatory element.  Fault − An optional Fault element that provides information about errors that occur while processing the message. All these elements are declared in the default namespace for the SOAP envelope − SOAP Message Structure The following block depicts the general structure of a SOAP message − <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap- envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Header> ... ... </SOAP-ENV:Header> <SOAP-ENV:Body> ... ... <SOAP-ENV:Fault> ... ... </SOAP-ENV:Fault> ... </SOAP-ENV:Body> </SOAP_ENV:Envelope> Example: SOAP request − POST /Quotation HTTP/1.0 Host: www.xyz.org Content-Type: text/xml; charset=utf-8 Content-Length: nnn <?xml version="1.0"?>
  • 95.
    95 <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap- envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding"> <SOAP-ENV:Body xmlns:m="http://www.xyz.org/quotations" > <m:GetQuotation> <m:QuotationsName>MiscroSoft</m:QuotationsName> </m:GetQuotation> </SOAP-ENV:Body> </SOAP-ENV:Envelope> A corresponding SOAP response looks like − HTTP/1.0 200 OK Content-Type: text/xml; charset=utf-8 Content-Length: nnn <?xml version="1.0"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap- envelope" SOAP-ENV:encodingStyle="http://www.w3.org/2001/12/soap-encoding" > <SOAP-ENV:Body xmlns:m="http://www.xyz.org/quotation" > <m:GetQuotationResponse> <m:Quotation>Here is the quotation</m:Quotation> </m:GetQuotationResponse> </SOAP-ENV:Body> </SOAP-ENV:Envelope>
  • 96.
    96 3. Explain aboutAJAX Http Request Object (16) XMLHttpRequest (XHR) is an API that can be used by JavaScript, JScript, VBScript, and other web browser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent connection channel between a webpage's Client-Side and Server-Side. The data returned from XMLHttpRequest calls will often be provided by back-end databases. Besides XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or even plain text. XMLHttpRequest Methods  abort() Cancels the current request.  getAllResponseHeaders() Returns the complete set of HTTP headers as a string.  getResponseHeader( headerName ) Returns the value of the specified HTTP header.  open( method, URL ) open( method, URL, async ) open( method, URL, async, userName ) open( method, URL, async, userName, password ) Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications) may be possible. The "async" parameter specifies whether the request should be handled asynchronously or not. "true" means that the script processing carries on after the send() method without waiting for a response, and "false" means that the script waits for a response before continuing script processing. send( content ) Sends the request. setRequestHeader( label, value ) Adds a label/value pair to the HTTP header to be sent. XMLHttpRequest Properties onreadystatechange An event handler for an event that fires at every state change. readyState The readyState property defines the current state of the XMLHttpRequest object. The following table provides a list of the possible values for the readyState property: State Description 0 The request is not initialized. 1 The request has been set up. 2 The request has been sent. 3 The request is in process. 4 The request is completed.
  • 97.
    97 readyState = 0After you have created the XMLHttpRequest object, but before you have called the open() method. readyState = 1 After you have called the open() method, but before you have called send(). readyState = 2 After you have called send(). readyState = 3 After the browser has established a communication with the server, but before the server has completed the response. readyState = 4 After the request has been completed, and the response data has been completely received from the server. responseText Returns the response as a string. responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properties. status Returns the status as a number (e.g., 404 for "Not Found" and 200 for "OK"). statusText Returns the status as a string (e.g., "Not Found" or "OK"). Here is a list of some famous web applications that make use of AJAX. Google Maps A user can drag an entire map by using the mouse, rather than clicking on a button.  http://maps.google.com/ Google Suggest As you type, Google will offer suggestions. Use the arrow keys to navigate the results.  http://www.google.com/webhp?complete=1&hl=en Gmail Gmail is a webmail, built on the idea that email can be more intuitive, efficient and useful.  http://gmail.com/ Yahoo Maps (new) Now it's even easier and more fun to get where you're going!  http://maps.yahoo.com/
  • 98.
    98 4. Explain indetails about Web Services Conceptual Architecture (16) The Web Services Model The Web Services architecture is based upon the interactions between three roles: service provider, service registry and service requestor. The interactions involve the publish, find and bind operations. Together, these roles and operations act upon the Web Services artifacts: the Web service software module and its description. In a typical scenario, a service provider hosts a network-accessible software module (an implementation of a Web service). The service provider defines a service description for the Web service and publishes it to a service requestor or service registry. The service requestor uses a find operation to retrieve the service description locally or from the service registry and uses the service description to bind with the service provider and invoke or interact with the Web service implementation. Service provider and service requestor roles are logical constructs and a service can exhibit characteristics of both. Figure 1 illustrates these operations, the components providing them and their interactions Roles in a Web Services Architecture • Service provider. From a business perspective, this is the owner of the service. From an architectural perspective, this is the platform that hosts access to the service. • Service requestor. From a business perspective, this is the business that requires certain functions to be satisfied. From an architectural perspective, this is the application that is looking for and invoking or initiating an interaction with a service. The service requestor role can be played by a browser driven by a person or a program without a user interface, for example another Web service • Service registry. This is a searchable registry of service descriptions where service providers publish their service descriptions. Service requestors find services and obtain binding information (in the service descriptions) for services during development for static binding or during execution for dynamic binding. For statically bound service requestors, the service registry is an optional role in the architecture, because a service provider can send the description directly to service requestors. Likewise, service requestors can obtain a service description from other sources besides a service registry, such as a local file, FTP site, Web site, Advertisement and Discovery of Services (ADS) or Discovery of Web Services (DISCO).
  • 99.
    99 Operations in WebService Architecture For an application to take advantage of Web Services, three behaviors must take place: Publication of service descriptions, lookup or finding of service descriptions, and binding or invoking of services based on the service description. These behaviors can occur singly or iteratively. In detail, these operations are: • Publish. To be accessible, a service description needs to be published so that the service requestor can find it. Where it is published can vary depending upon the requirements of the application (see ―Service Publication‖ for more details). • Find. In the find operation, the service requestor retrieves a service description directly or queries the service registry for the type of service required (see ―Service Discovery‖ for more details). The find operation can be involved in two different lifecycle phases for the service requestor: at design time to retrieve the service‘s interface description for program development, and at runtime to retrieve the service‘s binding and location description for invocation. • Bind. Eventually, a service needs to be invoked. In the bind operation the service requestor invokes or initiates an interaction with the service at runtime using the binding details in the service description to locate, contact and invoke the service. The development lifecycle can have four phases: 1. Build The build phase of the lifecycle includes development and testing of the Web service implementation, the definition of the service interface description and the definition of the service implementation description. Web service implementations can be provided by creating new Web Services, transforming existing applications into Web Services, and composing new Web Services from other Web Services and applications. 2. Deploy The deploy phase includes the publication of the service interface and service implementation definition to a service requestor or service registry and deployment of the executables for the Web service into an execution environment (typically, a Web application server). 3. Run During the run phase, the Web service is available for invocation. At this point, the Web service is fully deployed, operational and network-accessible from the service provider. Now the service requestor can perform the find and bind operations. 4. Manage The manage phase covers ongoing management and administration of the Web service application. Security, availability, performance, quality of service and business processes must all be addressed The Web Services Stack To perform the three operations of publish, find and bind in an interoperable manner, there must be a Web Services stack that embraces standards at each level. Figure 2 shows a conceptual Web Services stack. The upper layers build upon the capabilities provided by the lower layers. The vertical towers represent requirements that must be addressed at every level of the stack. The text on the left represents standard technologies that apply at that layer of the stack.
  • 100.
    100 5. Write aprogram to run and implement the web service (16) NewWebService.java: /*To change this template, choose Tools | Templates and open the template in the editor. */ package pack1; import javax.jws.WebService; import javax.jws.WebMethod; import javax.jws.WebParam; import java.sql.*; /***@author SREC*/ @WebService() public class NewWebService { @WebMethod (operationName="get") public String[] get(@WebParam(name="from")String from,@WebParam (name="to")String to) { String hello[]=new String[6]; int i=0; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); String filename = "d:/data1.mdb"; String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ="; database+= filename.trim() + ";DriverID=22;READONLY=true}"; Connection con = DriverManager.getConnection( database ,"",""); Statement s = con.createStatement(); s.execute("select * from details "); ResultSet rs = s.getResultSet(); if (rs != null) while ( rs.next() ) {
  • 101.
    101 hello[i]= rs.getString("name"); i++; hello[i]=rs.getString("date"); i++; } } catch (Exception e) { System.out.println("Error: " + e); } return hello; }} Index.jsp: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <form name="air" action="action.jsp" method="post"> From<input type="text" name="from" id="from"><br/> To<input type="text" name="to" id="to"><br/> <input type="submit" value="GetDtails"> </form> </body> </html> Action.jsp: <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <% String from1=request.getParameter("from"); String to1=request.getParameter("to"); %> <%-- start web service invocation --%><hr/> <% try {
  • 102.
    102 pack1.NewWebServiceService service =new pack1.NewWebServiceService(); pack1.NewWebService port = service.getNewWebServicePort(); // TODO initialize WS operation arguments here java.lang.String from = from1; java.lang.String to = to1; // TODO process result here java.util.List<java.lang.String> result = port.get(from, to); out.println("Result = "+result); } catch (Exception ex) { // TODO handle custom exceptions here }%> <%-- end web service invocation --%><hr/> </body> </html>
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
    111 CS6501- INTERNET PROGRAMMING UNITWISE UNIVERSITY QUESTIONS UNIT I –JAVA PROGRAMMING PART A 1. Which method is used to set a priority for a thread? List out its priorities. (JUNE 2007) 2. How does one import a single package? (DEC 2010) 3. Define Objects and classes in java. (DEC 2010) 4. What is the difference between the static and non-static variables? (DEC 2010) 5. List out the Type of Arrays? (May 2014) 6. In java what is the use of Interfaces? (DEC 2010) 7. Can an abstract class be final? Why? (DEC 2010) 8. What is the difference between the String and String Buffer classes? ? (DEC 2010) 9. What is an anonymous inner class? ? (DEC 2010) 10. What are three ways in which a thread can enter the waiting state? ? (DEC 2010) 11. What are the different states in thread? (DEC 2010) 12. What is meant by Inheritance Hierarchy? Give an Example. (DEC 2010,Nov 2013,May 2011) 13. Define objects and object variable. (May 2012) 14. Define class.(Nov 2013) 15. Define interface and write the syntax of the Interface? (May 2014, NOV 2013) 16. Define Static inner classes? (May 2012) 17. What are threads? (May 2012) 18. What do you mean by Threads in java? (Nov 2013) 19. What is multithreading? (Nov 2013 , Nov2014) 20. What is the use of Final keyword? (May 2014) 21. What is Thread Safe? (May 2014 ) 22. List access specifiers used in Java. ( Nov2014) 23. What is meant by java package. ( Nov2014) 24. What is meant by abstract class. ( Nov2014) 25. Write the properties of thread. ( Nov2014) PART B 1. Write java application program for generating 4 threads to do the following operations. (JUNE 2007) (i) getting n numbers (ii) printing even numbers (iii) printing odd numbers (iv) printing average of a numbers 2. What is class? How do you define a class in java? (DEC 2010) 3. Explain the following in Strings : (1) Concatenation (2) Substrings. (DEC 2010) 4. Explain any four methods available in string handling. (DEC 2010)
  • 112.
    112 5. What isa Package? How does a complier locate packages? (DEC 2010) 6. Explain arrays in java. (DEC 2010) 7. What is a Package? What are the benefits of using packages? Write down the steps in creating a package and using it in a java program with an example? (DEC 2010) 8. What is a thread? Explain its states and methods and Explain thread properties. (DEC 2010) 9. Explain how to create threads. Write a java program that prints numbers from 1 to 10 line by line after every 5 seconds. (DEC 2010) 10. Define package. Explain type of package with its importance.(8) (Nov 2011) 11. Explain any four string operations in java. With suitable example.(8) (Nov 2012) 12. State the properties of interfaces?(8) (Nov 2012) 13. Explain various state of thread (8) (Nov 2012) 14. Write in java program to iiustrate multithreaded programming(10) (May 2013,May 2014) 15. Explain how threads are created in java.(8) (May 2013) 16. Write about various threads states in java(8) (May 2013) 17. Explain the concept of inheritance with suitable example in java(8) (May 2013) 18. Explain Access specifier (8) (Nov 2013) 19. Explain packages with examples? (16) (May 2014) 20. Discuss about String(8) (May 2014) 21. Write in detail about the the following: (May 2014) i)Abstact Classes(8) ii) interfaces(8) UNIT-II: WEBSITES BASICS, HTML 5, CSS 3, WEB 2.0 PART-A 1. Give the syntax of a CSS rule. (Nov/Dec 2011) 2. Mention the need for cascading style sheets. (Apr/May 2011) 3. Give the core syntax of CSS. (May/June 2012) 4. Give example for inline style sheet? (May/June 2013) 5. What are the style sheets? (Nov/Dec 2013) 6. How external style sheet is useful in web page design. (May/June 2014) 7. List some HTML intrinsic attributes. (Apr/May 2011) PART-B: 1. Explain any eight CSS text properties. (8) (Nov/Dec 2011) 2. Explain in detail CSS border and CSS outline. (8) (Nov/Dec 2011) 3. Explain the features of cascading style sheets. (8) (Apr/May 2011) 4. Explain the CSS box model in detail. (8) (May/June 2012) 5. Write a CSS which adds bachground images and indentation? (8) (May/June 2013) 6. Explain external style sheet with an example? (8) (May/June 2013) 7. Discuss the various features of CSS with an example. (May/June 2014)
  • 113.
    113 UNIT-III: CLIENT SIDEAND SERVER SIDE PROGRAMMING PART-A 1. What is a JavaScript statement? Give an example. (Nov/Dec 2011) 2. Explain array creation in Java script with example. (Apr/May 2011) 3. List and Explain any two java script built in objects. (May/June 2012) 4. Write down the purpose of Java script debuggers. (Nov/Dec 2012) 5. Deñne DOM. (Nov/Dec 2012) 6. List the different methods defined in document and window object of java script? (May/June 2013) 7. Mention the advantages of java/java scipt. (Nov/Dec 2013) 8. Write a java script to print ―GOOD DAY‖ using IF-ELSE condition. (May/June 2014) 9. Write code to return the full URL of a document. (Nov/Dec 2011) 10. How is session tracking achieved by URL rewriting? (Nov/Dec 2011) 11. Explain in brief the interaction between a web server and a Servlet. (Apr/May 2011) 12. What is meant by intrinsic event handling? (May/June 2012) 13. Compare Client side vs. server side scripting. (Nov/Dec 2012) 14. State the Servlet life cycle. (Nov/Dec 2012) 15. List the different life cycle methods of java servlets ? (May/June 2013) 16. What is the purpose of cookies? (May/June 2013) 17. List any two keyboard events. (Nov/Dec 2013) 18. What are servlets? (Nov/Dec 2013) 19. Which parser is best in parsing large documents?why? (May/June 2014) 20. What is servlet container? Specify its functions. (May/June 2014) 21. Explain in brief about Java scriptlet. (Apr/May 2011) 22. Give the advantages of using JSP for server side programming. (May/June 2012) 23. Write down the syntax JDBC. (Nov/Dec 2012) 24. Write 2 basic differences between JSP and servlet? (May/June 2013) 25. What do you mean by cookies? (Nov/Dec 2012) PART-B: 1. Discuss JavaScript Array object in detail. (8) (Nov/Dec 2011) 2. Discuss about JavaScript debugging. (8) (Nov/Dec 2011) 3. List and explain in detail the various selector strings.(8)(Apr/May 2011) 4. State and explain the types of statements in Java script. (8) (Apr/May 2011) 5. Explain how functions can be written in Java script with an example.(8)(Apr/May 2011) 6. List and explain in detail the types of selector strings. (8) (May/June 2012) 7. Explain the way in which java script handles arrays with example. (8) (May/June 2012) 8. Explain how local and global functions can be written using java script. (8) (May/June 2012)
  • 114.
    114 9. Using RegExpinstance,wríte a Java Script function isValid( ) that accepts a string argument and returns true if the argument matches one of the following phone- number formats and returns false otherwise: (16) (Nov/Dec 2012) (044) 234-56'î8 (044) 234-5678 044/234-5678 044 234 0442345678. 10. Discuss about the nodes in a document tree with an example. (16)(Nov/Dec 2012) 11. Write java script to find factorial of a given number? (8) (May/June 2013) 12. Write Java script to find sum offirst N even number and display the result . Get the value of n from user? (8) (May/June 2013) 13. Develop a simple online shopping using java script.(Nov/Dec 2013) 14. Write a java script program to develop a arithmetic calculator. (Nov/Dec 2013) 15. Discuss the data types, functions and objects used in java script with an example. (May/June 2014) 16. Explain in detail DOM event handling. Also explain with an example of creating a context menu. [Note: A context menu is one that that is shown when the user right-clicks anywhere in the document]. (16) (Nov/Dec 2011) 3 17. What is a session? Explain how client state is maintained using session and also explain about session tracking and session management using an example. (16) (Nov/Dec 2011) 3 18. Explain about the document tree in detail. (8) (Apr/May 2011) 3 19. Explain DOM event handling in detail. (8) (Apr/May 2011) 3 20. 3. Explain the Servlet operation in detail with a sample Servlet program.(16) (Apr/May 2011) 3 21. Explain the document tree in detail.(8) (May/June 2012) 3 22. Explain DOM event handling in detail. (8) (May/June 2012) 3 23. Explain in detail with an example the dynamic content generation by a servlet. (8) (May/June 2012) 24. Explain how java servlets perform session handling.(8) (May/June 2012) 25. Write a servlet program for Blogging appîicatíon, One servlet for login, second one for Prevíewíng fadding entry to the blog, third one for viewing the blog that generates HTML document. (16) (Nov/Dec 2012) 26. Write an ASP code to display different image each time a user visite a page. (8) (Nov/Dec 2012) 27. Write a JSP to demonstrate the usage of page and include directives. (8) (Nov/Dec 2012) 28. Write a servlet to illustrate the principles of cookies and explain? (16) (May/June 2013) 29. Explain about architecture of servlet? (6) (May/June 2013) 30. Explain the purpose of the following DOM methods and properties? (10) (May/June 2013) i ) getElementById ii)createElement
  • 115.
    115 iii)createTextNode iv)appendChild v)parentNode 31. Explain theconcepts of servlets with an example program. (Nov/Dec 2013) 32. Explain about JSP actions with example. (Nov/Dec 2013) 33. Write the code for converting currencies to US dollars using java servlets. (May/June 2014) 34. Explain the following with an example (May/June 2014) i.cookies ii.URL rewriting 35. What is a JavaBeans component? How will you use the JSP language elements for accessing Beans in your JSP pages? (16) (Nov/Dec 2011) 36. State and explain the information in a JSP document in detail. (16)(Apr/May 2011) 37. Explain the use of Java beans classes in JSP with examples. (8) (May/June 2012) 38. Write a client server JSP program to find simple interest and display the result in the client? (10) (May/June 2013) 39. Write about the JSP tag Libraries?(6) (May/June 2013) 40. Describe the basic java bean classes and JSP tag libraries. (May/June 2014) 41. Explain the JDBC database access in detail. (8)(Apr/May 2011) 42. Write a java servlet to display net salary of employee, use JDBC connectivity to get a employee details from database? (16) (May/June 2013) UNIT-IV: PHP AND XML PART-A 1. How is XML parsing done with SAX? (Nov/Dec 2011) 2. What is the purpose of XSLT? (Nov/Dec 2011) 3. What is meant by a XML namespace? (Apr/May 2011) 4. What does XSLT mean? (May/June 2012) 5. State the role of XML parser. (Nov/Dec 2012) 6. Compare DOM and SAX in XML processing? (May/June 2013) 7. What is the use of XML namespace? (Nov/Dec 2013) 8. What are the XSLT elements? (Nov/Dec 2013) 9. When the namespace is called in XML?why? 10. What is XPATH? 11. What is the speciality in PHP? (Nov/Dec 2012) 12. What is the purpose of XML schema? (May/June 2013) PART-B: 1. Explain XPATH nodes in detail. (8) (Nov/Dec 2011) 2. Explain about the object that helps AJAX reload parts of a web page without reloading the whole page. (8) (Nov/Dec 2011) 3. List and explain the XML syntax rules in detail. (8) (Apr/May 2011) 4. Explain how a XML document can be displayed on a browser. (8) (Apr/May 2011)
  • 116.
    116 5. Explain therole XML name spaces with examples. (8) (May/June 2012) 6. Explain the features of XML path language. (8) (May/June 2012) 7. Explain the model view controller architecture pattern in detail.(8) (May/June 2012) 13. Explain on how template based transformation made in XML. (8) (Nov/Dec 2012) 14. Create a XML document for students mark list preparation and a DTD for that then valídate the XML document. (16) (Nov/Dec 2012) 15. Write XSLT code to display employee details in a table form which is stored in XML?(16) (May/June 2013) 16. What is DTD? Explain it with example. (Nov/Dec 2013) 17. Explain how XSLT transforms a document from one type to other. (May/June 2014) 18. Explain in detail the XML schema, built in and user defined data type in detail. (16)(Apr/May 2011) 19. Explain the role of XML schema in building web services in detail. (16) (May/June 2012) UNIT-V: INTRODUCTION TO AJAX AND WEB SERVICES PART-A 1. What is meant by WSDL? (Apr/May 2011) 2. List some examples of web services. (May/June 2012) 3. State the use of WSDL. (May/June 2012) 4. Define the need for SOAP? (May/June 2013) 5. What is the use of web services? (Nov/Dec 2013) 6. What is WSDL? (Nov/Dec 2013) PART-B 1. Describe the significance and working of WSDL with an example. (16) (Nov/Dec 2011) 2. Describe the major elements of SOAP. (16) (Nov/Dec 2011) 3. Explain the SOAP elements in detail. (8) (Apr/May 2011) 4. Explain the creation of a java web service in detail with examples. (16) (May/June 2012) 5. Illustrate the principles of WSDL , XML and SOAP and their interaction between them in web service applications?(16) (May/June 2013) 6. Explain web service architecture. (Nov/Dec 2013) 7. Write a program for any two web services. (Nov/Dec 2013) 8. Explain the WSDL structure and its elements. (May/June 2014)