Home Education and learning Web hosting and design Small Business
education and learning Interview Questions
1) What is final in Java ?
1) Final means: it cannot be changed. Final classes may not be subclassed. Final methods may not be overridden.

2) What is the difference between an Interface and an Abstract class?
2) In Abstract class there is at least one instance method that is declared abstract which will be implemented by the subclasses. An abstract class can have instance methods that implement a default behavior.
But Interface can only declare constants and instance methods. In interface you cannot implement default behavior.
An abstract class may contain code in method bodies, which is not allowed in an interface.

3) What is difference between the method sleep() and method wait()
3) The method sleep puts the thread aside for the exact time as specified in method sleep. The method wait puts the thread aside for the the time as specified in method wait, but it could stop waiting if it receives the notify() or notifyAll() call.

4) What is the purpose of garbage collection in Java, and when is it used?
4) The purpose of garbage collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used.

5) Describe synchronization in respect to multithreading.
5) With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchonization, it is possible for one thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to significant errors.

6) Explain different way of using thread?
6) The thread could be implemented in following way:
1. by using runnable interface
2. by inheriting from the Thread class.
The former is more advantageous, cause when you are going for multiple inheritance..the only interface can help.

7) What is difference between pass by reference and passby value?
7) Pass By Reference means the passing the address itself rather than passing the value. Passby Value means passing a copy of the value to be passed.

8) What is difference between HashMap and Map ?
8) Map is Interface
Hashmap is class that implements Map.

9) What is difference between HashMap and HashTable?
9) The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and it permits nulls. (HashMap allows null values as key and value whereas Hashtable doesnt allow). HashMap does not guarantee that the order of the map will remain constant over time. HashMap is non synchronized and Hashtable is synchronized.

10) What is difference between Vector and ArrayList ?
10) Vector is synchronized whereas arraylist is not not synchronized.

11) What is difference between Swing and Awt?
11) AWT are heavy-weight componenets. Swings are light-weight components. Hence swing works faster than AWT. The look and feel of swing is platform independent.

12) What is the difference between a constructor and a method ?
12) A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself. Constructor has no return type. Constructor is invoked using the new operator. A method is an ordinary member function of a class. Method has its own name, a return type (which may be void), and is invoked using the dot(.) operator.

13) What is the difference between a queue and a stack ?
13) Stack works on last-in-first-out rule (LIFO), whereas queues works on First-in-first-out (FIFO) rule.

14) What do you know about an Iterators ?
14) Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained. It is not advisable to modify the collection itself while traversing an Iterator.

15) State the significance of public, private, protected, default modifiers both singly and in combination and state the effect of package relationships on declared items qualified by these modifiers.
15) public : Public class is visible in other packages, field is visible everywhere (class must be public too)
private : Private variables or methods may be used only by an instance of the same class that declares the variable or method, A private feature may only be accessed by the class that owns the feature.
protected : Is available to all classes in the same package and also available to all subclasses of the class that owns the protected feature.This access is provided even to subclasses that reside in a different package from the class that owns the protected feature.
default :What you get by default ie, without any access modifier (ie, public private or protected). It means that it is visible to all within a particular package.

16) What is an abstract class?
16) Abstract class must be extended (i.e. subclassed). It serves as a template. A class that is abstract may not be instantiated (ie, you may not call its constructor), abstract class may contain static data. Any class with an abstract method is automatically abstract itself, and must be declared as such. A class may be declared abstract even if it has no abstract methods. This prevents it from being instantiated.

17) What is static in java?
17) Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object. A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

18) What is final?
18) A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

19) What if the main method is declared as private?
19) The program compiles properly but at runtime it will give "Main method not public." message.

20) What will happen if the static modifier is removed from the signature of the main method?
20) The java program compiles. But at runtime it will throws an error as : "NoSuchMethodError".

21) What if I write static public void instead of public static void?
21) Program compiles and runs properly.

22) What if you do not provide the String array as the argument to the method?
22) The program will compile, but it will throw a runtime error as : "NoSuchMethodError".

23) What is the first argument of the String array in main method?
23) The String array is empty. It does not have any element. This is unlike C/C++ where the first element by default is the program name.

24) If you do not provide any arguments on the command line, then the String array of Main method will be empty of null?
24) It is empty. But not null.

25) How can one prove that the array is not null but empty?
25) Print args.length. It will print 0. That means it is empty. But if it would have been null then it would have thrown a NullPointer Exception on attempting to print args.length.

26) What environment variables do you need to set on my machine in order to be able to run Java programs?
26) CLASSPATH and PATH are the two environment variables.

27) Can an application have multiple classes having main method?
27) A: Yes it is possible. While starting the application we mention the class name to be run. The JVM will look for the Main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

28) Can I have multiple main methods in the same class?
28) No the program fails to compile. The compiler says that the main method is already defined in the class.

29) Q: Do I need to import java.lang package any time? Why ?
29) No. java.lang package is loaded by default, internally by the JVM.

30) Can you import same package/class twice? Will the JVM load the package twice at runtime?
30) One can import the same package or same class multiple times. Neither compiler nor JVM complains about it. And the JVM will internally load the class only once no matter how many times you import the same class.

31) Q: What are Checked and UnChecked Exception?
31) A: A checked exception is some subclass of Exception (or Exception itself), excluding class RuntimeException and its subclasses. Making an exception checked forces client programmers to deal with the possibility that the exception will be thrown. eg, IOException thrown by java.io.FileInputStream's read() method Unchecked exceptions are RuntimeException and any of its subclasses. Class Error and its subclasses also are unchecked. With an unchecked exception, however, the compiler doesn't force client programmers either to catch the exception or declare it in a throws clause. In fact, client programmers may not even know that the exception could be thrown. eg, StringIndexOutOfBoundsException thrown by String's charAt() method Checked exceptions must be caught at compile time. Runtime exceptions do not need to be. Errors often cannot be.

32) Q: What is Overriding?
32) A: When a class defines a method using the same name, return type, and arguments as a method in its superclass, the method in the class overrides the method in the superclass. When the method is invoked for an object of the class, it is the new definition of the method that is called, and not the method definition from superclass. Methods may be overridden to be more public, not more private.

33) Q: What are different types of inner classes?
33) A: Nested top-level classes, Member classes, Local classes, Anonymous classes Nested top-level classes- If you declare a class within a class and specify the static modifier, the compiler treats the class just like any other top-level class. Any class outside the declaring class accesses the nested class with the declaring class name acting similarly to a package. eg, outer.inner. Top-level inner classes implicitly have access only to static variables.There can also be inner interfaces. All of these are of the nested top-level variety. Member classes - Member inner classes are just like other member methods and member variables and access to the member class is restricted, just like methods and variables. This means a public member class acts similarly to a nested top-level class. The primary difference between member classes and nested top-level classes is that member classes have access to the specific instance of the enclosing class. Local classes - Local classes are like local variables, specific to a block of code. Their visibility is only within the block of their declaration. In order for the class to be useful beyond the declaration block, it would need to implement a more publicly available interface.Because local classes are not members, the modifiers public, protected, private, and static are not usable. Anonymous classes - Anonymous inner classes extend local inner classes one level further. As anonymous classes have no name, you cannot provide a constructor.

34) Q: Are the imports checked for validity at compile time? e.g. will the code containing an import such as java.lang.ABCD compile?
34) A: Yes the imports are checked for the semantic validity at compile time. The code containing above line of import will not compile. It will throw an error saying,can not resolve symbol symbol : class ABCD location: package io import java.io.ABCD;

35) Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests.*?
35) A: No you will have to import the subpackages explicitly. Importing com.MyTest.* will import classes in the package MyTest only. It will not import any class in any of it's subpackage.

36) Q: What is the difference between declaring a variable and defining a variable?
36) A: In declaration we just mention the type of the variable and it's name. We do not initialize it. But defining means declaration + initialization. e.g String s; is just a declaration while String s = new String ("abcd"); Or String s = "abcd"; are both definitions.

37) Q: What is the default value of an object reference declared as an instance variable?
37) A: null unless we define it explicitly.

38) Q: Can a top level class be private or protected?
38) A: No. A top level class can not be private or protected. It can have either "public" or no modifier. If it does not have a modifier it is supposed to have a default access.If a top level class is declared as private the compiler will complain that the "modifier private is not allowed here". This means that a top level class can not be private. Same is the case with protected.

39) Q: What type of parameter passing does Java support?
39) A: In Java the arguments are always passed by value .

40) Q: Primitive data types are passed by reference or pass by value?
40) A: Primitive data types are passed by value.

41) Q: Objects are passed by value or by reference?
41) A: Java only supports pass by value. With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object .

42) Q: What is serialization?
42) A: Serialization is a mechanism by which you can save the state of an object by converting it to a byte stream.

43) Q: How do I serialize an object to a file?
43) A: The class whose instances are to be serialized must implement an interface: Serializable. Then pass the instance to the ObjectOutputStream which is connected to a fileoutputstream. This will save the object to a file.

44) Q: Which methods of Serializable interface should I implement?
44) A: The serializable interface is an empty interface, it does not contain any methods. So we do not implement any methods.

45) Q: How can I customize the seralization process? i.e. how can one have a control over the serialization process?
45) A: Yes it is possible to have control over serialization process. The class should implement Externalizable interface. This interface contains two methods namely readExternal and writeExternal. You should implement these methods and write the logic for customizing the serialization process.

46) Q: What is the common usage of serialization?
46) A: Whenever an object is to be sent over the network, objects need to be serialized. Moreover if the state of an object is to be saved, objects need to be serilazed.

47) Q: What is Externalizable interface?
47) A: Externalizable is an interface which contains two methods readExternal and writeExternal. These methods give you a control over the serialization mechanism. Thus if your class implements this interface, you can customize the serialization process by implementing these methods.

48) Q: What happens to the object references included in the object?
48) A: The serialization mechanism generates an object graph for serialization. Thus it determines whether the included object references are serializable or not. This is a recursive process. Thus when an object is serialized, all the included objects are also serialized alongwith the original obect.

49) Q: What one should take care of while serializing the object?
49) A: One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializableException.

50) Q: What happens to the static fields of a class during serialization? Are these fields serialized as a part of each serialized object?
50) A: Yes the static fields do get serialized. If the static field is an object then it must have implemented Serializable interface. The static fields are serialized as a part of every object. But the commonness of the static fields across all the instances is maintained even after serialization.

51) Q: How are Observer and Observable used?
51) A: Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

52) Q: What is synchronization and why is it important?
52) With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object's value. This often leads to significant errors.

53) Q: How does Java handle integer overflows and underflows?
53) A: It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

54) Q: Does garbage collection guarantee that a program will not run out of memory?
54) A: Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

55) Q: What is the difference between preemptive scheduling and time slicing?
55) A: Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.

56) Q: When a thread is created and started, what is its initial state?
56) A: A thread is in the ready state after it has been created and started.

57) Q: What is the purpose of finalization?
57) A: The purpose of finalization is to give an unreachable object the opportunity to perform any cleanup processing before the object is garbage collected.

58) Q: What is the Locale class?
58) A: The Locale class is used to tailor program output to the conventions of a particular geographic, political, or cultural region.

59) Q: What is the difference between a while statement and a do statement?
59) A: A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.

60) Q: What is the difference between static and non-static variables?
60) A: A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.

61) Q: How are this() and super() used with constructors?
61) A: this() is used to invoke a constructor of the same class. super() is used to invoke a superclass constructor.

62) Q: What are synchronized methods and synchronized statements?
62) A: Synchronized methods are methods that are used to control access to an object. A thread only executes a synchronized method after it has acquired the lock for the method's object or class. Synchronized statements are similar to synchronized methods. A synchronized statement can only be executed after a thread has acquired the lock for the object or class referenced in the synchronized statement.

63) Q: Does Java provide any construct to find out the size of an object?
63) A: No there is not sizeof operator in Java. So there is not direct way to determine the size of an object directly in Java.

64) Q: Does importing a package imports the subpackages as well? e.g. Does importing com.MyTest.* also import com.MyTest.UnitTests. ?
64) A: Read the system time just before the method is invoked and immediately after method returns. Take the time difference, which will give you the time taken by a method for execution. To put it in code... long start = System.currentTimeMillis (); method (); long end = System.currentTimeMillis (); System.out.println ("Time taken for execution is " + (end - start)); Remember that if the time taken for execution is too small, it might show that it is taking zero milliseconds for execution. Try it on a method which is big enough, in the sense the one which is doing considerable amout of processing.

65) Q: What are wrapper classes?
65) A: Java provides specialized classes corresponding to each of the primitive data types. These are called wrapper classes. They are e.g. Integer, Character, Double etc.

66) Q: Why do we need wrapper classes?
66) A: It is sometimes easier to deal with primitives as objects. Moreover most of the collection classes store objects and not primitive data types. And also the wrapper classes provide many utility methods also. Because of these resons we need wrapper classes. And since we create instances of these classes we can store them in any of the collection classes and pass them around as a collection. Also we can pass them around as method parameters where a method expects an object.

67) Q: What are checked exceptions?
67) A: Checked exception are those which the Java compiler forces you to catch. e.g. IOException are checked Exceptions.

68) Q: What are runtime exceptions?
68) A: Runtime exceptions are those exceptions that are thrown at runtime because of either wrong input data or because of wrong business logic etc. These are not checked by the compiler at compile time.

69) Q: What is the difference between error and an exception?
69) A: An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory error. These JVM errors and you can not repair them at runtime. While exceptions are conditions that occur because of bad input etc. e.g. FileNotFoundException will be thrown if the specified file does not exist. Or a NullPointerException will take place if you try using a null reference. In most of the cases it is possible to recover from an exception (probably by giving user a feedback for entering proper values etc.).

70) Q: How to create custom exceptions?
70) A: Your class should extend class Exception, or some more specific type thereof.

71) Q: If I want an object of my class to be thrown as an exception object, what should I do?
71) A: The class should extend from Exception class. Or you can extend your class from some more precise exception type also.

72) Q: If my class already extends from some other class what should I do if I want an instance of my class to be thrown as an exception object?
72) A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

73) Q: What happens to an unhandled exception?
73) A: One can not do anytihng in this scenarion. Because Java does not allow multiple inheritance and does not provide any exception interface as well.

74) Q: How does an exception permeate through the code?
74) A: An unhandled exception moves up the method stack in search of a matching When an exception is thrown from a code which is wrapped in a try block followed by one or more catch blocks, a search is made for matching catch block. If a matching type is found then that block will be invoked. If a matching type is not found then the exception moves up the method stack and reaches the caller method. Same procedure is repeated if the caller method is included in a try catch block. This process continues until a catch block handling the appropriate type of exception is found. If it does not find such a block then finally the program terminates.

75) Q: What are the different ways to handle exceptions?
75) A: There are two ways to handle exceptions, 1. By wrapping the desired code in a try block followed by a catch block to catch the exceptions. and 2. List the desired exceptions in the throws clause of the method and let the caller of the method hadle those exceptions.

76) Q: Q: What is the basic difference between the 2 approaches to exception handling...1> try catch block and 2> specifying the candidate exceptions in the throws clause? When should you use which approach?
76) A: In the first approach as a programmer of the method, you urself are dealing with the exception. This is fine if you are in a best position to decide should be done in case of an exception. Whereas if it is not the responsibility of the method to deal with it's own exceptions, then do not use this approach. In this case use the second approach. In the second approach we are forcing the caller of the method to catch the exceptions, that the method is likely to throw. This is often the approach library creators use. They list the exception in the throws clause and we must catch them. You will find the same approach throughout the java libraries we use.

77) Q: Is it necessary that each try block must be followed by a catch block?
77) A: It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.

78) Q: If I write return at the end of the try block, will the finally block still execute?
78) A: Yes even if you write return as the last statement in the try block and no exception occurs, the finally block will execute. The finally block will execute and then the control return.

79) Q: If I write System.exit (0); at the end of the try block, will the finally block still execute?
79) A: No in this case the finally block will not execute because when you say System.exit (0); the control immediately goes out of the program, and thus finally never executes. A: JMS is an acronym used for Java Messaging Service. It is Java's answer to creating software using asynchronous messaging. It is one of the official specifications of the J2EE technologies and is a key technology.

80) Q: How JMS is different from RPC?
80) A: In RPC the method invoker waits for the method to finish execution and return the control back to the invoker. Thus it is completely synchronous in nature. While in JMS the message sender just sends the message to the destination and continues it's own processing. The sender does not wait for the receiver to respond. This is asynchronous behavior.

81) Q: What are the advantages of JMS?
81) A: JMS is asynchronous in nature. Thus not all the pieces need to be up all the time for the application to function as a whole. Even if the receiver is down the MOM will store the messages on it's behalf and will send them once it comes back up. Thus at least a part of application can still function as there is no blocking.

82) Tell about any major JMS products available in the market?
82) IBM's MQ Series is one of the most popular product used as Message Oriented Middleware. Some of the other products are SonicMQ, iBus etc. Weblogic application server also comes with built in support for JMS messaging.

83) What are the different types of messages available in the JMS API ?
83) Message, TextMessage, BytesMessage, StreamMessage, ObjectMessage, MapMessage are the different messages available in the JMS API.

84) What are the different messaging paradigms JMS supports?
84) Publish and Subscribe i.e. pub/suc and Point to Point i.e. p2p.

85) What is the difference between topic and queue?
85) A topic is typically used for one to many messaging i.e. it supports publish subscribe model of messaging. While queue is used for one-to-one messaging i.e. it supports Point to Point Messaging.

86) What is the role of JMS in enterprise solution development?
86) A: JMS is typically used in the following scenarios 1. Enterprise Application Integration: - Where a legacy application is integrated with a new application via messaging. 2. B2B or Business to Business: - Businesses can interact with each other via messaging because JMS allows organizations to cooperate without tightly coupling their business systems. 3. Geographically dispersed units: - JMS can ensure safe exchange of data amongst the geographically dispersed units of an organization. 4. One to many applications: - The applications that have to push data in packet to huge number of clients in a one-to-many fashion are good candidates for the use JMS. Typical such applications are Auction Sites, Stock Quote Services etc.

87) Q: What is the use of Message object?
87) A: Message is a light weight message having only header and properties and no payload. Thus if the received are to be notified abt an event, and no data needs to be exchanged then using Message can be very efficient.

88) Q: What is the basic difference between Publish Subscribe model and P2P model?
88) A: Publish Subscribe model is typically used in one-to-many situation. It is unreliable but very fast. P2P model is used in one-to-one situation. It is highly reliable.

89) Q: What is the use of BytesMessage?
89) A: BytesMessage contains an array of primitive bytes in it's payload. Thus it can be used for transfer of data between two applications in their native format which may not be compatible with other Message types. It is also useful where JMS is used purely as a transport between two systems and the message payload is opaque to the JMS client. Whenever you store any primitive type, it is converted into it's byte representation and then stored in the payload. There is no boundary line between the different data types stored. Thus you can even read a long as short. This would result in erroneous data and hence it is advisable that the payload be read in the same order and using the same type in which it was created by the sender.

90) What is the use of StreamMessage?
90) A: StreamMessage carries a stream of Java primitive types as it's payload. It contains some conveient methods for reading the data stored in the payload. However StreamMessage prevents reading a long value as short, something that is allwed in case of BytesMessage. This is so because the StreamMessage also writes the type information alonwgith the value of the primitive type and enforces a set of strict conversion rules which actually prevents reading of one primitive type as another.

91) Q: What is the use of TextMessage?
91) A: TextMessage contains instance of java.lang.String as it's payload. Thus it is very useful for exchanging textual data. It can also be used for exchanging complex character data such as an XML document.

92) Q: What is the use of ObjectMessage?
92) ObjectMessage contains a Serializable java object as it's payload. Thus it allows exchange of Java objects between applications. This in itself mandates that both the applications be Java applications. The consumer of the message must typecast the object received to it's appropriate type. Thus the consumer should before hand know the actual type of the object sent by the sender. Wrong type casting would result in ClassCastException. Moreover the class definition of the object set in the payload should be available on both the machine, the sender as well as the consumer. If the class definition is not available in the consumer machine, an attempt to type cast would result in ClassNotFoundException. Some of the MOMs might support dynamic loading of the desired class over the network, but the JMS specification does not mandate this behavior and would be a value added service if provided by your vendor. And relying on any such vendor specific functionality would hamper the portability of your application. Most of the time the class need to be put in the classpath of both, the sender and the consumer, manually by the developer.

93) Q: What is the use of MapMessage?
93) A: A MapMessage carries name-value pair as it's payload. Thus it's payload is similar to the java.util.Properties object of Java. The values can be Java primitives or their wrappers.

94) Q: What is the difference between BytesMessage and StreamMessage??
94) A: BytesMessage stores the primitive data types by converting them to their byte representation. Thus the message is one contiguous stream of bytes. While the StreamMessage maintains a boundary between the different data types stored because it also stores the type information along with the value of the primitive being stored. BytesMessage allows data to be read using any type. Thus even if your payload contains a long value, you can invoke a method to read a short and it will return you something. It will not give you a semantically correct data but the call will succeed in reading the first two bytes of data. This is strictly prohibited in the StreamMessage. It maintains the type information of the data being stored and enforces strict conversion rules on the data being read.

95) Q: What is SQL?
95) A: SQL stands for 'Structured Query Language'.

96) Q: What is SELECT statement?
96) A: The SELECT statement lets you select a set of values from a table in a database. The values selected from the database table would depend on the various conditions that are specified in the SQL query.

97) Q: How can you compare a part of the name rather than the entire name?
97) A: SELECT * FROM people WHERE empname LIKE '%ab%' Would return a recordset with records consisting empname the sequence 'ab' in empname .

98) Q: What is the INSERT statement?
98) A: The INSERT statement lets you insert information into a database.

99) How do you delete a record from a database?
99) Use the DELETE statement to remove records or any particular column values from a database.

100) How could I get distinct entries from a table?
100) The SELECT statement in conjunction with DISTINCT lets you select a set of distinct values from a table in a database. The values selected from the database table would of course depend on the various conditions that are specified in the SQL query. Example SELECT DISTINCT empname FROM emptable

101) Q: How to get the results of a Query sorted in any order?
101) A: You can sort the results and return the sorted results to your program by using ORDER BY keyword thus saving you the pain of carrying out the sorting yourself. The ORDER BY keyword is used for sorting. SELECT empname, age, city FROM emptable ORDER BY empname

102) Q: How can I find the total number of records in a table?
102) You could use the COUNT keyword , example SELECT COUNT(*) FROM emp WHERE age>40

103) What is GROUP BY?
103) A: The GROUP BY keywords have been added to SQL because aggregate functions (like SUM) return the aggregate of all column values every time they are called. Without the GROUP BY functionality, finding the sum for each individual group of column values was not possible. TOP

104) What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table.
104) Dropping : (Table structure + Data are deleted), Invalidates the dependent objects ,Drops the indexes Truncating: (Data alone deleted), Performs an automatic commit, Faster than delete Delete : (Data alone deleted), Doesn't perform automatic commit

105) Q: What are the Large object types suported by Oracle?
105) A: Blob and Clob.

106) Q: Difference between a "where" clause and a "having" clause.
106) A: Having clause is used only with group functions whereas Where is not used with.

107) Q: What's the difference between a primary key and a unique key?
107) A: Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

108) Q: What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors?
108) A: Cursors allow row-by-row prcessing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one rowundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Furthere, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors.

109) Q: What are triggers? How can a trigger be invoked on demand?
109) A: Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. You cannot invoke triggers on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster.

110) Q: What is a join and explain different types of joins.
110) A: Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS.

111) Q: What is a self join?
111) A: Self join is just like any other join, except that two instances of the same table will be joined in the query.

112) 1. What is the difference between SAX parser and DOM parser?
112) DOM: - creates an internal representation of an XML document - Nice for smaller XML files, but because of the whole XML file - representation is in memory, it is possible not useful for very large documents - good for representation of an XML document. SAX: - Event driven, so reacting when it finds certain elements in the XML code (e.g. tags, properties, ? ) - goes from top to bottom, and if it encounters e.g. begintag, it fires an event. e.g. end tag, it fires and event. e.g. begin of file, it fires an event DOM parser - reads the whole XML document and returns a DOM tree representation of xml document. It provides a convenient way for reading, analyzing and manipulating XML files. It is not well suited for large xml files, as it always reads the whole file before processing. SAX parser - works incrementally and generate events that are passed to the application. It does not generate data representation of xml content so some programming is required. However, it provides stream processing and partial processing which cannot be done alone by DOM parser. 2. What is Xpath? XPath is used to navigate through elements and attributes in an XML document.

113) 3. What is XSL?
113) XSLT - a language for transforming XML documents XSLT is used to transform an XML document into another XML document, or another type of document that is recognized by a browser, like HTML and XHTML. Normally XSLT does this by transforming each XML element into an (X)HTML element. XPath - a language for navigating in XML documents XSL-FO - a language for formatting XML documents

114) What is DTD
114) 4. A DTD is: The XML Document Type Declaration contains or points to markup declarations that provide a grammar for a class of documents. This grammar is known as a document type definition or DTD. The DTD can point to an external subset containing markup declarations, or can contain the markup declarations directly in an internal subset, or can even do both. 4. A Schema is: XML Schemas express shared vocabularies and allow machines to carry out rules made by people. They provide a means for defining the structure, content and semantics of XML documents. An XML Schema: defines elements that can appear in a document defines attributes that can appear in a document defines which elements are child elements defines the order of child elements defines the number of child elements defines whether an element is empty or can include text defines data types for elements and attributes defines default and fixed values for elements and attributes In summary, schemas are a richer and more powerful of describing information than what is possible with DTDs. 5. How Schemas Differ from DTDs The first, and probably most significant, difference between XML Schemas and XML DTDs is that XML Schemas use XML document syntax. While transforming the syntax to XML doesn't automatically improve the quality of the description, it does make those descriptions far more extensible than they were in the original DTD syntax. Declarations can have richer and more complex internal structures than declarations in DTDs, and schema designers can take advantage of XML's containment hierarchies to add extra information where appropriate even sophisticated information like documentation. There are a few other benefits from this approach. XML Schemas can be stored along with other XML documents in XML-oriented data stores, referenced, and even styled, using tools like XLink, XPointer, and XSL. The largest addition XML Schemas provide to the functionality of the descriptions is a vastly improved data typing system. XML Schemas provide data-oriented data types in addition to the more document-oriented data types XML 1.0 DTDs support, making XML more suitable for data interchange applications. Built-in datatypes include strings, booleans, and time values, and the XML Schemas draft provides a mechanism for generating additional data types. Using that system, the draft provides support for all of the XML 1.0 data types (NMTOKENS, IDREFS, etc.) as well as data-specific types like decimal, integer, date, and time. Using XML Schemas, developers can build their own libraries of easily interchanged data types and use them inside schemas or across multiple schemas. The current draft of XML Schemas also uses a very different style for declaring elements and attributes to DTDs. In addition to declaring elements and attributes individually, developers can create models archetypes that can be applied to multiple elements and refined if necessary. This provides a lot of the functionality SOX had developed to support object-oriented concepts like inheritance. Archetype development and refinement will probably become the mark of the high-end schema developer, much as the effective use of parameter entities was the mark of the high-end DTD developer. Archetypes should be easier to model and use consistently, however. XML Schemas also support namespaces, a key feature of the W3C's vision for the future of XML. While it probably wouldn't be impossible to integrate DTDs and namespaces, the W3C has decided to move on, supporting namespaces in its newer developments and not retrofitting XML 1.0. In many cases, provided that namespace-prefixes don't change or simply aren't used, DTD's can work just fine with namespaces, and should be able to interoperate with namespaces and schema processing that relies on namespaces. There will be a few cases, however, where namespaces may force developers to use the newer schemas rather than the older DTDs.

115) 6. How do you parse/validate the XML document?
115) The only way to validate an XML file is to parse the XML document using the DOM parser or the SAX parser.

116) 7. What is XML Namespace?
116) The XML namespaces recommendation defines a way to distinguish between duplicate element type and attribute names. Such duplication might occur, for example, in an XSLT stylesheet or in a document that contains element types and attributes from two different DTDs. 8. An XML namespace is a collection of element type and attribute names. The namespace is identified by a unique name, which is a URI. Thus, any element type or attribute name in an XML namespace can be uniquely identified by a two-part name: the name of its XML namespace and its local name. This two-part naming system is the only thing defined by the XML namespaces recommendation. XML namespaces are declared with an xmlns attribute, which can associate a prefix with the namespace. The declaration is in scope for the element containing the attribute and all its descendants. For example: abcd If an XML namespace declaration contains a prefix, you refer to element type and attribute names in that namespace with the prefix. For example: abcd If an XML namespace declaration does not contain a prefix, the namespace is the default XML namespace and you refer to element type names in that namespace without a prefix. For example: abcd

117) Explain what XML namespaces are not?
117) They aren't a cure of cancer, they aren't a way to win the lottery, and they aren't a direct cause of world peace. They also aren't very difficult to understand or use. Two things that XML namespaces are not have caused a lot of confusion, so ww will mention them here: XML namespaces are not a technology for joining XML documents that use different DTDs. Although they might be used in such a technology, they don't provide it themselves. The URIs used as XML namespace names are not guaranteed to point to schemas, information about the namespace, or anything else they're just identifiers. URIs were used simply because they're a well-known system for creating unique identifiers. Don't even think about trying to resolve these URIs. XPath is a language for addressing parts of an XML document, designed to be used by both XSLT and XPointer.

118) How would you generate PDF from XML
118) Today, the most common application of XSL-FO is to produce Adobe PDF documents from the source XML files. Here is the two step process that is used to turn XML into PDF: Step 1. XML to XSL-FO using XSLT: The first step is to transform XML into XSL-FO format document. XSL-FO, like XSLT, makes use of XML syntax. The obvious choice here is to use XSLT to transform XML into XSL-FO. However, if you want, you can use some other method, such as DOM- or SAX-based processing the XML document, and generating XSL-FO document. In this article, we will use XSLT to transform XML into XSL-FO. XSLT transformation engine, such as MSXML, Xalan, Saxon, XT, etc. can be used to apply the XSLT stylesheet on the XML document. XSL-FO document describes the details of the presentation, such as physical size of the page, pagination details, margins, fonts, font sizes, colors, and so on. These characteristics are expressed using XSL formatting objects (for example: fo:page-sequence, fo:block, fo:footnote, fo:float, fo:region-body, and so on) and formatting properties (for example: background-attachment, background-color, font-family, text-depth, and so on). If you are know CSS (Cascading Style Sheets), the XSL formatting properties should sound familiar, however it is important to realize that XSL-FO provides a more sophisticated layout model than the CSS, and that XSL-FO is specifically designed to be used for generating fine-grained presentational layout files.

Step 2. Processing XSL-FO using Formatting Engine (or Formatter): Once you have the XSL-FO document, XSL rendering engine, such as FOP or XSL Formatter (see XSL-FO Tools section below) can be used to convert XSL-FO elements into a PDF, PostScript, RTF or any other such print format.

XSL-FO is not meant to be hand-coded. Generally, XSLT stylesheet will be written to transform XML into XSL-FO. The rendering engine is then used to convert XSL-FO into the required print documents. External resources (such as images and fonts) can be referred in the XSL-FO document. SVG elements can be used inside XSL-FO document to produce vector graphics (such as charts or maps).


119) Describe the differences between XML and HTML.
119) It's amazing how many developers claim to be proficient programming with XML, yet do not understand the basic differences between XML and HTML. Anyone with a fundamental grasp of XML should be able describe some of the main differences outlined in the table below. Differences Between XML and HTML Table 1.

XML: User definable tags
HTML: Defined set of tags designed for web display

XML: Content driven HTML: Format driven

XML: End tags required for well formed documents HTML: End tags not required

XML: Quotes required around attributes values HTML: Quotes not required XML: Slash required in empty tags HTML: Slash not required


120) Describe the role that XSL can play when dynamically generating HTML pages from a relational database.
120) Even if candidates have never participated in a project involving this type of architecture, they should recognize it as one of the common uses of XML. Querying a database and then formatting the result set so that it can be validated as an XML document allows developers to translate the data into an HTML table using XSLT rules. Consequently, the format of the resulting HTML table can be modified without changing the database query or application code since the document rendering logic is isolated to the XSLT rules. Give a few examples of types of applications that can benefit from using XML. There are literally thousands of applications that can benefit from XML technologies. The point of this question is not to have the candidate rattle off a laundry list of projects that they have worked on, but, rather, to allow the candidate to explain the rationale for choosing XML by citing a few real world examples. For instance, one appropriate answer is that XML allows content management systems to store documents independently of their format, which thereby reduces data redundancy. Another answer relates to B2B exchanges or supply chain management systems. In these instances, XML provides a mechanism for multiple companies to exchange data according to an agreed upon set of rules. A third common response involves wireless applications that require WML to render data on hand held devices.

121) What is DOM and how does it relate to XML?
121) The Document Object Model (DOM) is an interface specification maintained by the W3C DOM Workgroup that defines an application independent mechanism to access, parse, or update XML data. In simple terms it is a hierarchical model that allows developers to manipulate XML documents easily Any developer that has worked extensively with XML should be able to discuss the concept and use of DOM objects freely. Additionally, it is not unreasonable to expect advanced candidates to thoroughly understand its internal workings and be able to explain how DOM differs from an event-based interface like SAX.

122) What is SOAP and how does it relate to XML?
122) The Simple Object Access Protocol (SOAP) uses XML to define a protocol for the exchange of information in distributed computing environments. SOAP consists of three components: an envelope, a set of encoding rules, and a convention for representing remote procedure calls. Unless experience with SOAP is a direct requirement for the open position, knowing the specifics of the protocol, or how it can be used in conjunction with HTTP, is not as important as identifying it as a natural application of XML.

123) Can you walk us through the steps necessary to parse XML documents?
123) Superficially, this is a fairly basic question. However, the point is not to determine whether candidates understand the concept of a parser but rather have them walk through the process of parsing XML documents step-by-step. Determining whether a non-validating or validating parser is needed, choosing the appropriate parser, and handling errors are all important aspects to this process that should be included in the candidate's response. Give some examples of XML DTDs or schemas that you have worked with. Although XML does not require data to be validated against a DTD, many of the benefits of using the technology are derived from being able to validate XML documents against business or technical architecture rules. Polling for the list of DTDs that developers have worked with provides insight to their general exposure to the technology. The ideal candidate will have knowledge of several of the commonly used DTDs such as FpML, DocBook, HRML, and RDF, as well as experience designing a custom DTD for a particular project where no standard existed. Using XSLT, how would you extract a specific attribute from an element in an XML document? Successful candidates should recognize this as one of the most basic applications of XSLT. If they are not able to construct a reply similar to the example below, they should at least be able to identify the components necessary for this operation: xsl:template to match the appropriate XML element, xsl:value-of to select the attribute value, and the optional xsl:apply-templates to continue processing the document. Extract Attributes from XML Data Example 1. Attribute Value:

124) When constructing an XML DTD, how do you create an external entity reference in an attribute value?
124) Every interview session should have at least one trick question. Although possible when using SGML, XML DTDs don't support defining external entity references in attribute values. It's more important for the candidate to respond to this question in a logical way than than the candidate know the somewhat obscure answer.

125) How would you build a search engine for large volumes of XML data?
125) The way candidates answer this question may provide insight into their view of XML data. For those who view XML primarily as a way to denote structure for text files, a common answer is to build a full-text search and handle the data similarly to the way Internet portals handle HTML pages. Others consider XML as a standard way of transferring structured data between disparate systems. These candidates often describe some scheme of importing XML into a relational or object database and relying on the database's engine for searching. Lastly, candidates that have worked with vendors specializing in this area often say that the best way the handle this situation is to use a third party software package optimized for XML data. Obviously, some important areas of XML technologies were not included in this list -- namespaces, XPointer, XLink, and so on -- and should be added to the interviewer's set of questions if applicable to the particular position that the candidate is applying for. However, these questions in conjunction with others to assess soft skills (communication skills, ability to work on teams, leadership ability, etc.) will help determine how well candidates understand the fundamental principles of XML. XML stands for EXtensible Markup Language
XML is a markup language much like HTML
XML was designed to describe data
XML tags are not predefined. You must define your own tags XML uses a Document Type Definition (DTD) or an XML Schema to describe the data XML with a DTD or XML Schema is designed to be self-descriptive XML is a W3C Recommendation

XML is a cross-platform, software and hardware independent tool for transmitting information.


126) Q: What is a output comment?
126) A: A comment that is sent to the client in the viewable page source.The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser. JSP Syntax Example 1 Displays in the page source:

127) What is a Hidden Comment?
127) A comments that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or "comment out" part of your JSP page. You can use any characters in the body of the comment except the closing --%> combination. If you need to use --%> in your comment, you can escape it by typing --%\>. JSP Syntax <%-- comment --%> Examples <%@ page language="java" %> A Hidden Comment <%-- This comment will not be visible to the colent in the page source --%>

128) What is a Expression?
128) A: An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within text in a JSP file. Like <%= someexpression %> <%= (new java.util.Date()).toLocaleString() %> You cannot use a semicolon to end an expression

129) What is a Declaration?
129) A declaration declares one or more variables or methods for use later in the JSP source file. A declaration must contain at least one complete declarative statement. You can declare any number of variables or methods within one declaration tag, as long as they are separated by semicolons. The declaration must be valid in the scripting language used in the JSP file. <%! somedeclarations %> <%! int i = 0; %> <%! int a, b, c; %>

130) Q: What is a Scriptlet?
130) A: A scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.Within scriptlet tags, you can 1.Declare variables or methods to use later in the file (see also Declaration). 2.Write expressions valid in the page scripting language (see also Expression). 3.Use any of the JSP implicit objects or any object declared with a tag. You must write plain text, HTML-encoded text, or other JSP tags outside the scriptlet. Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

131) What are implicit objects? List them?
131) A: Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet. The implicit objects re listed below request
response
pageContext
session
application
out
config
page
exception

132) What is the difference between forward and sendRedirect?
132) A: When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completly with in the web container. When a sendRedirtect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completly new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

133) Q: What are the different scope valiues for the ?
133) A: The different scope values for are 1. page
2. request
3. session
4. application

134) Q: Explain the life-cycle mehtods in JSP?
134) A: THe generated servlet class for a JSP page implements the HttpJspPage interface of the javax.servlet.jsp package. Hte HttpJspPage interface extends the JspPage interface which inturn extends the Servlet interface of the javax.servlet package. the generated servlet class thus implements all the methods of the these three interfaces. The JspPage interface declares only two mehtods - jspInit() and jspDestroy() that must be implemented by all JSP pages regardless of the client-server protocol. However the JSP specification has provided the HttpJspPage interfaec specifically for the JSp pages serving HTTP requests. This interface declares one method _jspService(). The jspInit()- The container calls the jspInit() to initialize te servlet instance.It is called before any other method, and is called only once for a servlet instance. The _jspservice()- The container calls the _jspservice() for each request, passing it the request and the response objects. The jspDestroy()- The container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.

135) How do I prevent the output of my JSP or Servlet pages from being cached by the browser?
135) A: You will need to set the appropriate HTTP header attributes to prevent the dynamic content output by the JSP page from being cached by the browser. Just execute the following scriptlet at the beginning of your JSP pages to prevent them from being cached at the browser. You need both the statements to take care of some of the older browser versions. <% response.setHeader("Cache-Control","no-store"); //HTTP 1.1 response.setHeader("Pragma\","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server %>

136) Q: How does JSP handle run-time exceptions?
136) You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

137) Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
137) A: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .

138) Q: How do I use a scriptlet to initialize a newly instantiated bean?
138) A: A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the today property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. <%-- scriptlets calling bean setter methods go here --%>

139) Q: How can I prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
139) A: You could make a simple wrapper function, like <%! String blanknull(String s) { return (s == null) ? \"\" : s; } %> then use it inside your JSP form, like

140) Q: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
140) A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

141) Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
141) A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie. Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. hello1.jsp <%@ page session=\"true\" %> <% Integer num = new Integer(100); session.putValue("num",num); String url =response.encodeURL("hello2.jsp"); %> <a href="<%=url%>"> hello2.jsp </a> hello2.jsp <%@ page session="true" %> <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is " + i.intValue());

142) Q: What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?
142) A: Variable declared inside declaration part is treated as a global variable.that means after convertion jsp file into servlet that variable will be in outside of service method or it will be declared as instance variable.And the scope is available to complete jsp and to complete in the converted servlet class.where as if u declare a variable inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

143) Q: How does JSP handle run-time exceptions?
143) A: You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example: <%@ page errorPage=\"error.jsp\" %> redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing. Within error.jsp, if you indicate that it is an error-processing page, via the directive: <%@ page isErrorPage=\"true\" %> Throwable object describing the exception may be accessed within the error page via the exception implicit object. Note: You must always use a relative URL as the value for the errorPage attribute.

144) Q: How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
144) A: You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page. With this, instead of a single instance of the servlet generated for your JSP page loaded in memory, you will have N instances of the servlet loaded and initialized, with the service method of each instance effectively synchronized. You can typically control the number of instances (N) that are instantiated for all servlets implementing SingleThreadModel through the admin screen for your JSP engine. More importantly, avoid using the tag for variables. If you do use this tag, then you should set isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access those variables, causing a nasty race condition. SingleThreadModel is not recommended for normal use. There are many pitfalls, including the example above of not being able to use <%! %>. You should try really hard to make them thread-safe the old fashioned way: by making them thread-safe .

145) Q: How do I use a scriptlet to initialize a newly instantiated bean?
145) A: A jsp:useBean action may optionally have a body. If the body is specified, its contents will be automatically invoked when the specified bean is instantiated. Typically, the body will contain scriptlets or jsp:setProperty tags to initialize the newly instantiated bean, although you are not restricted to using those alone. The following example shows the "today" property of the Foo bean initialized to the current date when it is instantiated. Note that here, we make use of a JSP expression within the jsp:setProperty action. <%-- scriptlets calling bean setter methods go here --%>

146) How can you prevent the word "null" from appearing in my HTML input text fields when I populate them with a resultset that has null values?
146) A: You could make a simple wrapper function, like <%! String blanknull(String s) { return (s == null) ? \"\" : s; } %> then use it inside your JSP form, like

147) Q: What's a better approach for enabling thread-safe servlets and JSPs? SingleThreadModel Interface or Synchronization?
147) A: Although the SingleThreadModel technique is easy to use, and works well for low volume sites, it does not scale well. If you anticipate your users to increase in the future, you may be better off implementing explicit synchronization for your shared data. The key however, is to effectively minimize the amount of code that is synchronzied so that you take maximum advantage of multithreading. Also, note that SingleThreadModel is pretty resource intensive from the server\'s perspective. The most serious issue however is when the number of concurrent requests exhaust the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free - which results in poor performance. Since the usage is non-deterministic, it may not help much even if you did add more memory and increased the size of the instance pool.

148) Q: How can I enable session tracking for JSP pages if the browser has disabled cookies?
148) A: We know that session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response. Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page. Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object. Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages. Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting. hello1.jsp <%@ page session=\"true\" %> <% Integer num = new Integer(100); session.putValue("num",num); String url =response.encodeURL("hello2.jsp"); %> <a href="<%=url%>"> hello2.jsp </a> hello2.jsp <%@ page session="true" %> <% Integer i= (Integer )session.getValue("num"); out.println("Num value in session is " + i.intValue()); %>


149) Q: Is there a way to execute a JSP from the comandline or from my own application?
149) A: There is a little tool called JSPExecutor that allows you to do just that. The developers (Hendrik Schreiber & Peter Rossbach ) aim was not to write a full blown servlet engine, but to provide means to use JSP for generating source code or reports. Therefore most HTTP-specific features (headers, sessions, etc) are not implemented, i.e. no reponseline or header is generated. Nevertheless you can use it to precompile JSP for your website.

150) What is JavaServer Pages technology?
150) JavaServer Pages (JSP) technology provides a simplified, fast way to create web pages that display dynamically-generated content. The JSP specification, developed through an industry-wide initiative led by Sun Microsystems, defines the interaction between the server and the JSP page, and describes the format and syntax of the page.

151) How does the JavaServer Pages technology work?
151) JSP pages use XML tags and scriptlets written in the Java programming language to encapsulate the logic that generates the content for the page. It passes any formatting (HTML or XML) tags directly back to the response page. In this way, JSP pages separate the page logic from its design and display. JSP technology is part of the Java technology family. JSP pages are compiled into servlets and may call JavaBeans components (beans) or Enterprise JavaBeans components (enterprise beans) to perform processing on the server. As such, JSP technology is a key component in a highly scalable architecture for web-based applications. JSP pages are not restricted to any specific platform or web server. The JSP specification represents a broad spectrum of industry input.

152) What is a servlet?
152) A servlet is a program written in the Java programming language that runs on the server, as opposed to the browser (applets). Detailed information can be found at http://java.sun.com/products/servlet. Why do I need JSP technology if I already have servlets? JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets. Where can I get the most current version of the JSP specification? The JavaServer Pages 2.0 specification is available for download from here.

153) How does the JSP specification relate to the Java 2 Platform, Enterprise Edition?
153) The JSP 2.0 specification is an important part of the Java 2 Platform, Enterprise Edition 1.4. Using JSP and Enterprise JavaBeans technologies together is a great way to implement distributed enterprise applications with web-based front ends.

154) Which web servers support JSP technology?
154) There are a number of JSP technology implementations for different web servers. The latest information on officially-announced support can be found at http://java.sun.com/products/jsp/industry.html. Is Sun providing a reference implementation for the JSP specification? The J2EE SDK is a reference implementation of the JavaTM 2 Platform, Enterprise Edition. Sun adapts and integrates the Tomcat JSP and Java Servlet implementation into the J2EE SDK. The J2EE SDK can be used as a development enviroment for applications prior to their deployment and distribution. Tomcat a free, open-source implementation of Java Servlet and JavaServer Pages technologies developed under the Jakarta project at the Apache Software Foundation, can be downloaded from http://jakarta.apache.org. Tomcat is available for commercial use under the ASF license from the Apache web site in both binary and source versions. An implementation of JSP technology is part of the J2EE SDK. How is JSP technology different from other products? JSP technology is the result of industry collaboration and is designed to be an open, industry-standard method supporting numerous servers, browsers and tools. JSP technology speeds development with reusable components and tags, instead of relying heavily on scripting within the page itself. All JSP implementations support a Java programming language-based scripting language, which provides inherent scalability and support for complex operations.

155) Where do I get more information on JSP technology?
155) The first place to check for information on JSP technology is http://java.sun.com/products/jsp/. This site includes numerous resources, as well as pointers to mailing lists and discussion groups for JSP technology-related topics.

156) What is a JSP page?
156) A JSP page is a page created by the web developer that includes JSP technology-specific and custom tags, in combination with other static (HTML or XML) tags. A JSP page has the extension .jsp or .jspx; this signals to the web server that the JSP engine will process elements on this page. Using the web.xml deployment descriptor, additional extensions can be associated with the JSP engine. The exact format of a JSP page is described in the JSP specification.

157) How do JSP pages work?
157) A JSP engine interprets tags, and generates the content required - for example, by calling a bean, accessing a database with the JDBC API or including a file. It then sends the results back in the form of an HTML (or XML) page to the browser. The logic that generates the content is encapsulated in tags and beans processed on the server. Does JSP technology require the use of other Java platform APIs? JSP pages are typically compiled into Java platform servlet classes. As a result, JSP pages require a Java virtual machine that supports the Java platform servlet specification.

158) How is a JSP page invoked and compiled?
158) Pages built using JSP technology are typically implemented using a translation phase that is performed once, the first time the page is called. The page is compiled into a Java Servlet class and remains in server memory, so subsequent calls to the page have very fast response times.

159) What is the syntax for JavaServer Pages technology?
159) The syntax card and reference can be viewed or downloaded from sun website.

160) Can you create XML pages using JSP technology?
160) Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output. See the white paper Developing XML Solutions with JavaServer Pages Technology (PDF) for details. Can I generate and manipulate JSP pages using XML tools? The JSP 2.0 specification describes a mapping between JSP pages and XML documents. The mapping enables the creation and manipulation of JSP pages using XML tools.

161) How do I use JavaBeans components (beans) from a JSP page?
161) The JSP specification includes standard tags for bean use and manipulation. The useBean tag creates an instance of a specific JavaBeans class. If the instance already exists, it is retrieved. Otherwise, it is created. The setProperty and getProperty tags let you manipulate properties of the given object. These tags are described in more detail in the JSP specification and tutorial Java Server Pages or JSP for short is Sun's solution for developing dynamic web sites. JSP provide excellent server side scripting support for creating database driven web applications. JSP enable the developers to directly insert java code into jsp file, this makes the development process very simple and its maintenance also becomes very easy. JSP pages are efficient, it loads into the web servers memory on receiving the request very first time and the subsequent calls are served within a very short period of time. In today's environment most web sites servers dynamic pages based on user request. Database is very convenient way to store the data of users and other things. JDBC provide excellent database connectivity in heterogeneous database environment. Using JSP and JDBC its very easy to develop database driven web application. Java is known for its characteristic of "write once, run anywhere." JSP pages are platform independent. Your port your .jsp pages to any platform. JPS pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests. javax.servlet.jsp package defines two classes: JSPPage HttpJspPage These classes defines the interface for the compiled JSP page. These interfaces are: jspInit() jspDestroy() _jspService(HttpServletRequest request,HttpServletResponse response) In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine. In this lesson we will learn about the various tags available in JSP with suitable examples. In JSP tags can be devided into 4 different types. These are: Directives In the directives we can import packages, define error handling pages or the session information of the JSP page. Declarations This tag is used for defining the functions and variables to be used in the JSP. Scriplets In this tag we can insert any amount of valid java code and these codes are placed in _jspService method by the JSP engine. Expressions We can use this tag to output any data on the generated page. These data are automatically converted to string and printed on the output stream. Now we will examine each tags in details with examples. DIRECTIVES Syntax of JSP directives is: <%@directive attribute="value" %> Where directive may be: page: page is used to provide the information about it. Example: <%@page language="java" %> include: include is used to include a file in the JSP page. Example: <%@ include file="/header.jsp" %> taglib: taglib is used to use the custom tags in the JSP pages (custom tags allows us to defined our own tags). Example: <%@ taglib uri="tlds/taglib.tld" prefix="mytag" %> and attribute may be: language="java" This tells the server that the page is using the java language. Current JSP specification supports only java language. Example: <%@page language="java" %> extends="mypackage.myclass" This attribute is used when we want to extend any class. We can use comma(,) to import more than one packages. Example: <%@page language="java" import="java.sql.*,mypackage.myclass" %> session="true" When this value is true session data is available to the JSP page otherwise not. By default this value is true. Example: <%@page language="java" session="true" %> errorPage="error.jsp" errorPage is used to handle the un-handled exceptions in the page. Example: <%@page language="java" session="true" errorPage="error.jsp" %> contentType="text/html;charset=ISO-8859-1" Use this attribute to set the mime type and character set of the JSP. Example: <%@page language="java" session="true" contentType="text/html;charset=ISO-8859-1" %> Syntax of JSP Declaratives are: <%! //java codes %> JSP Declaratives begins with <%! and ends %> with .We can embed any amount of java code in the JSP Declaratives. Variables and functions defined in the declaratives are class level and can be used anywhere in the JSP page. Example: <%@page contentType="text/html" %> <%! int cnt=0; private int getCount(){ //increment cnt and return the value cnt++; return cnt; } %>

Values of Cnt are:

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

<%=getCount()%>

The above example prints the value of variable cnt. To execute the code click below.


Syntax of JSP Scriptles are: <% //java codes %> JSP Scriptlets begins with <% and ends with %> .We can embed any amount of java code in the JSP Scriptlets. JSP Engine places these code in the _jspService() method. Variables available to the JSP Scriptlets are: request:
request represents the clients request and is a subclass of HttpServletRequest. Use this variable to retrieve the data submitted along the request. Example: <% //java codes String userName=null; userName=request.getParameter("userName"); %> response: response is subclass of HttpServletResponse. session:
session represents the HTTP session object associated with the request. out:
out is an object of output stream and is used to send any output to the client. Other variable available to the scriptlets are pageContext, application,config and exception.

Syntax of JSP Expressions are: <%="Any thing" %> JSP Expressions start with Syntax of JSP Scriptles are with <%= and ends with %>. Between these this you can put anything and that will converted to the String and that will be displayed. Example: <%="hello teacherone" %> Above code will display 'hello teacherone'. Introduction
While there are numerous technologies for building web applications that serve dynamic content, the one that has really caught the attention of the development community is JavaServer Pages (JSP). And not without ample reason either. JSP not only enjoys cross-platform and cross-Web-server support, but effectively melds the power of server-side Java technology with the WYSIWYG features of static HTML pages. JSP pages typically comprise of: Static HTML/XML components. Special JSP tags Optionally, snippets of code written in the Java programming language called "scriptlets." Consequently, you can create and maintain JSP pages by conventional HTML/XML tools. It is important to note that the JSP specification is a standard extension defined on top of the Servlet API. Thus, it leverages all of your experience with servlets.

There are significant differences between JSP and servlet technology. Unlike servlets, which is a programmatic technology requiring significant developer expertise, JSP appeals to a much wider audience. It can be used not only by developers, but also by page designers, who can now play a more direct role in the development life cycle. Another advantage of JSP is the inherent separation of presentation from content facilitated by the technology, due its reliance upon reusable component technologies like the JavaBeans component architecture and Enterprise JavaBeans technology. This course provides you with an in-depth introduction to this versatile technology, and uses the Tomcat JSP 1.1 Reference Implementation from the Apache group for running the example programs.


162) What are JSP Advantages
162) Separation of static from dynamic content: With servlets, the logic for generation of the dynamic content is an intrinsic part of the servlet itself, and is closely tied to the static presentation templates responsible for the user interface. Thus, even minor changes made to the UI typically result in the recompilation of the servlet. This tight coupling of presentation and content results in brittle, inflexible applications. However, with JSP, the logic to generate the dynamic content is kept separate from the static presentation templates by encapsulating it within external JavaBeans components. These are then created and used by the JSP page using special tags and scriptlets. When a page designer makes any changes to the presentation template, the JSP page is automatically recompiled and reloaded into the web server by the JSP engine. Write Once Run Anywhere: JSP technology brings the "Write Once, Run Anywhere" paradigm to interactive Web pages. JSP pages can be moved easily across platforms, and across web servers, without any changes. Dynamic content can be served in a variety of formats: There is nothing that mandates the static template data within a JSP page to be of a certain format. Consequently, JSP can service a diverse clientele ranging from conventional browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML. Recommended Web access layer for n-tier architecture: Sun's J2EE Blueprints, which offers guidelines for developing large-scale applications using the enterprise Java APIs, categorically recommends JSP over servlets for serving dynamic content. Completely leverages the Servlet API: If you are a servlet developer, there is very little that you have to "unlearn" to move over to JSP. In fact, servlet developers are at a distinct advantage because JSP is nothing but a high-level abstraction of servlets. You can do almost anything that can be done with servlets using JSP--but more easily! Comparing JSP with ASP Although the features offered by JSP may seem similar to that offered by Microsoft's Active Server Pages (ASP), they are fundamentally different technologies, as shown by the following table:

JavaServer Pages Active Server Pages Web Server Support Most popular web servers including Apache, Netscape, and Microsoft IIS can be easily enabled with JSP. Native support only within Microsoft IIS or Personal Web Server. Support for select servers using third-party products. Platform Support Platform independent. Runs on all Java-enabled platforms. Is fully supported under Windows. Deployment on other platforms is cumbersome due to reliance on the Win32-based component model. Component Model Relies on reusable, cross-platform components like JavaBeans, Enterprise JavaBeans, and custom tag libraries. Uses the Win32-based COM component model. Scripting Can use the Java programming language or JavaScript. Supports VBScript and JScript for scripting. Security Works with the Java security model. Can work with the Windows NT security architecture. Database Access Uses JDBC for data access. Uses Active Data Objects for data access. Customizable Tags JSP is extensible with custom tag libraries. Cannot use custom tag libraries and is not extensible.


163) Which one is preferred...JSP or Servlets?
163) It is true that both servlets and JSP pages have many features in common, and can be used for serving up dynamic web content. Naturally, this may cause some confusion as to when to opt for one of the technologies over the other. Luckily, Sun's J2EE Blueprints offers some guidelines towards this. According to the Blueprints, use servlets strictly as a web server extension technology. This could include the implementation of specialized controller components offering services like authentication, database validation, and so forth. It is interesting to note that what is commonly known as the "JSP engine" itself is a specialized servlet running under the control of the servlet engine. Since JSP only deals with textual data, you will have to continue to use servlets when communicating with Java applets and applications. Use JSP to develop typical web applications that rely upon dynamic content. JSP should also be used in place of proprietary web server extensions like server-side includes as it offers excellent features for handling repetitive content.

The purpose of JSP is to provide a declarative, presentation-centric method of developing servlets. As noted before, the JSP specification itself is defined as a standard extension on top the Servlet API. Consequently, it should not be too surprisingly that under the covers, servlets and JSP pages have a lot in common. Typically, JSP pages are subject to a translation phase and a request processing phase. The translation phase is carried out only once, unless the JSP page changes, in which case it is repeated. Assuming there were no syntax errors within the page, the result is a JSP page implementation class file that implements the Servlet interface, as shown below.

The translation phase is typically carried out by the JSP engine itself, when it receives an incoming request for the JSP page for the first time. Note that the JSP 1.1 specification also allows for JSP pages to be precompiled into class files. Precompilation may be especially useful in removing the start-up lag that occurs when a JSP page delivered in source form receives the first request from a client. Many details of the translation phase, like the location where the source and class files are stored are implementation dependent. The source for the class file generated by Tomcat for this example JSP page (shown in the above figure) is as follows: package jsp; import java.io.PrintWriter; import java.io.IOException; import java.io.FileInputStream; import java.io.ObjectInputStream; import java.util.Vector; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*; import java.beans.*; import org.apache.jasper.JasperException; import java.text.*; import java.util.*; public class _0005cjsp_0005cjsptest_0002ejspjsptest_jsp_0 extends HttpJspBase { static { } public _0005cjsp_0005cjsptest_0002ejspjsptest_jsp_0( ) { } private static boolean _jspx_inited = false; public final void _jspx_init() throws JasperException { } public void _jspService(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; String _value = null; try { if (_jspx_inited == false) { _jspx_init(); _jspx_inited = true; } _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html"); pageContext = _jspxFactory.getPageContext(this, request,response, "", true, 8192, true); application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); // begin out.write("\r\n\r\n\r\n"); // end // begin [file="E:\\jsp\\jsptest.jsp";from=(3,2);to=(5,0)] Date d = new Date(); String today = DateFormat.getDateInstance().format(d); // end // begin out.write("\r\nToday is: \r\n "); // end // begin [file="E:\\jsp\\jsptest.jsp";from=(7,8);to=(7,13)] out.print(today); // end // begin out.write(" \r\n\r\n\r\n"); // end } catch (Exception ex) { if (out.getBufferSize() != 0) out.clear(); pageContext.handlePageException(ex); } finally { out.flush(); _jspxFactory.releasePageContext(pageContext); } } } The JSP page implementation class file extends HttpJspBase, which in turn implements the Servlet interface. Observe how the service method of this class, _jspService(), essentially inlines the contents of the JSP page. Although _jspService() cannot be overridden, the developer can describe initialization and destroy events by providing implementations for the jspInit() and jspDestroy() methods within their JSP pages. Once this class file is loaded within the servlet container, the _jspService() method is responsible for replying to a client's request. By default, the _jspService() method is dispatched on a separate thread by the servlet container in processing concurrent client requests, as shown below: JSP Access Models The early JSP specifications advocated two philosophical approaches, popularly known as Model 1 and Model 2 architectures, for applying JSP technology. These approaches differ essentially in the location at which the bulk of the request processing was performed, and offer a useful paradigm for building applications using JSP technology. Consider the Model 1 architecture, shown below: In the Model 1 architecture, the incoming request from a web browser is sent directly to the JSP page, which is responsible for processing it and replying back to the client. There is still separation of presentation from content, because all data access is performed using beans. Although the Model 1 architecture is suitable for simple applications, it may not be desirable for complex implementations. Indiscriminate usage of this architecture usually leads to a significant amount of scriptlets or Java code embedded within the JSP page, especially if there is a significant amount of request processing to be performed. While this may not seem to be much of a problem for Java developers, it is certainly an issue if your JSP pages are created and maintained by designers--which is usually the norm on large projects. Another downside of this architecture is that each of the JSP pages must be individually responsible for managing application state and verifying authentication and security. The Model 2 architecture, shown above, is a server-side implementation of the popular Model/View/Controller design pattern. Here, the processing is divided between presentation and front components. Presentation components are JSP pages that generate the HTML/XML response that determines the user interface when rendered by the browser. Front components (also known as controllers) do not handle any presentation issues, but rather, process all the HTTP requests. Here, they are responsible for creating any beans or objects used by the presentation components, as well as deciding, depending on the user's actions, which presentation component to forward the request to. Front components can be implemented as either a servlet or JSP page. The advantage of this architecture is that there is no processing logic within the presentation component itself; it is simply responsible for retrieving any objects or beans that may have been previously created by the controller, and extracting the dynamic content within for insertion within its static templates. Consequently, this clean separation of presentation from content leads to a clear delineation of the roles and responsibilities of the developers and page designers on the programming team. Another benefit of this approach is that the front components present a single point of entry into the application, thus making the management of application state, security, and presentation uniform and easier to maintain. JSP Syntax Basics JSP syntax is fairly straightforward, and can be classified into directives, scripting elements, and standard actions.

Directives JSP directives are messages for the JSP engine. They do not directly produce any visible output, but tell the engine what to do with the rest of the JSP page. JSP directives are always enclosed within the <%@ ... %> tag. The two primary directives are page and include. (Note that JSP 1.1 also provides the taglib directive, which can be used for working with custom tag libraries, although this isn't discussed here.)

Page Directive
Typically, the page directive is found at the top of almost all of your JSP pages. There can be any number of page directives within a JSP page, although the attribute/value pair must be unique. Unrecognized attributes or values result in a translation error. For example, <%@ page import="java.util.*, com.foo.*" buffer="16k" %> makes available the types declared within the included packages for scripting and sets the page buffering to 16K. Include Directive The include directive lets you separate your content into more manageable elements, such as those for including a common page header or footer. The page included can be a static HTML page or more JSP content. For example, the directive: <%@ include file="copyright.html" %>

can be used to include the contents of the indicated file at any location within the JSP page.

Declarations JSP declarations let you define page-level variables to save information or define supporting methods that the rest of a JSP page may need. While it is easy to get led away and have a lot of code within your JSP page, this move will eventually turn out to be a maintenance nightmare. For that reason, and to improve reusability, it is best that logic-intensive processing is encapsulated as JavaBean components. Declarations are found within the <%! ... %> tag. Always end variable declarations with a semicolon, as any content must be valid Java statements: <%! int i=0; %> You can also declare methods. For example, you can override the initialization event in the JSP life cycle by declaring: <%! public void jspInit() { //some initialization code } %> Expressions With expressions in JSP, the results of evaluating the expression are converted to a string and directly included within the output page. Typically expressions are used to display simple values of variables or return values by invoking a bean's getter methods. JSP expressions begin within <%= ... %> tags and do not include semicolons: <%= fooVariable %> <%= fooBean.getName() %> Scriptlets JSP code fragments or scriptlets are embedded within <% ... %> tags. This Java code is run when the request is serviced by the JSP page. You can have just about any valid Java code within a scriptlet, and is not limited to one line of source code. For example, the following displays the string "Hello" within H1, H2, H3, and H4 tags, combining the use of expressions and scriptlets: <% for (int i=1; i<=4; i++) { %> >Hello> <% } %> Comments Although you can always include HTML comments in JSP pages, users can view these if they view the page's source. If you don't want users to be able to see your comments, embed them within the <%-- ... --%> tag: <%-- comment for server side only --%> A most useful feature of JSP comments is that they can be used to selectively block out scriptlets or tags from compilation. Thus, they can play a significant role during the debugging and testing process. Object Scopes Before we look at JSP syntax and semantics, it is important to understand the scope or visibility of Java objects within JSP pages that are processing a request. Objects may be created implicitly using JSP directives, explicitly through actions, or, in rare cases, directly using scripting code. The instantiated objects can be associated with a scope attribute defining where there is a reference to the object and when that reference is removed. The following diagram indicates the various scopes that can be associated with a newly created object:

JSP Implicit Objects As a convenience feature, the JSP container makes available implicit objects that can be used within scriptlets and expressions, without the page author first having to create them. These objects act as wrappers around underlying Java classes or interfaces typically defined within the Servlet API. The nine implicit objects: request: represents the HttpServletRequest triggering the service invocation. Request scope.
response: represents HttpServletResponse to the request. Not used often by page authors. Page scope. pageContext: encapsulates implementation-dependent features in PageContext. Page scope. application: represents the ServletContext obtained from servlet configuration object. Application scope. out: a JspWriter object that writes into the output stream. Page scope. config: represents the ServletConfig for the JSP. Page scope.
page: synonym for the "this" operator, as an HttpJspPage. Not used often by page authors. Page scope. session: An HttpSession. Session scope. More on sessions shortly. exception: the uncaught Throwable object that resulted in the error page being invoked. Page scope. Note that these implicit objects are only visible within the system generated _jspService() method. They are not visible within methods you define yourself in declarations.

Synchronization Issues By default, the service method of the JSP page implementation class that services the client request is multithreaded. Thus, it is the responsibility of the JSP page author to ensure that access to shared state is effectively synchronized. There are a couple of different ways to ensure that the service methods are thread-safe. The easy approach is to include the JSP page directive:

<%@ page isThreadSafe="false" %>

This causes the JSP page implementation class to implement the SingleThreadModel interface, resulting in the synchronization of the service method, and having multiple instances of the servlet to be loaded in memory. The concurrent client requests are then distributed evenly amongst these instances for processing in a round-robin fashion, as shown below: The downside of using this approach is that it is not scalable. If the wait queue grows due to a large number of concurrent requests overwhelming the processing ability of the servlet instances, then the client may suffer a significant delay in obtaining the response. A better approach is to explicitly synchronize access to shared objects (like those instances with application scope, for example) within the JSP page, using scriptlets:

<% synchronized (application) { SharedObject foo = (SharedObject) application.getAttribute("sharedObject"); foo.update(someValue); application.setAttribute("sharedObject",foo); } %>

Exception Handling JSP provides a rather elegant mechanism for handling runtime exceptions. Although you can provide your own exception handling within JSP pages, it may not be possible to anticipate all situations. By making use of the page directive's errorPage attribute, it is possible to forward an uncaught exception to an error handling JSP page for processing. For example, <%@ page isErrorPage="false" errorPage="errorHandler.jsp" %> informs the JSP engine to forward any uncaught exception to the JSP page errorHandler.jsp. It is then necessary for errorHandler.jsp to flag itself as a error processing page using the directive: <%@ page isErrorPage="true" %> This allows the Throwable object describing the exception to be accessed within a scriptlet through the implicit exception object.

By default, all JSP pages participate in an HTTP session. The HttpSession object can be accessed within scriptlets through the session implicit JSP object. Sessions are a good place for storing beans and objects that need to be shared across other JSP pages and servlets that may be accessed by the user. The session objects is identified by a session ID and stored in the browser as a cookie. If cookies are unsupported by the browser, then the session ID may be maintained by URL rewriting. Support for URL rewriting is not mandated by the JSP specification and is supported only within a few servers. Although you cannot place primitive data types into the session, you can store any valid Java object by identifying it by a unique key. For example:

<% Foo foo = new Foo(); session.putValue("foo",foo); %>

makes available the Foo instance within all JSP pages and servlets belonging to the same session. The instance may be retrieved within a different JSP page as:

<% Foo myFoo = (Foo) session.getValue("foo"); %>

The call to session.getValue() returns a reference to the generic Object type. Thus it is important to always cast the value returned to the appropriate data type before using it. It is not mandatory for JSP pages to participate in a session; they may choose to opt out by setting the appropriate attribute of the page directive: <%@ page session="false" %> There is no limit on the number of objects you can store into the session. However, placing large objects into the session may degrade performance, as they take up valuable heap space. By default, most servers set the lifetime of a session object to 30 minutes, although you can easily reset it on a per session basis by invoking setMaxInvalidationInterval(int secs) on the session object. The figure below highlights the general architecture of session management:

The JSP engine holds a live reference to objects placed into the session as long as the session is valid. If the session is invalidated or encounters a session timeout, then the objects within are flagged for garbage collection.

Standard Actions Actions allow you to perform sophisticated tasks like instantiating objects and communicating with server-side resources like JSP pages and servlets without requiring Java coding. Although the same can be achieved using Java code within scriptlets, using action tags promotes reusability of your components and enhances the maintainability of your application.

Using JavaBean Components The component model for JSP technology is based on JavaBeans component architecture. JavaBeans components are nothing but Java objects which follow a well-defined design/naming pattern: the bean encapsulates its properties by declaring them private and provides public accessor (getter/setter) methods for reading and modifying their values.

Before you can access a bean within a JSP page, it is necessary to identify the bean and obtain a reference to it. The tag tries to obtain a reference to an existing instance using the specified id and scope, as the bean may have been previously created and placed into the session or application scope from within a different JSP page. The bean is newly instantiated using the Java class name specified through the class attribute only if a reference was not obtained from the specified scope. Consider the tag:

In this example, the Person instance is created just once and placed into the session. If this useBean tag is later encountered within a different JSP page, a reference to the original instance that was created before is retrieved from the session. The tag can also optionally include a body, such as <% user.setDate(DateFormat.getDateInstance( ).format(new Date())); //etc.. %>

Any scriptlet (or tags, which are explained shortly) present within the body of a tag are executed only when the bean is instantiated, and are used to initialize the bean's properties. Once you have declared a JavaBean component, you have access to its properties to customize it. The value of a bean's property is accessed using the tag. With the tag, you specify the name of the bean to use (from the id field of useBean), as well as the name of the property whose value you are interested in. The actual value is then directly printed to the output: Changing the property of a JavaBean component requires you to use the tag. For this tag, you identify the bean and property to modify and provide the new value:

or When developing beans for processing form data, you can follow a common design pattern by matching the names of the bean properties with the names of the form input elements. You also need to define the corresponding getter/setter methods for each property within the bean. The advantage in this is that you can now direct the JSP engine to parse all the incoming values from the HTML form elements that are part of the request object, then assign them to their corresponding bean properties with a single statement, like this: This runtime magic is possible through a process called introspection, which lets a class expose its properties on request. The introspection is managed by the JSP engine, and implemented through the Java reflection mechanism. This feature alone can be a lifesaver when processing complex forms containing a significant number of input elements. If the names of your bean properties do not match those of the form's input elements, they can still be mapped explicitly to your property by naming the parameter as:

With the tag, you can redirect the request to any JSP, servlet, or static HTML page within the same context as the invoking page. This effectively halts processing of the current page at the point where the redirection occurs, although all processing up to that point still takes place: A tag may also have jsp:param subelements that can provide values for some elements in the request used in the forwarding:

Request Chaining Request chaining is a powerful feature and can be used to effectively meld JSP pages and servlets in processing HTML forms, as shown in the following figure:

Consider the following JSP page, say Bean1.jsp, which creates a named instance fBean of type FormBean, places it in the request, and forwards the call to the servlet JSP2Servlet. Observe the way the bean is instantiated--here we automatically call the bean's setter methods for properties which match the names of the posted form elements, while passing the corresponding values to the methods. The servlet JSP2Servlet now extracts the bean passed to it from the request, makes changes using the appropriate setters, and forwards the call to another JSP page Bean2.jsp using a request dispatcher. Note that this servlet, acting as a controller, can also place additional beans if necessary, within the request.

public void doPost (HttpServletRequest request, HttpServletResponse response) { try { FormBean f = (FormBean) request.getAttribute ("fBean"); f.setName("Mogambo"); // do whatever else necessary getServletConfig().getServletContext(). getRequestDispatcher("/jsp/Bean2.jsp"). forward(request, response); } catch (Exception ex) { . . . } }

The JSP page Bean2.jsp can now extract the bean fBean (and whatever other beans that may have been passed by the controller servlet) from the request and extract its properties. Including Requests The tag can be used to redirect the request to any static or dynamic resource that is in the same context as the calling JSP page. The calling page can also pass the target resource bean parameters by placing them into the request, as shown in the diagram: For example: not only allows shoppingcart.jsp to access any beans placed within the request using a tag, but the dynamic content produced by it is inserted into the calling page at the point where the tag occurs. The included resource, however, cannot set any HTTP headers, which precludes it from doing things like setting cookies, or else an exception is thrown.


164) Briefly describe : what XML namespaces are?
164) The XML namespaces recommendation defines a way to distinguish between duplicate element type and attribute names. Such duplication might occur, for example, in an XSLT stylesheet or in a document that contains element types and attributes from two different DTDs. An XML namespace is a collection of element type and attribute names. The namespace is identified by a unique name, which is a URI. Thus, any element type or attribute name in an XML namespace can be uniquely identified by a two-part name: the name of its XML namespace and its local name. This two-part naming system is the only thing defined by the XML namespaces recommendation. XML namespaces are declared with an xmlns attribute, which can associate a prefix with the namespace. The declaration is in scope for the element containing the attribute and all its descendants. For example: abcd If an XML namespace declaration contains a prefix, you refer to element type and attribute names in that namespace with the prefix. For example: abcd If an XML namespace declaration does not contain a prefix, the namespace is the default XML namespace and you refer to element type names in that namespace without a prefix. For example: abcd

165) Can you give me an executive summary of what XML namespaces are not?
165) They aren't a cure of cancer, they aren't a way to win the lottery, and they aren't a direct cause of world peace. They also aren't very difficult to understand or use. Two things that XML namespaces are not have caused a lot of confusion, so we'll mention them here: XML namespaces are not a technology for joining XML documents that use different DTDs. Although they might be used in such a technology, they don't provide it themselves. The URIs used as XML namespace names are not guaranteed to point to schemas, information about the namespace, or anything else -- they're just identifiers. URIs were used simply because they're a well-known system for creating unique identifiers. Don't even think about trying to resolve these URIs.

166) What is a traditional namespace?
166) Before discussing XML namespaces, it is useful to discuss namespaces in general. In this FAQ, we will refer to such namespaces as traditional namespaces. We will refer to XML namespaces as XML namespaces. The word namespace can refer to either a traditional namespace or an XML namespace, depending on context, but will generally refer to an XML namespace. A traditional namespace is a set of zero or more names, each of which must be unique within the namespace and constructed according to the rules (if any) of the namespace. For example, the names of element types in an XML document inhabit a traditional namespace, as do the names of tables in a relational database and the names of class variables in a Java class. Traditional namespaces also occur outside the field of computer science -- for example, the names of people could be thought to inhabit a traditional namespace, as could the names of species.

167) What is the relationship between different traditional namespaces?
167) They are disjoint -- that is, they are not related. Because of this, a name in one traditional namespace does not collide with the same name in a different traditional namespace. This property is useful to applications that have multiple sets of names. By assigning each set of names to a different traditional namespace, they can allow the same name to occur in each set of names without fear of collision. For example, in the following XML document, there is no conflict between the three different uses of the name Value. This is because an XML document has one traditional namespace for element type names and, for each element type, one traditional namespace for the names of the attributes that apply to that element type. Thus, the two Value attribute names don't conflict because each is assigned to a different traditional namespace -- the first to the attribute namespace for the Title element type and the second to the attribute namespace for the Category element type. Furthermore, neither of the Value attribute names conflicts with the Value element type name because element type names are kept in a traditional namespace that is separate from the attribute namespaces. Other examples of applications that use multiple traditional namespaces include: Java classes. In a Java class, there is one traditional namespace for the names of class variables, one traditional namespace for the names of methods, and, for each method, one traditional namespace for the names of variables local to that method. Relational databases. In a relational database, there is one traditional namespace for the names of tables and, for each table, one traditional namespace for the names of columns in that table.

168) What are traditional namespaces used for?
168) Perhaps the most common (computer science) use of traditional namespaces is to provide a container for a set of identifiers. For example, traditional namespaces are used to contain the names (identifiers) of element types in an XML document, the names of class variables in a Java class, and the names of tables in a relational database. Traditional namespaces are useful in this regard because of their requirement that each name in the namespace be unique. Thus, when a new name (identifier) is added to the namespace, the uniqueness of the identifier can be verified by checking that the name does not already exist in the namespace. (Note that just because a set of objects draws its names from some traditional namespace does not mean that those names uniquely identify the objects. For example, two different people can share the same name, as can two different element nodes in a DOM tree, which use element type names as their names. For the names in a traditional namespace to uniquely identify the objects in a set, the objects in the set must draw their names only from that namespace and no name can be applied to more than one object. In practice, the names from a single traditional namespace are only used to identify the objects in a single set; otherwise, additional information must be stored stating which names apply to which set.)

169) What is the purpose of XML namespaces?
169) XML namespaces are designed to provide universally unique names for elements and attributes. This allows people to do a number of things, such as: Combine fragments from different documents without any naming conflicts. (See example below.) Write reusable code modules that can be invoked for specific elements and attributes. Universally unique names guarantee that such modules are invoked only for the correct elements and attributes.

Define elements and attributes that can be reused in other schemas or instance documents without fear of name collisions. For example, you might use XHTML elements in a parts catalog to provide part descriptions. Or you might use the nil attribute defined in XML Schemas to indicate a missing value. As an example of how XML namespaces are used to resolve naming conflicts in XML documents that contain element types and attributes from multiple XML languages, consider the following two XML documents:

1010 Miami Florida usa 11111
and: MyWebServer
123.45.67.8
Each document uses a different XML language and each language defines an Address element type. Each of these Address element types is different -- that is, each has a different content model, a different meaning, and is interpreted by an application in a different way. This is not a problem as long as these element types exist only in separate documents. But what if they are combined in the same document, such as a list of departments, their addresses, and their Web servers? How does an application know which Address element type it is processing? One solution is to simply rename one of the Address element types -- for example, we could rename the second element type IPAddress. However, this is not a useful long term solution. One of the hopes of XML is that people will standardize XML languages for various subject areas and write modular code to process those languages. By reusing existing languages and code, people can quickly define new languages and write applications that process them. If we rename the second Address element type to IPAddress, we will break any code that expects the old name. A better answer is to assign each language (including its Address element type) to a different namespace. This allows us to continue using the Address name in each language, but to distinguish between the two different element types. The mechanism by which we do this is XML namespaces. (Note that by assigning each Address name to an XML namespace, we actually change the name to a two-part name consisting of the name of the XML namespace plus the name Address. This means that any code that recognizes just the name Address will need to be changed to recognize the new two-part name. However, this only needs to be done once, as the two-part name is universally unique.

170) What is an XML namespace?
170) An XML namespace is a collection of element type and attribute names. The collection itself is unimportant -- in fact, a reasonable argument can be made that XML namespaces don't actually exist as physical or conceptual entities (see myth #1 in "Namespace Myths Exploded"). What is important is the name of the XML namespace, which is a URI. This allows XML namespaces to provide a two-part naming system for element types and attributes. The first part of the name is the URI used to identify the XML namespace -- the namespace name. The second part is the element type or attribute name itself -- the local part, also known as the local name. Together, they form the universal name. This two-part naming system is the only thing defined by the XML namespaces recommendation. By using multiple XML namespaces, multiple element types with the same local name can inhabit the same XML document. For example, the following document uses XML namespaces to distinguish between two different element types named Address. DVS1 Wilhelminenstr. 7 Darmstadt Hessen Germany D-64285 OurWebServer 123.45.67.8 The first Address element type name belongs to the http://www.anyname.com/ito/addresses XML namespace. It has a universal (two-part) name of "http://www.anyname.com/ito/addresses" plus "Address". (Following the convention proposed by James Clark in his paper XML Namespaces (see question 14.1), we write this as {http://www.anyname.com/ito/addresses}Address.) The second Address element type name belongs to the http://www.tu-darmstadt.de/ito/servers XML namespace and has a universal name of {http://www.anyname.com/ito/servers}Address. Thus, each universal name is unique, meeting the requirement that each element type in an XML document have a unique name.

171) Does the XML namespaces recommendation define anything except a two-part naming system for element types and attributes?
171) No.
THE XML NAMESPACES RECOMMENDATION DOES NOT DEFINE ANYTHING EXCEPT A TWO-PART NAMING SYSTEM FOR ELEMENT TYPES AND ATTRIBUTES. In particular, they do not provide or define any of the following:
A way to merge two documents that use different DTDs. A way to associate XML namespaces and schema information.

A way to validate documents that use XML namespaces. A way to associate element type or attribute declarations in a DTD with an XML namespace.


172) What do XML namespaces actually contain?
172) XML namespaces are collections of names, nothing more. That is, they contain the names of element types and attributes, not the elements or attributes themselves.

The element type name A and the attribute name C are in the http://www.foo.org/ namespace because they are mapped there by the foo prefix. The element type name B and the attribute name D are not in any XML namespace because no prefix maps them there. On the other hand, the elements A and B and the attributes C and D are not in any XML namespace, even though they are physically within the scope of the http://www.foo.org/ namespace declaration. This is because XML namespaces contain names, not elements or attributes. XML namespaces also do not contain the definitions of the element types or attributes. This is an important difference, as many people are tempted to think of an XML namespace as a schema, which it is not. (For information about the structure of an XML namespace, see myth #6 in "Namespace Myths Exploded".)


173) Are the names of all element types and attributes in some XML namespace? No.
173) If an element type or attribute name is not specifically declared to be in an XML namespace -- that is, it is unprefixed and (in the case of element type names) there is no default XML namespace -- then that name is not in any XML namespace. If you want, you can think of it as having a null URI as its name, although no "null" XML namespace actually exists.

174) 3.6) Do XML namespaces apply to entity names, notation names, or processing instruction targets? No.
174) XML namespaces apply only to element type and attribute names. Furthermore, in an XML document that conforms to the XML namespaces recommendation, entity names, notation names, and processing instruction targets must not contain colons.

175) Who can create an XML namespace?
175) Anybody can create an XML namespace -- all you need to do is assign a URI as its name and decide what element type and attribute names are in it. The URI must be under your control and should not be being used to identify a different XML namespace, such as by a coworker. (In practice, most people that create XML namespaces also describe the element types and attributes whose names are in it -- their content models and types, their semantics, and so on. However, this is not part of the process of creating an XML namespace, nor does the XML namespace include or provide a way to discover such information.)

176) Do I need to use XML namespaces?
176) Maybe, maybe not. If you don't have any naming conflicts in the XML documents you are using today, as is often the case with documents used inside a single organization, then you probably don't need to use XML namespaces. However, if you do have conflicts today, or if you expect conflicts in the future due to distributing your documents outside your organization or bringing outside documents into your organization, then you should probably use XML namespaces. Regardless of whether you use XML namespaces in your own documents, it is likely that you will use them in conjunction with some other XML technology, such as XSL, XHTML, or XML Schemas. For example, the following XSLT (XSL Transformations) stylesheet uses XML namespaces to distinguish between element types defined in XSLT and those defined elsewhere:

177) What is the relationship between XML namespaces and the XML 1.0 recommendation?
177) Although the XML 1.0 recommendation anticipated the need for XML namespaces by noting that element type and attribute names should not include colons, it did not actually support XML namespaces. Thus, XML namespaces are layered on top of XML 1.0. In particular, any XML document that uses XML namespaces is a legal XML 1.0 document and can be interpreted as such in the absence of XML namespaces. For example, consider the following document: If this document is processed by a namespace-unaware processor, that processor will see two elements whose names are foo:A and foo:B. The foo:A element has an attribute named xmlns:foo and the foo:B element has an attribute named foo:C. On the other hand, a namespace-aware processor will see two elements with universal names {http://www.foo.org}A and {http://www.foo.org}B. The {http://www.foo.org}A does not have any attributes; instead, it has a namespace declaration that maps the foo prefix to the URI http://www.foo.org. The {http://www.foo.org}B element has an attribute named {http://www.foo.org}C.

Needless to say, this has led to a certain amount of confusion. One area of confusion is the relationship between XML namespaces and validating XML documents against DTDs. This occurs because the XML namespaces recommendation did not describe how to use XML namespaces with DTDs.
Fortunately, a similar situation does not occur with XML schema languages, as all of these support XML namespaces. The other main area of confusion is in recommendations and specifications such as DOM and SAX whose first version predates the XML namespaces recommendation. Although these have since been updated to include XML namespace support, the solutions have not always been pretty due to backwards compatibility requirements. All recommendations in the XML family now support XML namespaces.


178) What is the difference between versions 1.0 and 1.1 of the XML namspaces recommendation?
178) There are only two differences between XML namespaces 1.0 and XML namespaces 1.1:
Version 1.1 adds a way to undeclare prefixes. For more information, Version 1.1 uses IRIs (Internationalized Resource Identifiers) instead of URIs. Basically, URIs are restricted to a subset of ASCII characters, while IRIs allow much broader use of Unicode characters. For complete details, see section 9 of Namespaces in XML 1.1.
NOTE: As of this writing (February, 2003), Namespaces in XML 1.1 is still a candidate recommendation and not widely used. PART II: DECLARING AND USING XML NAMESPACES 4) SECTION 4: DECLARING XML NAMESPACES IN AN XML DOCUMENT 4.1) How do I declare an XML namespace in an XML document? To declare an XML namespace, you use an attribute whose name has the form: xmlns:prefix --OR-- xmlns These attributes are often called xmlns attributes and their value is the name of the XML namespace being declared; this is a URI. The first form of the attribute (xmlns:prefix) declares a prefix to be associated with the XML namespace. The second form (xmlns) declares that the specified namespace is the default XML namespace. For example, the following declares two XML namespaces, named http://www.anyname.com/ito/addresses and http://www.anyname.com/ito/servers. The first declaration associates the addr prefix with the http://www.anyname.com/ito/addresses namespace and the second declaration states that the http://www.tu-darmstadt.de/ito/servers namespace is the default XML namespace. NOTE: Technically, xmlns attributes are not attributes at all -- they are XML namespace declarations that just happen to look like attributes. Unfortunately, they are not treated consistently by the various XML recommendations, which means that you must be careful when writing an XML application. For example, in the XML Information Set (http://www.w3.org/TR/xml-infoset), xmlns "attributes" do not appear as attribute information items. Instead, they appear as namespace declaration information items. On the other hand, both DOM level 2 and SAX 2.0 treat namespace attributes somewhat ambiguously. In SAX 2.0, an application can instruct the parser to return xmlns "attributes" along with other attributes, or omit them from the list of attributes. Similarly, while DOM level 2 sets namespace information based on xmlns "attributes", it also forces applications to manually add namespace declarations using the same mechanism the application would use to set any other attributes.

179) Where can I declare an XML namespace?
179) You can declare an XML namespace on any element in an XML document. The namespace is in scope for that element and all its descendants unless it is overridden (see question 4.5 and question 4.6) or undeclared

180) Can I use an attribute default in a DTD to declare an XML namespace?
180) Yes. For example, the following uses the FIXED attribute xmlns:foo on the A element type to associate the foo prefix with the http://www.foo.org/ namespace. The effect of this is that both A and B are in the http://www.foo.org/ namespace. ]> abc IMPORTANT: You should be very careful about placing XML namespace declarations in external entities (external DTDs), as non-validating parsers are not required to read these. For example, suppose the preceding DTD was placed in an external entity (foo.dtd) and that the document was processed by a non-validating parser that did not read foo.dtd. This would result in a namespace error because the foo prefix was never declared: abc

181) 4.4) Do the default values of xmlns attributes declared in the DTD apply to the DTD?
181) No. Declaring a default value of an xmlns attribute in the DTD does not declare an XML namespace for the DTD. (In fact, no XML namespace declarations apply to DTDs.) Instead, these defaults (declarations) take effect only when the attribute is instantiated on an element. For example: ]> <========== Namespace declaration takes effect here. abc <========= Namespace declaration ends here. (Note that an earlier version of MSXML (the parser used by Internet Explorer) did use fixed xmlns attribute declarations as XML namespace declarations, but that this was removed in MSXML 4.

182) 4.5) How do I override an XML namespace declaration that uses a prefix?
182) To override the prefix used in an XML namespace declaration, you simply declare another XML namespace with the same prefix. For example, in the following, the foo prefix is associated with the http://www.foo.org/ namespace on the A and B elements and the http://www.bar.org/ namespace on the C and D elements. That is, the names A and B are in the http://www.foo.org/ namespace and the names C and D are in the http://www.bar.org/ namespace. abcd In general, this leads to documents that are confusing to read and should be avoided. 4.6) How do I override a default XML namespace declaration? To override the current default XML namespace, you simply declare another XML namespace as the default. For example, in the following, the default XML namespace is the http://www.foo.org/ namespace on the A and B elements and the http://www.bar.org/ namespace on the C and D elements. That is, the names A and B are in the http://www.foo.org/ namespace and the names C and D are in the http://www.bar.org/ namespace. abcd Using multiple default XML namespaces can lead to documents that are confusing to read and should be done carefully.

183) How do you undeclare an XML namespace prefix?
183) In version 1.0 of the XML namespaces recommendation, you cannot "undeclare" an XML namespace prefix. It remains in scope until the end of the element on which it was declared unless it is overridden. Furthermore, trying to undeclare a prefix by redeclaring it with an empty (zero-length) name (URI) results in a namespace error. For example: <==== This is an error in v1.0, legal in v1.1. abcd In version 1.1 of the XML namespaces recommendation [currently a candidate recommendation -- February, 2003], you can undeclare an XML namespace prefix by redeclaring it with an empty name. For example, in the above document, the XML namespace declaration xmlns:foo="" is legal and removes the mapping from the foo prefix to the http://www.foo.org URI. Because of this, the use of the foo prefix in the foo:D element results in a namespace error.

184) How do you undeclare the default XML namespace?
184) To "undeclare" the default XML namespace, you declare a default XML namespace with an empty (zero-length) name (URI). Within the scope of this declaration, unprefixed element type names do not belong to any XML namespace. For example, in the following, the default XML namespace is the http://www.foo.org/ for the A and B elements and there is no default XML namespace for the C and D elements. That is, the names A and B are in the http://www.foo.org/ namespace and the names C and D are not in any XML namespace. abcd

185) Why are special attributes used to declare XML namespaces?
185) I don't know the answer to this question, but the likely reason is that the hope that they would simplify the process of moving fragments from one document to another document. An early draft of the XML namespaces recommendation proposed using processing instructions to declare XML namespaces. While these were simple to read and process, they weren't easy to move to other documents. Attributes, on the other hand, are intimately attached to the elements being moved. Unfortunately, this hasn't worked as well as was hoped. For example, consider the following XML document: bar Simply using a text editor to cut the fragment headed by the element from one document and paste it into another document results in the loss of namespace information because the namespace declaration is not part of the fragment -- it is on the parent element () -- and isn't moved. Even when this is done programmatically, the situation isn't necessarily any better. For example, suppose an application uses DOM level 2 to "cut" the fragment from the above document and "paste" it into a different document. Although the namespace information is transferred (it is carried by each node), the namespace declaration (xmlns attribute) is not, again because it is not part of the fragment. Thus, the application must manually add the declaration before serializing the document or the new document will be invalid.

186) How do different XML technologies treat XML namespace declarations?
186) This depends on the technology -- some treat them as attributes and some treat them as namespace declarations. For example, SAX1 treats them as attributes and SAX2 can treat them as attributes or namespace declarations, depending on how the parser is configured.
DOM levels 1 and 2 treat them as attributes, but DOM level 2 also interprets them as namespace declarations. (For more information, see question 9.5.) XPath, XSLT, and XML Schemas treat them as namespaces declarations. The reason that different technologies treat these differently is that many of these technologies predate XML namespaces. Thus, newer versions of them need to worry both about XML namespaces and backwards compatibility issues.

187) How do I use prefixes to refer to element type and attribute names in an XML namespace?
187) Make sure you have declared the prefix and that it is still in scope . All you need to do then is prefix the local name of an element type or attribute with the prefix and a colon. The result is a qualified name , which the application parses to determine what XML namespace the local name belongs to. For example, suppose you have associated the serv prefix with the http://www.anyname.com/ito/servers namespace and that the declaration is still in scope. In the following, serv:Address refers to the Address name in the http://www.anyname.com/ito/servers namespace. (Note that the prefix is used on both the start and end tags.) 123.45.67.8 Now suppose you have associated the xslt prefix with the http://www.w3.org/1999/XSL/Transform namespace. In the following, xslt:version refers to the version name in the http://www.w3.org/1999/XSL/Transform namespace:

188) How do you use the default XML namespace to refer to element type names in an XML namespace?
188) Make sure you have declared the default XML namespace (see question 4.1) and that that declaration is still in scope (see section 6). All you need to do then is use the local name of an element type. Even though it is not prefixed, the result is still a qualified name (see question 10.1), which the application parses to determine what XML namespace it belongs to. For example, suppose you declare the http://www.anyname.com/ito/addresses namespace as the default XML namespace and that the declaration is still in scope. In the following, Address refers to the Address name in the http://www.anyname.com/ito/addresses namespace.
123.56.78.9
For information about how to use the default XML namespace with attribute names, see question 5.3.

189) How do I use the default XML namespace to refer to attribute names in an XML namespace?
189) You cannot do it.
The default XML namespace only applies to element type names, so you can refer to attribute names that are in an XML namespace only with a prefix. For example, suppose that you declared the http://www.anyname.com/ito/addresses namespace as the default XML namespace. In the following, the type attribute name does not refer to that namespace, although the Address element type name does. That is, the Address element type name is in the http://www.tu-darmstadt.de/ito/addresses namespace, but the type attribute name is not in any XML namespace.
To understand why this is true, remember that the purpose of XML namespaces is to uniquely identify element and attribute names. Unprefixed attribute names can be uniquely identified based on the element type to which they belong, so there is no need identify them further by including them in an XML namespace. In fact, the only reason for allowing attribute names to be prefixed is so that attributes defined in one XML language can be used in another XML language.

190) When should I use the default XML namespace instead of prefixes?
190) This is purely a matter of choice, although your choice may affect the readability of the document. When elements whose names all belong to a single XML namespace are grouped together, using a default XML namespace might make the document more readable. For example: abcd efgh 1234 5678 ijkl When elements whose names are in multiple XML namespaces are interspersed, default XML namespaces definitely make a document more difficult to read and prefixes should be used instead. For example: abcd efgh 1234 5678 ijkl In some cases, default namespaces can be processed faster than namespace prefixes, but the difference is certain to be negligible in comparison to total processing time.

191) What is the scope of an XML namespace declaration?
191) The scope of an XML namespace declaration is that part of an XML document to which the declaration applies. An XML namespace declaration remains in scope for the element on which it is declared and all of its descendants, unless it is overridden or undeclared on one of those descendants (see questions 4.5, 4.6, and 4.8). For example, in the following, the scope of the declaration of the http://www.foo.org/ namespace is the element A and its descendants (B and C). The scope of the declaration of the http://www.bar.org/ namespace is only the element C.

192) Does the scope of an XML namespace declaration include the element it is declared on?
192) Yes.
For example, in the following, the names B and C are in the http://www.bar.org/ namespace, not the http://www.foo.org/ namespace. This is because the declaration that associates the foo prefix with the http://www.bar.org/ namespace occurs on the B element, overriding the declaration on the A element that associates it with the http://www.foo.org/ namespace. abcd Similarly, in the following, the names B and C are in the http://www.bar.org/ namespace, not the http://www.foo.org/ namespace because the declaration declaring http://www.bar.org/ as the default XML namespace occurs on the B element, overriding the declaration on the A element. abcd A final example is that, in the following, the attribute name D is in the http://www.bar.org/ namespace. abcd One consequence of XML namespace declarations applying to the elements they occur on is that they actually apply before they appear. Because of this, software that processes qualified names should be particularly careful to scan the attributes of an element for XML namespace declarations before deciding what XML namespace (if any) an element type or attribute name belongs to.

193) 6.3) If an element or attribute is in the scope of an XML namespace declaration, is its name in that namespace? Not necessarily.
193) When an element or attribute is in the scope of an XML namespace declaration, the element or attribute's name is checked to see if it has a prefix that matches the prefix in the declaration. Whether the name is actually in the XML namespace depends on whether the prefix matches.

194) 6.4) What happens when an XML namespace declaration goes out of scope?
194) When an XML namespace declaration goes out of scope, it simply no longer applies. For example, in the following, the declaration of the http://www.foo.org/ namespace does not apply to the C element because this is outside its scope. That is, it is past the end of the B element, on which the http://www.foo.org/ namespace was declared. abcd efgh In addition to the declaration no longer applying, any declarations that it overrode come back into scope. For example, in the following, the declaration of the http://www.foo.org/ namespace is brought back into scope after the end of the B element. This is because it was overridden on the B element by the declaration of the http://www.bar.org/ namespace. abcd efgh

195) What happens if no XML namespace declaration is in scope?
195) If no XML namespace declaration is in scope, then any prefixed element type or attribute names result in namespace errors. For example, in the following, the names foo:A and foo:B result in namespace errors. In the absence of an XML namespace declaration, unprefixed element type and attribute names do not belong to any XML namespace. For example, in the following, the names A and B are not in any XML namespace.

196) Can multiple XML namespace declarations be in scope at the same time?
196) Yes, as long as they don't use the same prefixes and at most one of them is the default XML namespace. For example, in the following, the http://www.foo.org/ and http://www.bar.org/ namespaces are both in scope for all elements: abcd efgh One consequence of this is that you can place all XML namespace declarations on the root element and they will be in scope for all elements. This is the simplest way to use XML namespaces.

197) 6.7) How can I declare XML namespaces so that all elements and attributes are in their scope?
197) XML namespace declarations that are made on the root element are in scope for all elements and attributes in the document. This means that an easy way to declare XML namespaces is to declare them only on the root element. For example: DVS1 Wilhelminenstr. 7 Darmstadt Hessen Germany D-64285 OurWebServer 123.45.67.8

198) Does the scope of an XML namespace declaration ever include the DTD ?
198) No.
XML namespaces can be declared only on elements and their scope consists only of those elements and their descendants. Thus, the scope can never include the DTD.

199) Can I use XML namespaces in DTDs?
199) Yes and no.
In particular, DTDs can contain qualified names but XML namespace declarations do not apply to DTDs .
This has a number of consequences. Because XML namespace declarations do not apply to DTDs:
There is no way to determine what XML namespace a prefix in a DTD points to. Which means... Qualified names in a DTD cannot be mapped to universal names. Which means... Element type and attribute declarations in a DTD are expressed in terms of qualified names, not universal names. Which means... Validation cannot be redefined in terms of universal names as might be expected. This situation has caused numerous complaints but, as XML namespaces are already a recommendation, is unlikely to change. The long term solution to this problem is an XML schema language: all of the proposed XML schema languages provide a mechanism by which the local name in an element type or attribute declaration can be associated with an XML namespace. This makes it possible to redefine validity in terms of universal names.

200) Do XML namespace declarations apply to DTDs ?
200) No.
In particular, an xmlns attribute declared in the DTD with a default is not an XML namespace declaration for the DTD.
(Note that an earlier version of MSXML (the parser used by Internet Explorer) did use such declarations as XML namespace declarations, but that this was removed in MSXML 4.

201) Can I use qualified names in DTDs?
201) Yes. For example, the following is legal: However, because XML namespace declarations do not apply to DTDs (see question 7.2), qualified names in the DTD cannot be converted to universal names. As a result, qualified names in the DTD have no special meaning. For example, foo:A is just foo:A -- it is not A in the XML namespace to which the prefix foo is mapped. The reason qualified names are allowed in the DTD is so that validation will continue to work.

202) Can the content model in an element type declaration contain element types whose names come from other XML namespaces?
202) Yes and no.
The answer to this question is yes in the sense that a qualified name in a content model can have a different prefix than the qualified name of the element type being declared. For example, the following is legal: The answer to this question is no in the sense that XML namespace declarations do not apply to DTDs so the prefixes used in an element type declaration are technically meaningless. In particular, they do not specify that the name of a certain element type belongs to a certain namespace. Nevertheless, the ability to mix prefixes in this manner is crucial when: a) you have a document whose names come from multiple XML namespaces (see question 8.5), and b) you want to construct that document in a way that is both valid and conforms to the XML namespaces recommendation (see question 7.6).

203) Can the attribute list of an element type contain attributes whose names come from other XML namespaces?
203) Yes and no, for the reasons listed in question 7.4. For example, the following is legal: 7.6) How can I construct an XML document that is valid and conforms to the XML namespaces recommendation? In answering this question, it is important to remember that: Validity is a concept defined in XML 1.0, XML namespaces are layered on top of XML 1.0 (see myth #11 in "Namespace Myths Exploded"), and The XML namespaces recommendation does not redefine validity, such as in terms of universal names (see myth #9 in "Namespace Myths Exploded"). Thus, validity is the same for a document that uses XML namespaces and one that doesn't. In particular, with respect to validity: xmlns attributes are treated as attributes, not XML namespace declarations. Qualified names are treated like other names. For example, in the name foo:A, foo is not treated as a namespace prefix, the colon is not treated as separating a prefix from a local name, and A is not treated as a local name. The name foo:A is treated simply as the name foo:A. Because of this, XML documents that you might expect to be valid are not. For example, the following document is not valid because the element type name A is not declared in the DTD, in spite of the fact both foo:A and A share the universal name {http://www.foo.org/}A: ]> Similarly, the following is not valid because the xmlns attribute is not declared in the DTD: ]> Furthermore, documents that you might expect to be invalid are valid. For example, the following document is valid but contains two definitions of the element type with the universal name {http://www.foo.org/}A: ]> abcd Finally, validity has nothing to do with correct usage of XML namespaces. For example, the following document is valid but does not conform to the XML namespaces recommendation because the foo prefix is never declared: ]> Therefore, when constructing an XML document that uses XML namespaces, you need to do both of the following if you want the document to be valid: Declare xmlns attributes in the DTD. Use the same qualified names in the DTD and the body of the document. For example: ]> There is no requirement that the same prefix always be used for the same XML namespace. For example, the following is also valid: ]> However, documents that use multiple prefixes for the same XML namespace or the same prefix for multiple XML namespaces are confusing to read and thus prone to error. They also allow abuses such as defining an element type or attribute with a given universal name more than once, as was seen earlier. Therefore, a better set of guidelines for writing documents that are both valid and conform to the XML namespaces recommendation is: Declare all xmlns attributes in the DTD. Use the same qualified names in the DTD and the body of the document. Use one prefix per XML namespace. Do not use the same prefix for more than one XML namespace. Use at most one default XML namespace. The latter three guidelines guarantee that prefixes are unique. This means that prefixes fulfill the role normally played by namespace names (URIs) -- uniquely identifying an XML namespace -- and that qualified names are equivalent to universal names, so a given universal name is always represented by the same qualified name. Unfortunately, this is contrary to the spirit of prefixes, which were designed for their flexibility.

204) How can I allow the prefixes in my document to be different from the prefixes in my DTD?
204) One of the problems with the solution proposed in question 7.6 is that it requires the prefixes in the document to match those in the DTD. Fortunately, there is a workaround for this problem, although it does require that a single prefix be used for a particular namespace URI throughout the document. (This is a good practice anyway, so it's not too much of a restriction.) The solution assumes that you are using a DTD that is external to the document, which is common practice. To use different prefixes in the external DTD and XML documents, you declare the prefix with a pair of parameter entities in the DTD. You can then override these entities with declarations in the internal DTD in a given XML document. This works because the internal DTD is read before the external DTD and the first definition of a particular entity is the one that is used. The following paragraphs describe how to use a single namespace in your DTD. You will need to modify them somewhat to use multiple namespaces. To start with, declare three parameter entities in your DTD: The p entity ("p" is short for "prefix") is used in place of the actual prefix in element type and attribute names. The s entity ("s" is short for "suffix") is used in place of the actual prefix in namespace declarations. The nsdecl entity ("nsdecl" is short for "namespace declaration") is used in place of the name of the xmlns attribute in declarations of that attribute. Now use the p entity to define parameter entities for each of the names in your namespace. For example, suppose element type names A, B, and C and attribute name D are in your namespace. Next, declare your element types and attributes using the "name" entities, not the actual names. For example: There are several things to notice here. Attribute D is in a namespace, so it is declared with a "name" entity. Attribute E is not in a namespace, so no entity is used. The nsdecl entity is used to declare the xmlns attribute. (xmlns attributes must be declared on every element type on which they can occur.) Note that a default value is given for the xmlns attribute. The reference to element type B in the content model of A is placed inside parentheses. The reason for this is that a modifier -- * in this case -- is applied to it. Using parentheses is necessary because the replacement values of parameter entities are padded with spaces; directly applying the modifier to the parameter entity reference would result in illegal syntax in the content model. For example, suppose the value of the A entity is "foo:A", the value of the B entity is "foo:B", and the value of the C entity is "foo:C". The declaration: would resolve to: This is illegal because the * modifier must directly follow the reference to the foo:B element type. By placing the reference to the B entity in parentheses, the declaration resolves to: This is legal because the * modifier directly follows the closing parenthesis. Now let's see how this all works. Suppose our XML document won't use prefixes, but instead wants the default namespace to be the http://www.foo.org/ namespace. In this case, no entity declarations are needed in the document. For example, our document might be: bizbuz This document is valid because the declarations for p, s, and nsdecl in the DTD set p and s to "" and nsdecl to "xmlns". That is, after replacing the p, s, and nsdecl parameter entities, the DTD is as follows. Notice that both the DTD and document use the element type names A, B, and C and the attribute names D and E. But what if the document wants to use a different prefix, such as foo? In this case, the document must override the declarations of the p and s entities in its internal DTD. That is, it must declare these entities so that they use foo as a prefix (followed by a colon) and a suffix (preceded by a colon). For example: ]> bizbuz In this case, the internal DTD is read before the external DTD, so the values of the p and s entities from the document are used. Thus, after replacing the p, s, and nsdecl parameter entities, the DTD is as follows. Notice that both the DTD and document use the element type names foo:A, foo:B, and foo:C and the attribute names foo:D and E.

205) How can I validate an XML document that uses XML namespaces?
205) There is no difference between validating a document that uses XML namespaces and validating one that doesn't. In either case, you simply use a validating parser or other software that performs validation. For information about how to construct an XML document that is valid and conforms to the XML namespace recommendation.

206) If I start using XML namespaces, do I need to change my existing DTDs?
206) Probably.
If you want your XML documents to be both valid and conform to the XML namespaces recommendation, you need to declare any xmlns attributes and use the same qualified names in the DTD as in the body of the document. If your DTD contains element type and attribute names from a single XML namespace, the easiest thing to do is to use your XML namespace as the default XML namespace. To do this, declare the attribute xmlns (no prefix) for each possible root element type. If you can guarantee that the DTD is always read (see question 4.3), set the default value in each xmlns attribute declaration to the URI used as your namespace name. Otherwise, declare your XML namespace as the default XML namespace on the root element of each instance document. If your DTD contains element type and attribute names from multiple XML namespaces, you need to choose a single prefix for each XML namespace and use these consistently in qualified names in both the DTD and the body of each document. You also need to declare your xmlns attributes in the DTD and declare your XML namespaces. As in the single XML namespace case, the easiest way to do this is add xmlns attributes to each possible root element type and use default values if possible. Note that you should only need to make these changes once.

207) How do I create documents that use XML namespaces?
207) The same as you create documents that don't use XML namespaces. If you're currently using Notepad on Windows or emacs on Linux, you can continue using Notepad or emacs. If you're using an XML editor that is not namespace-aware, you can also continue to use that, as qualified names are legal names in XML documents and xmlns attributes are legal attributes. And if you're using an XML editor that is namespace-aware, it will probably provide features such as automatically declaring XML namespaces and keeping track of prefixes and the default XML namespace for you.

208) How can I check that a document conforms to the XML namespaces recommendation?
208) Unfortunately, I know of no software that only checks for conformance to the XML namespaces recommendation. It is possible that some namespace-aware validating parsers (such as those from DataChannel (Microsoft), IBM, Oracle, or Sun) check XML namespace conformance as part of parsing and validating. Thus, you might be able to run your document through such parsers as a way of testing conformance. Note that writing an application to check conformance to the XML namespaces recommendation is not as easy as it might seem. The problem is that most parsers do not make DTD information available to the application, so it might not be possible to check conformance in the DTD. Also note that writing a SAX 1.0 application that checks conformance in the body of the document (as opposed to the DTD) should be an easy thing to do. (John Cowan's Namespace SAX Filter probably already does this.

209) Can I use the same document with both namespace-aware and namespace-unaware applications?
209) Yes. This situation is quite common, such as when a namespace-aware application is built on top of a namespace-unaware parser. Another common situation is when you create an XML document with a namespace-unaware XML editor but process it with a namespace-aware application. Using the same document with both namespace-aware and namespace-unaware applications is possible because XML namespaces use XML syntax. That is, an XML document that uses XML namespaces is still an XML document and is recognized as such by namespace-unaware software. The only thing you need to be careful about when using the same document with both namespace-aware and namespace-unaware applications is when the namespace-unaware application requires the document to be valid. In this case, you must be careful to construct your document in a way that is both valid and conforms to the XML namespaces recommendation. (It is possible to construct documents that conform to the XML namespaces recommendation but are not valid and vice versa.) For information about how to do this, see question 7.6.

210) What software is needed to process XML namespaces?
210) From a document author's perspective, this is generally not a relevant question. Most XML documents are written in a specific XML language and processed by an application that understands that language. If the language uses an XML namespace, then the application will already use that namespace -- there is no need for any special XML namespace software. For information about the software application writers use to process XML namespaces .

211) How can I use XML namespaces to combine documents that use different element type and attribute names?
211) Before we answer this question, we need to clear up a common misconception about XML namespaces. It is often believed that XML namespaces provide some sort of magic that allows you to automatically combine XML documents that use separate sets of element types and attributes. This is not true. Although XML namespaces provide some of the tools you need to do this, you still need to do most of the work yourself, as you will see in the answer to this question. To combine documents that use separate sets of element types and attributes, all you really need to do is decide where the elements and attributes go in the final document. For example, does element type A from the first document go inside element type B? Is it a sibling? Or are they completely unrelated? Although the procedure for actually combining two documents can be easily automated, deciding how to combine them is not likely to ever be automated. Instead, it is a strictly human problem, requiring somebody to make choices. For example, suppose we have a document containing addresses:
Wilhelminenstr. 7 Darmstadt Hessen Germany D-64285
and a document containing Web server information: OurWebServer
123.45.67.8
Now suppose we would like a document of departments, their addresses, and their Web servers, which we can make from the above documents plus a little additional information: DVS1
Wilhelminenstr. 7 Darmstadt Hessen Germany D-64285
OurWebServer
123.45.67.8
...
Unfortunately, we have a problem: there are two Address element types and two Name element types. (Although the Name element types both have a content model of PCDATA, they have different meanings -- one is the name of the department and the other is the name of the server -- so we would like to recognize them as different element types.) To solve these conflicts, we can use XML namespaces. We assign the address information to the http://www.anyname.com/ito/addresses namespace, the server information to the http://www.anyname.com/ito/servers namespace, and the newly added departmental information to the http://www.anyname.com/ito/depts namespace. Thus, our new document looks like: For example, the following was accepted by MSXML and both xmlns:foo attributes were required: MSXML returned an error for the following because the second foo prefix was not "declared": The reason for this restriction was so that MSXML could use universal names to match element type and attribute declarations to elements and attributes during validation. Although this would have simplified many of the problems of writing documents that are both valid and conform to the XML namespaces recommendation (see question 7.6), some users complained about it because it was not part of the XML namespaces recommendation. In response to these complaints, Microsoft removed this restriction in later versions, which are now shipping. Ironically, the idea was later independently derived as a way to resolve the problems of validity and namespaces. However, it has not been implemented by anyone.

213) How do applications process documents that use XML namespaces?
213) Applications process documents that use XML namespaces in almost exactly the same way they process documents that don't use XML namespaces. For example, if a namespace-unaware application adds a new sales order to a database when it encounters a SalesOrder element, the equivalent namespace-aware application does the same. The only difference is that the namespace-aware application: Might need to check for xmlns attributes and parse qualified names. Whether it does this depends on whether such processing is already done by lower-level software, such as a namespace-aware DOM implementation. Uses universal (two-part) names instead of local (one-part) names. For example, the namespace-aware application might add a new sales order in response to an {http://www.anyname.com/ito/sales}SalesOrder element instead of a SalesOrder element.

214) How do I use XML namespaces with SAX 1.0 ?
214) The easiest way to use XML namespaces with SAX 1.0 is to use John Cowan's Namespace SAX Filter (see http://www.ccil.org/~cowan/XML). This is a SAX filter that keeps track of XML namespace declarations, parses qualified names, and returns element type and attribute names as universal names in the form: URI^local-name For example: http://www.anyname.com/ito/sales^SalesOrder Your application can then base its processing on these longer names. For example, the code: public void startElement(String elementName, AttributeList attrs) throws SAXException { ... if (elementName.equals("SalesOrder")) { // Add new database record. } ... } might become: public void startElement(String elementName, AttributeList attrs) throws SAXException { ... if (elementName.equals("http://www.anyname.com/sales^SalesOrder")) { // Add new database record. } ... } or: public void startElement(String elementName, AttributeList attrs) throws SAXException { ... // getURI() and getLocalName() are utility functions // to parse universal names. if (getURI(elementName).equals("http://www.anyname.com/ito/sales")) { if (getLocalName(elementName).equals("SalesOrder")) { // Add new database record. } } ... } If you do not want to use the Namespace SAX Filter, then you will need to do the following in addition to identifying element types and attributes by their universal names: In startElement, scan the attributes for XML namespace declarations before doing any other processing. You will need to maintain a table of current prefix-to-URI mappings (including a null prefix for the default XML namespace). In startElement and endElement, check whether the element type name includes a prefix. If so, use your mappings to map this prefix to a URI. Depending on how your software works, you might also check if the local part of the qualified name includes any colons, which are illegal. In startElement, check whether attribute names include a prefix. If so, process as in the previous point.

215) How do I use XML namespaces with SAX 2.0 ?
215) SAX 2.0 primarily supports XML namespaces through the following methods: startElement and endElement in the ContentHandler interface return namespace names (URIs) and local names as well as qualified names. getValue, getType, and getIndex in the Attributes interface can retrieve attribute information by namespace name (URI) and local name as well as by qualified name. For example, the namespace-unaware SAX 1.0 code: public void startElement(String elementName, AttributeList attrs) throws SAXException { ... if (elementName.equals("SalesOrder")) { // Add new database record. } ... } might become: public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attrs) throws SAXException { ... if (namespaceURI.equals("http://www.anyname.com/sales") && localName.equals("SalesOrder")) { // Add new database record. } ... } Although the above methods are sufficient for most applications, SAX 2.0 also supports the following: startPrefixMapping and endPrefixMapping in the ContentHandler interface return scope information about individual prefixes. getURI, getLocalName, and getQName in the Attributes interface return the namespace name (URI), local name, and qualified name of an attribute by index. The http://xml.org/features/namespaces and http://xml.org/features/namespace-prefixes properties allow applications to request whether parsers return qualified names and xmlns attributes. The NamespaceSupport class helps applications track the currently declared namespace prefixes and names (URIs). For complete details, see the SAX 2.0 specification (http://www.saxproject.org/).

216) How do you use XML namespaces with DOM level 1 ?
216) This depends on what DOM level 1 implementation you are using. If you are using a namespace-aware DOM implementation, such as those from Data Channel (Microsoft), IBM, Oracle, or Sun, then all you need to do is use the methods provided by those implementations to retrieve the namespace name (URI) and local names. For example, the namespace-unaware code: // Check the local name. // getNodeName() is a DOM level 1 method. if (elementNode.getNodeName().equals("SalesOrder")) { // Add new database record. } might become the following namespace-aware code when using Oracle's DOM implementation: // Check the XML namespace name (URI). // getNamespace() and NSElement are Oracle-specific. String SALES_NS = "http://www.anyname.com/ito/sales"; if ((NSElement)elementNode).getNamespace().equals(SALES_NS)) { // Check the local name. // getLocalName() is Oracle-specific. if ((NSElement)elementNode.getLocalName().equals("SalesOrder")) { // Add new database record. } } Because DOM level 1 does not include XML namespace support, each DOM level 1 implementation provides a slightly different interface for accessing XML namespace information. Most of these implementations include some combination of methods for getting the qualified name, namespace name (URI), local name, and prefix. Therefore, if you are writing a DOM-neutral application, you will need to define your own XML namespace interface and write converters for each DOM implementation you support. Fortunately, this is easy to do. If you are using a namespace-unaware DOM implementation, such as Docuverse version 1 or OpenXML version 1 (these may support XML namespaces in a later version), you will need to perform namespace processing yourself. Although this is largely the same as in a SAX 1.0 application (see question 9.2) -- checking for xmlns attributes on each Element node and converting qualified names on Element and Attr nodes to universal names -- it is potentially more difficult to determine what XML namespace declarations are in scope for any given node. If your application traverses the DOM tree in order from the root, this is fairly easy, as you can maintain prefix-to-URI mappings as you go. However, if you access the tree randomly, you may want to construct a parallel tree with mapping information before you do any other processing or rebuild the DOM tree using prefixes that map to known URIs.

217) How do I use XML namespaces with DOM level 2?
217) DOM level 2 supports XML namespaces through a number of new methods and attributes. The most important of these are the namespaceURI and localName attributes in the Node interface; these allow applications to identify nodes by their namespace name (URI) and local name rather than by qualified name. For example, the namespace-unaware code: // Check the local name. // getNodeName() is a DOM level 1 method. if (elementNode.getNodeName().equals("SalesOrder")) { // Add new database record. } might become the following namespace-aware code: // Check the XML namespace name (URI). // getNamespaceURI() is a DOM level 2 method. String SALES_NS = "http://www.anyname.com/ito/sales"; if (elementNode.getNamespaceURI().equals(SALES_NS)) { // Check the local name. // getLocalName() is a DOM level 2 method. if (elementNode.getLocalName().equals("SalesOrder")) { // Add new database record. } } Note that, unlike SAX 2.0, DOM level 2 treats xmlns attributes as normal attributes. For complete details, see the DOM level 2 recommendation (http://www.w3.org/TR/DOM-Level-2/).

218) Can an application process documents that use XML namespaces and documents that don't use XML namespaces?
218) Yes.
This is a common situation for generic applications, such as editors, browsers, and parsers, that are not wired to understand a particular XML language. Such applications simply treat all element type and attribute names as qualified names. Those names that are not mapped to an XML namespace --- that is, unprefixed element type names in the absence of a default XML namespace and unprefixed attribute names --- are simply processed as one-part names, such as by using a null XML namespace name (URI). Note that such applications must decide how to treat documents that do not conform to the XML namespaces recommendation. For example, what should the application do if an element type name contains a colon (thus implying the existence of a prefix), but there are no XML namespace declarations in the document? The application can choose to treat this as an error, or it can treat the document as one that does not use XML namespaces, ignore the "error", and continue processing.

219) Can an application be both namespace-aware and namespace-unaware?
219) Yes. However, there is generally no reason to do this. The reason is that most applications understand a particular XML language, such as one used to transfer sales orders between companies. If the element type and attribute names in the language belong to an XML namespace, the application must be namespace-aware; if not, the application must be namespace-unaware. For example, such an application should never need to recognize the element type names SalesOrder and {http://www.anyname.com/ito/sales}SalesOrder. For a few applications, being both namespace-aware and namespace-unaware makes sense. For example, a parser might choose to redefine validity in terms of universal names (see myth #9 in "Namespace Myths Exploded") and have both namespace-aware and namespace-unaware validation modes. However, such applications are uncommon.

220) What does a namespace-aware application do when it encounters an error?
220) The XML namespaces recommendation does not specify what a namespace-aware application does when it encounters a document that does not conform to the recommendation. Therefore, the behavior is application-dependent. For example, the application could stop processing, post an error to a log and continue processing, or ignore the error.

221) What is a qualified name?
221) A qualified name is a name of the following form. It consists of an optional prefix and colon, followed by the local part, which is sometimes known as a local name. prefix:local-part --OR-- local-part For example, both of the following are qualified names. The first name has a prefix of serv; the second name does not have a prefix. For both names, the local part (local name) is Address. serv:Address Address In most circumstances, qualified names are mapped to universal names.

222) What characters are allowed in a qualified name?
222) The prefix can contain any character that is allowed in the Name [5] production in XML 1.0 except a colon. The same is true of the local name. Thus, there can be at most one colon in a qualified name -- the colon used to separate the prefix from the local name.

223) Where can qualified names appear?
223) Qualified names can appear anywhere an element type or attribute name can appear: in start and end tags, as the document element type, and in element type and attribute declarations in the DTD. For example: ]> abcd Qualified names cannot appear as entity names, notation names, or processing instruction targets. 10.4) Can qualified names be used in attribute values? Yes, but they have no special significance. That is, they are not necessarily recognized as such and mapped to universal names. For example, the value of the C attribute in the following is the string "foo:D", not the universal name {http://www.foo.org/}D. In spite of this, there is nothing to stop an application from recognizing a qualified name in an attribute value and processing it as such. This is being done in various technologies today. For example, in the following XML Schemas definition, the attribute value xsd:string identifies the type of the foo attribute as the universal name {http://www.w3.org/1999/XMLSchema}string. There are two potential problems with this. First, the application must be able to retrieve the prefix mappings currently in effect. Fortunately, both SAX 2.0 and DOM level 2 support this capability. Second, any general purpose transformation tool, such as one that writes an XML document in canonical form and changes namespace prefixes in the process, will not recognize qualified names in attribute values and therefore not transform them correctly. Although this may be solved in the future by the introduction of the QName (qualified name) data type in XML Schemas, it is a problem today.

224) How are qualified names mapped to names in XML namespaces?
224) If a qualified name in the body of a document (as opposed to the DTD) includes a prefix, then that prefix is used to map the local part of the qualified name to a universal name -- that is, a name in an XML namespace. (Note that the prefix must be in scope -- see section 6.) For example, in the following, the prefix foo is used to map the local names A, B, and C to names in the http://www.foo.org/ namespace: abcd If a qualified name in the body of a document does not include a prefix and a default XML namespace is in scope then one of two things happens. If the name is used as an element tag, it is mapped to a name in the default XML namespace. If it is used as an attribute name, it is not in any XML namespace (see myth #4 in "Namespace Myths Exploded"). For example, in the following, A and B are in the http://www.foo.org/ namespace and C is not in any XML namespace: abcd If a qualified name in the body of a document does not include a prefix and no default XML namespace is in scope, then that name is not in any XML namespace. For example, in the following, A, B, and C are not in any XML namespace: abcd Qualified names in the DTD are never mapped to names in an XML namespace because they are never in the scope of an XML namespace declaration.

225) What is a prefixed name?
225) A prefixed name is a qualified name (see question 10.1) that contains a prefix.

226) What is an unprefixed name?
226) An unprefixed name is a qualified name (see question 10.1) that does not contain a prefix.

227) Are unprefixed names in an XML namespace?
227) Only if they are used in the body of a document (as opposed to the DTD) as an element tag and a default XML namespace is in scope.

228) What is a local name?
228) This is another term for the local part of a qualified name.

229) What is a namespace name?
229) This is the name used to identify a namespace. It is a URI.

230) What is a universal name?
230) A universal name is a two part name consisting of an XML namespace name (URI) and a local name. For example, in the following, the universal name is the namespace name "http://www.anyname.com/ito/servers" plus the local name "Address": 123.45.67.8 The ability to specify universal names is the only function of XML namespaces.

231) How are universal names represented?
231) There is no standard way to represent a universal name. However, three representations are common. The first representation keeps the XML namespace name (URI) and the local name separate. For example, many DOM level 1 implementations have different methods for returning the XML namespace name (URI) and the local name of an element or attribute node. The second representation concatenates the namespace name (URI) and the local name with caret (^). The result is a universally unique (see question 10.12) name, since carets are not allowed in URIs or local names. This is the method used by John Cowan's Namespace SAX Filter (see question 9.2). For example, the universal name that has the URI http://www.anyname.com/ito/servers and the local name Address would be represented as: http://www.anyname.com/ito/servers^Address The third representation, which we use in this FAQ, was suggested by James Clark in his XML Namespaces paper (see question 14.1). It places the XML namespace name (URI) in braces and concatenates this with the local name. This notation is suggested only for documentation and I am aware of no code that uses it. For example, the above name would be represented as: {http://www.anyname.com/ito/servers}Address

232) Are universal names universally unique?
232) No, but it is reasonable to assume they are. Universal element type and attribute names are not guaranteed to be universally unique -- that is, unique within the space of all XML documents -- because it is possible for two different people, each defining their own XML namespace, to use the same URI and the same element type or attribute name. However, this occurs only if: One or both people use a URI that is not under their control, such as somebody outside Netscape using the URI http://www.netscape.com/, or Both people have control over a URI and both use it. The first case means somebody is cheating when assigning URIs (a process governed by trust) and the second case means that two people within an organization are not paying attention to each other's work. For widely published element type and attribute names, neither case is very likely. Thus, it is reasonable to assume that universal names are universally unique. (Since both cases are possible, applications that present security risks should be careful about assuming that universal names are universally unique.) For information about the ability of universal names to uniquely identify element types and attributes (as opposed to the names themselves being unique), see myth #2 in "Namespace Myths Exploded".

233) What is an XML namespace prefix?
233) An XML namespace prefix is a prefix used to specify that a local element type or attribute name is in a particular XML namespace. For example, in the following, the serv prefix specifies that the Address element type name is in the http://www.anyname.com/ito/addresses namespace:

234) What characters are allowed in an XML namespace prefix?
234) The prefix can contain any character that is allowed in the Name [5] production in XML 1.0 except a colon.

235) Are prefixes significant?
235) No. For example, the following are equivalent: and However, prefixes provide a visual cue to readers. Because of this, software (especially editors) should consider preserving prefixes. For example, this is much easier to read: Title ... than this: Title ... or (much worse yet) this: Title ... In spite of this, people are likely to read significance into prefixes, so it is a good idea to use prefixes appropriate to their XML namespace, such as xslt for the XSLT namespace. Finally, although prefixes are not significant in element and attribute names, they may be significant when used elsewhere in an XML document, such as in a DTD (see question 7.6) or an attribute value. Because such usage is common -- for example, XML Schemas uses qualified names in attribute values -- it is tempting to think that it is defined by the XML namespaces recommendation. This is not the case: the XML namespaces recommendation only defines the use of prefixes in element and attribute names. The use of prefixes elsewhere in an XML document is defined outside the XML namespaces recommendation and is entirely the responsibility of the defining application.

236) Can I use the same prefix for more than one XML namespace?
236) Yes. For example, in the following, B is in the http://www.foo.org/ namespace and C is in the http://www.bar.org/ namespace: abc abc Remember, however, that the prefix in an XML namespace declaration overrides the same prefix if that prefix is declared on an ancestor. For example, in the following, C is in the http://www.bar.org/ namespace, not the http://www.foo.org/ namespace: abc In general, it is a good idea to use a prefix for only one XML namespace, as this reduces confusion when reading the document. In spite of this, there is a very real possibility that the same prefix will be used for multiple XML namespaces when combining fragments from different documents.

237) Can I use more than one prefix for the same XML namespace?
237) Yes. For example, in the following, both B and C are in the http://www.foo.org/ namespace: abc abc More reasonably, this situation might arise when copying or cutting and pasting fragments from one document to another, where each document uses a different prefix for the same namespace. For example, suppose the http://www.foo.org/ namespace uses the foo prefix in one document and the bar prefix in another document. Copying an element from one document to the other might result in a document such as the following. Although this may be confusing to read, it is perfectly legal. abc abc In general, it is a good idea to use only one prefix for an XML namespace, as this reduces confusion when reading the document.

238) How are prefixes declared?
238) Prefixes are declared in an XML namespace declaration (xmlns attribute). For more information, see question 4.1.

239) Can I undeclare a prefix -- that is, dissociate a prefix from an XML namespace?
239) No. You can override a prefix (see question 4.5) or the XML namespace declaration that declares the prefix can go out of scope (see question 6.4), but you can't undeclare the prefix. (Note that you can undeclare the default XML namespace; for more information, see question 4.8.) 11.8) What happens if I use a prefix that is not declared? This results in a namespace error. For example, the following document does not conform to the XML namespaces recommendation. However, the XML namespaces recommendation does not specify what a namespace-aware application does when it encounters a non-conformant document, so the behavior is application-dependent. For example, the application could stop processing, post an error to a log and continue processing, or ignore the error. 11.9) What happens if there is no prefix on an element type name? If a default XML namespace declaration is in scope, then the element type name is in the default XML namespace. Otherwise, the element type name is not in any XML namespace. For example, in the following, B and C are in the http://www.foo.org/ namespace and A is not in any XML namespace: abc

240) What happens if there is no prefix on an attribute name?
240) The attribute name is not in any XML namespace. That is, the default XML namespace does not apply to unprefixed attribute names. For more information, see myth #4 in "Namespace Myths Exploded".

241) What is an XML namespace URI?
241) Technically, the term namespace URI is never defined in the XML namespaces recommendation. In practice, this is the term commonly used to denote the URI used as an XML namespace name. That is, it is a synonym for the term namespace name. Because of the widespread use of this term, we tend to use the term "namespace name (URI)" in this FAQ. Note: Version 1.1 of the XML namespaces recommendation uses IRIs (Internationalized Resource Identifiers) instead of URIs. However, because version 1.1 is not yet a full recommendation [February, 2003] and because the IRI RFC is not yet complete, this document continues to refer to URIs instead of IRIs.

242) What is an XML namespace name?
242) An XML namespace name is a URI that uniquely identifies the namespace. URIs are used because they are widely understood and well documented. Because people may only allocate URIs under their control, it is easy to ensure that no two XML namespaces are identified by the same URI.

243) What does the URI used as an XML namespace name point to?
243) The URI used as an XML namespace name is simply an identifier. It is not guaranteed to point to anything and, in general, it is a bad idea to assume that it does. This point causes a lot of confusion, so we'll repeat it here: URIs USED AS XML NAMESPACE NAMES ARE JUST IDENTIFIERS. THEY ARE NOT GUARANTEED TO POINT TO ANYTHING. While this might be confusing when URLs are used as namespace names, it is obvious when other types of URIs are used as namespace names. For example, the following namespace declaration uses an ISBN URN: xmlns:xbe="urn:ISBN:0-7897-2504-5" and the following namespace declaration uses a UUID URN: xmlns:foo="urn:uuid:f81d4fae-7dec-11d0-a765-00a0c91e6bf6" Clearly, neither namespace name points to anything on the Web. NOTE: Namespace URIs that are URLs may point to RDDL documents, although this does not appear to be widely implemented. For details, see the next question. NOTE: An early version of the W3C's XML Schemas used namespace URIs to point to an XML Schema document containing the definitions of the element types and attributes named in the namespace. However, this proved very controversial and the idea has been withdrawn.

244) Can I resolve the URI used as an XML namespace name?
244) Yes. You can also eat a tractor, but that doesn't mean it's a good idea. The URIs used as XML namespace names are not guaranteed to point to anything, so there is generally no reason to resolve them. Furthermore, there is nothing in the processing of XML namespaces that requires you to resolve these URIs. Finally, as was noted in the previous question, many types of namespace URIs are unresolvable on the Web. That said, some people have advocated placing RDDL (Resource Directory Description Language, pronounced "riddle") documents at the locations pointed to by namespace URIs. A RDDL document "provides a text description of some class of resources and of individual resources related to that class", including such things as a human-readable description of what the namespace describes and links to resources such as schemas (in a variety of languages), stylesheets, and code. RDDL documents apparently are being used, although it is not clear how widely. For more information about RDDL and the ideas behind it, see: Resource Directory Description Language RDDL Me This: What Does a Namespace URL Locate? Architectural Theses on Namespaces and Namespace Documents

245) Can I use a relative URI as a namespace name?
245) Yes. However, such usage is deprecated, so you should never do it. The original XML namespaces recommendation does not explicitly disallow the use of relative URIs as namespace names. Instead, it states that two namespace names are identical if their URIs match character for character. It then notes that non-identical URIs might be functionally equivalent, such as when they differ only in case. Combined with the URI specification (RFC2396), which states that relative URIs take on the base URI of their containing document, this provided a loophole with which to use relative URIs. When this was discovered more than a year after the recommendation was released it proved hugely controversial. For example, some people wanted to use relative URIs as namespace names so that elements and attributes would have different XML namespace names (URIs) depending on what document they were in. The objection to this was that it would undermine the purpose of XML namespaces. That is, XML namespaces would no longer provide universally unique names. After more than two months of discussion, it was decided that relative URIs are not expanded when used as namespace names and that their use was deprecated. That is, suppose that the following document has a URI of "http://www.foo.org/xml/relativeExample.xml". abc abc Although the URI "../relativeURI" does expand to the URI "http://www.foo.org/relativeURI", the name of the XML namespace associated with the foo prefix is "../relativeURI", not the expanded URI. It was also decided that: The infoset recommendation does not define an infoset for documents that use relative URIs as XML namespace names. The value of the namespaceURI attribute of the Node interface in the DOM is undefined if the URI is relative. The return value of the namespace-uri() function in XPath is undefined if the URI is relative. All new W3C recommendations should include a statement saying that they do not apply to XML documents that use relative URIs as XML namespace names. For the archives of the mailing list discussing the use of relative URIs as namespace names, see http://lists.w3.org/Archives/Public/xml-uri/. For the results of the W3C XML Plenary Ballot on the use of relative URIs in XML namespace names, see http://www.w3.org/2000/09/xppa.

246) Why are XML namespaces so hard to understand and use?
246) Actually, they aren't. When trying to understand XML namespaces, all you need to do is remember one thing: XML namespaces provide a two-part naming system for element types and attributes. That's it. They don't do anything else and what little complexity there is comes from the flexibility of declaration and scoping rules. You can minimize this complexity by doing the following: Declare all XML namespaces on the root element. Use one prefix per XML namespace. Processing XML namespaces isn't that hard either. In a SAX 1.0 application, you can use John Cowan's Namespace SAX Filter to return universal names; SAX 2.0 does this for you. In a DOM level 1 application, you can usually ask the DOM implementation for namespace information; DOM level 2 always provides this information. If you do your own processing, all you need to remember is to keep the prefix-to-URI mappings as part of your state, scan the attributes for xmlns attributes before doing anything else, and scan element type and attribute names for prefixes.

247) Are there any alternatives to XML namespaces?
247) Yes. You could resolve name clashes by simply renaming the offending element types or attributes and then, during processing, using architectural forms to transform them to names that are recognizeable by different modules in the application. Although you may have to rename some element types or attributes, you won't have to change your application modules. A discussion of architectural forms is beyond the scope of this paper. For more information, see Architectural Forms and SGML/XML Architectures on Robin Cover's XML Cover Pages. As to the actual syntax used by XML namespaces, the idea of declaring XML namespace prefixes in a processing instruction at the start of an XML document is occasionally raised. Processing instructions were used in an early draft of the XML namespaces specification and have the advantage of simplicity (see question 4.9). They were later replaced with the more flexible xmlns attributes. Although you might be tempted to strike out on your own and use processing instructions or some other strategy, this is probably a bad idea, although not necessarily for technical reasons. The real problem is that XML namespaces are already widely used and supported, so any XML documents you produce will be non-standard and non-portable.

248) How controversial are XML namespaces?
248) The need for XML namespaces and the basic idea that a two-part naming system (or something similar) is needed is not controversial. However, the design of XML namespaces -- that is, the way XML namespaces are declared and used in an XML document, as well the confusion discussed in "Namespace Myths Exploded" -- has, at times, been very controversial. (If you want to see just how controversial, go to the archives of the XML-DEV mailing list and search on the word "namespace".) Although XML namespaces still have some very vocal detractors, most people have accepted and are using them. Furthermore, most new XML tools and technologies use them, a state of affairs that is only likely to increase.

249) Q: What is Jakarta Struts Framework?
249) A: Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

250) Q: What is ActionServlet?
250) The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

251) How you will make available any Message Resources Definitions file to the Struts Framework Environment ?
251) Message Resources Definitions file are simple properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag. Example:

252) What is Action Class?
252) The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (command) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

253) Write code of any Action Class?
253) Here is the code of Action Class that returns the ActionForward object. TestAction.java
package roseindia.net;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

254) Q: What is ActionForm?
254) A: An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side.

255) Q: What is Struts Validator Framework?
255) A: Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

256) Q. Give the Details of XML files used in Validator Framework?
256) A: The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

257) Q. How you will display validation fail errors on jsp page?
257) A: Following tag displays all the errors:

258) Q. How you will enable front-end validation based on the xml in validation.xml?
258) A: The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form "logonForm" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script. : The javax.servlet.Servlet interface defines the three methods known as life-cycle method. public void init(ServletConfig config) throws ServletException public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException public void destroy() First the servlet is constructed, then initialized wih the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.

259) Q: What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
259) A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root. The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.

260) Q: Explain the directory structure of a web application.
260) A: The directory structure of a web application consists of two parts. A private directory called WEB-INF A public resource directory which contains public resource folder. WEB-INF folder consists of 1. web.xml 2. classes directory 3. lib directory

261) Q: What are the common mechanisms used for session tracking?
261) A: Cookies SSL sessions URL- rewriting

262) Q: Explain ServletContext.
262) A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.

263) Q: What is preinitialization of a servlet?
263) A: A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

264) Q: What is the difference between Difference between doGet() and doPost()?
264) A: A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.

265) Q: What is the difference between HttpServlet and GenericServlet?
265) A: A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.

266) Q: What is the difference between ServletContext and ServletConfig?
266) A: ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.

267) What is Jakarta Struts Framework?
267) Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java. What is ActionServlet? - The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests. How you will make available any Message Resources Definitions file to the Struts Framework Environment? - Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through tag. Example:

268) What is Action Class?
268) The Action Class is part of the Model and is a wrapper around the business logic. The purpose of Action Class is to translate the HttpServletRequest to the business logic. To use the Action, we need to Subclass and overwrite the execute() method. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. The return type of the execute method is ActionForward which is used by the Struts Framework to forward the request to the file as per the value of the returned ActionForward object.

269) Write code of any Action Class?
269) Here is the code of Action Class that returns the ActionForward object. import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class TestAction extends Action { public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { return mapping.findForward(\"testAction\"); } }

270) What is ActionForm?
270) An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side. What is Struts Validator Framework? - Struts Framework provides the functionality to validate the form data. It can be use to validate the data on the users browser as well as on the server side. Struts Framework emits the java scripts and it can be used validate the form data on the client browser. Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class. The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings. Give the Details of XML files used in Validator Framework? - The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean. How you will display validation fail errors on jsp page? - The following tag displays all the errors: How you will enable front-end validation based on the xml in validation.xml? - The tag to allow front-end validation based on the xml in validation.xml. For example the code: generates the client side java script for the form "logonForm" as defined in the validation.xml file. The when added in the jsp file generates the client site validation script.

271) How EJB Invocation happens ?
271) Retrieve Home Object reference from Naming Service via JNDI. Return Home Object reference to the client. Create me a new EJB Object through Home Object interface. Create EJB Object from the Ejb Object. Return EJB Object reference to the client. Invoke business method using EJB Object reference. Delegate request to Bean (Enterprise Bean).

272) Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?
272) You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintenance is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is, again, up to the implementer.

273) Can the primary key in the entity bean be a Java primitive type such as int?
273) The primary key can't be a primitive type. Use the primitive wrapper classes, instead. For example, you can use java.lang.Integer as the primary key class, but not int (it has to be a class, not a primitive). Can you control when passivation occurs? - The developer, according to the specification, cannot directly control when passivation occurs. Although for Stateful Session Beans, the container cannot passivate an instance that is inside a transaction. So using transactions can be a a strategy to control passivation. The ejbPassivate() method is called during passivation, so the developer has control over what to do during this exercise and can implement the require optimized logic. Some EJB containers, such as BEA WebLogic, provide the ability to tune the container to minimize passivation calls. Taken from the WebLogic 6.0 DTD --The passivation-strategy can be either default or transaction. With the default setting the container will attempt to keep a working set of beans in the cache. With the 'transaction' setting, the container will passivate the bean after every transaction (or method call for a non-transactional invocation).

274) What is the advantage of using Entity bean for database operations, over directly using JDBC API to do database operations? When would I use one over the other?
274) Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API. There are two types of Entity Beans Container Managed and Bean Mananged. In Container Managed Entity Bean - Whenever the instance of the bean is created the container automatically retrieves the data from the DB/Persistance storage and assigns to the object variables in bean for user to manipulate or use them. For this the developer needs to map the fields in the database to the variables in deployment descriptor files (which varies for each vendor). In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values, assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a bean object. Similarly in the ejbStore() the container saves the object values back the the persistance storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container. Apart from this, when you use Entity beans you dont need to worry about database transaction handling, database connection pooling etc. which are taken care by the ejb container.

275) What is EJB QL?
275) EJB QL is a Query Language provided for navigation across a network of enterprise beans and dependent objects defined by means of container managed persistence. EJB QL is introduced in the EJB 2.0 specification. The EJB QL query language defines finder methods for entity beans with container managed persistenceand is portable across containers and persistence managers. EJB QL is used for queries of two types of finder methods: Finder methods that are defined in the home interface of an entity bean and which return entity objects. Select methods, which are not exposed to the client, but which are used by the Bean Provider to select persistent values that are maintained by the Persistence Manager or to select entity objects that are related to the entity bean on which the query is defined.

276) Give a brief description about local interfaces ?
276) EEJB was originally designed around remote invocation using the Java Remote Method Invocation (RMI) mechanism, and later extended to support to standard CORBA transport for these calls using RMI/IIOP. This design allowed for maximum flexibility in developing applications without consideration for the deployment scenario, and was a strong feature in support of a goal of component reuse in J2EE. Many developers are using EJBs locally, that is, some or all of their EJB calls are between beans in a single container. With this feedback in mind, the EJB 2.0 expert group has created a local interface mechanism. The local interface may be defined for a bean during development, to allow streamlined calls to the bean if a caller is in the same container. This does not involve the overhead involved with RMI like marshalling etc. This facility will thus improve the performance of applications in which co-location is planned. Local interfaces also provide the foundation for container-managed relationships among entity beans with container-managed persistence.

277) What are the special design care that must be taken when you work with local interfaces?
277) It is important to understand that the calling semantics of local interfaces are different from those of remote interfaces. For example, remote interfaces pass parameters using call-by-value semantics, while local interfaces use call-by-reference. This means that in order to use local interfaces safely, application developers need to carefully consider potential deployment scenarios up front, then decide which interfaces can be local and which remote, and finally, develop the application code with these choices in mind. While EJB 2.0 local interfaces are extremely useful in some situations, the long-term costs of these choices, especially when changing requirements and component reuse are taken into account, need to be factored into the design decision.

278) What happens if remove( ) is never invoked on a session bean?
278) In case of a stateless session bean it may not matter if we call or not as in both cases nothing is done. The number of beans in cache is managed by the container. In case of stateful session bean, the bean may be kept in cache till either the session times out, in which case the bean is removed or when there is a requirement for memory in which case the data is cached and the bean is sent to free pool.

279) What is the difference between Message Driven Beans and Stateless Session beans?
279) In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways: Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls. Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic. Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary. The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.

280) How can I call one EJB from inside of another EJB?
280) EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

281) What is an EJB Context?
281) EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

282) Can we use the constructor, instead of init(), to initialize servlet?
282) Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext.

283) How can a servlet refresh automatically if some new data has entered the database?
283) You can use a client-side Refresh or Server Push. The code in a finally clause will never fail to execute, right? - Using System.exit(1); in try block will not allow finally code to execute. How many messaging models do JMS provide for and what are they? - JMS provide for two messaging models, publish-and-subscribe and point-to-point queuing.

284) What information is needed to create a TCP Socket?
284) The Local System?s IP Address and Port Number. And the Remote System's IPAddress and Port Number.

285) What Class.forName will do while loading drivers?
285) It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.

286) How to Retrieve Warnings?
286) SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object SQLWarning warning = stmt.getWarnings(); if (warning != null) { while (warning != null) { System.out.println(\"Message: \" + warning.getMessage()); System.out.println(\"SQLState: \" + warning.getSQLState()); System.out.print(\"Vendor error code: \"); System.out.println(warning.getErrorCode()); warning = warning.getNextWarning(); } }

287) How many JSP scripting elements are there and what are they?
287) There are three scripting language elements: declarations, scriptlets, expressions.

288) In the Servlet 2.4 specification SingleThreadModel has been deprecated, why?
288) Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level. What are stored procedures? How is it useful? - A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements everytime a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preproceesor. Newer versions of db's support writing stored procedures in Java and Perl too. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procs to implement the business logic( A lot of systems still do it). The biggest advantage is of course speed. Also certain kind of data manipulations are not achieved in SQL. Stored procs provide a mechanism to do these manipulations. Stored procs are also useful when you want to do Batch updates/exports/houseKeeping kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases.

289) How do I include static files within a JSP page?
289) Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase. Do note that you should always supply a relative URL for the file attribute. Although you can also include static resources using the action, this is not advisable as the inclusion is then performed for each and every request. Why does JComponent have add() and remove() methods but Component does not? - because JComponent is a subclass of Container, and can contain other components and jcomponents.

290) How can I implement a thread-safe JSP page?
290) You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" % > within your JSP page.

291) Is is possible for an EJB client to marshal an object of class java.lang.Class to an EJB?
291) Technically yes, spec. compliant NO! - The enterprise bean must not attempt to query a class to obtain information about the declared members that are not otherwise accessible to the enterprise bean because of the security rules of the Java language. Is it legal to have static initializer blocks in EJB? - Although technically it is legal, static initializer blocks are used to execute some piece of code before executing any constructor or method while instantiating a class. Static initializer blocks are also typically used to initialize static fields - which may be illegal in EJB if they are read/write - In EJB this can be achieved by including the code in either the ejbCreate(), setSessionContext() or setEntityContext() methods.

292) Is it possible to stop the execution of a method before completion in a SessionBean?
292) Stopping the execution of a method inside a Session Bean is not possible without writing code inside the Session Bean. This is because you are not allowed to access Threads inside an EJB. What is the default transaction attribute for an EJB? - There is no default transaction attribute for an EJB. Section 11.5 of EJB v1.1 spec says that the deployer must specify a value for the transaction attribute for those methods having container managed transaction. In WebLogic, the default transaction attribute for EJB is SUPPORTS.

293) What is the difference between session and entity beans? When should you use one or the other?
293) An entity bean represents persistent global data from the database; a session bean represents transient user-specific data that will die when the user disconnects (ends his session). Generally, the session beans implement business methods (e.g. Bank.transferFunds) that call entity beans (e.g. Account.deposit, Account.withdraw)

294) Is there any default cache management system with Entity beans ? In other words whether a cache of the data in database will be maintained in EJB ?
294) Caching data from a database inside the Application Server are what Entity EJB's are used for.The ejbLoad() and ejbStore() methods are used to synchronize the Entity Bean state with the persistent storage(database). Transactions also play an important role in this scenario. If data is removed from the database, via an external application - your Entity Bean can still be alive the EJB container. When the transaction commits, ejbStore() is called and the row will not be found, and the transaction rolled back.

295) Why is ejbFindByPrimaryKey mandatory?
295) An Entity Bean represents persistent data that is stored outside of the EJB Container/Server. The ejbFindByPrimaryKey is a method used to locate and load an Entity Bean into the container, similar to a SELECT statement in SQL. By making this method mandatory, the client programmer can be assured that if they have the primary key of the Entity Bean, then they can retrieve the bean without having to create a new bean each time - which would mean creating duplications of persistent data and break the integrity of EJB.

296) Why do we have a remove method in both EJBHome and EJBObject?
296) With the EJBHome version of the remove, you are able to delete an entity bean without first instantiating it (you can provide a PrimaryKey object as a parameter to the remove method). The home version only works for entity beans. On the other hand, the Remote interface version works on an entity bean that you have already instantiated. In addition, the remote version also works on session beans (stateless and stateful) to inform the container of your loss of interest in this bean.

297) How can I call one EJB from inside of another EJB?
297) EJBs can be clients of other EJBs. It just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance reference, and so forth.

298) What is the difference between a Server, a Container, and a Connector?
298) An EJB server is an application, usually a product such as BEA WebLogic, that provides (or should provide) for concurrent client connections and manages system resources such as threads, processes, memory, database connections, network connections, etc. An EJB container runs inside (or within) an EJB server, and provides deployed EJB beans with transaction and security management, etc. The EJB container insulates an EJB bean from the specifics of an underlying EJB server by providing a simple, standard API between the EJB bean and its container. A Connector provides the ability for any Enterprise Information System (EIS) to plug into any EJB server which supports the Connector architecture. See Sun's J2EE Connectors for more in-depth information on Connectors.

299) How is persistence implemented in enterprise beans?
299) Persistence in EJB is taken care of in two ways, depending on how you implement your beans: container managed persistence (CMP) or bean managed persistence (BMP) For CMP, the EJB container which your beans run under takes care of the persistence of the fields you have declared to be persisted with the database - this declaration is in the deployment descriptor. So, anytime you modify a field in a CMP bean, as soon as the method you have executed is finished, the new data is persisted to the database by the container. For BMP, the EJB bean developer is responsible for defining the persistence routines in the proper places in the bean, for instance, the ejbCreate(), ejbStore(), ejbRemove() methods would be developed by the bean developer to make calls to the database. The container is responsible, in BMP, to call the appropriate method on the bean. So, if the bean is being looked up, when the create() method is called on the Home interface, then the container is responsible for calling the ejbCreate() method in the bean, which should have functionality inside for going to the database and looking up the data.

300) What is an EJB Context?
300) EJBContext is an interface that is implemented by the container, and it is also a part of the bean-container contract. Entity beans use a subclass of EJBContext called EntityContext. Session beans use a subclass called SessionContext. These EJBContext objects provide the bean class with information about its container, the client using the bean and the bean itself. They also provide other functions. See the API docs and the spec for more details.

301) Is method overloading allowed in EJB?
301) Yes you can overload methods Should synchronization primitives be used on bean methods? - No. The EJB specification specifically states that the enterprise bean is not allowed to use thread primitives. The container is responsible for managing concurrent access to beans at runtime.

302) Are we allowed to change the transaction isolation property in middle of a transaction?
302) No.
You cannot change the transaction isolation level in the middle of transaction. For Entity Beans, What happens to an instance field not mapped to any persistent storage, when the bean is passivated? - The specification infers that the container never serializes an instance of an Entity bean (unlike stateful session beans). Thus passivation simply involves moving the bean from the ready to the pooled bin. So what happens to the contents of an instance variable is controlled by the programmer. Remember that when an entity bean is passivated the instance gets logically disassociated from it's remote object. Be careful here, as the functionality of passivation/activation for Stateless Session, Stateful Session and Entity beans is completely different. For entity beans the ejbPassivate method notifies the entity bean that it is being disassociated with a particular entity prior to reuse or for dereference.

303) What is a Message Driven Bean, what functions does a message driven bean have and how do they work in collaboration with JMS?
303) Message driven beans are the latest addition to the family of component bean types defined by the EJB specification. The original bean types include session beans, which contain business logic and maintain a state associated with client sessions, and entity beans, which map objects to persistent data. Message driven beans will provide asynchrony to EJB based applications by acting as JMS message consumers. A message bean is associated with a JMS topic or queue and receives JMS messages sent by EJB clients or other beans. Unlike entity beans and session beans, message beans do not have home or remote interfaces. Instead, message driven beans are instantiated by the container as required. Like stateless session beans, message beans maintain no client-specific state, allowing the container to optimally manage a pool of message-bean instances. Clients send JMS messages to message beans in exactly the same manner as they would send messages to any other JMS destination. This similarity is a fundamental design goal of the JMS capabilities of the new specification. To receive JMS messages, message driven beans implement the javax.jms.MessageListener interface, which defines a single onMessage() method. When a message arrives, the container ensures that a message bean corresponding to the message topic/queue exists (instantiating it if necessary), and calls its onMessage method passing the client's message as the single argument. The message bean's implementation of this method contains the business logic required to process the message. Note that session beans and entity beans are not allowed to function as message beans.

304) Does RMI-IIOP support code downloading for Java objects sent by value across an IIOP connection in the same way as RMI does across a JRMP connection?
304) Yes. The JDK 1.2 support the dynamic class loading. The EJB container implements the EJBHome and EJBObject classes. For every request from a unique client, does the container create a separate instance of the generated EJBHome and EJBObject classes? - The EJB container maintains an instance pool. The container uses these instances for the EJB Home reference irrespective of the client request. while refering the EJB Object classes the container creates a separate instance for each client request. The instance pool maintainence is up to the implementation of the container. If the container provides one, it is available otherwise it is not mandatory for the provider to implement it. Having said that, yes most of the container providers implement the pooling functionality to increase the performance of the application server. The way it is implemented is again up to the implementer.

305) What is the advantage of putting an Entity Bean instance from the Ready State to Pooled state?
305) The idea of the Pooled State is to allow a container to maintain a pool of entity beans that has been created, but has not been yet synchronized or assigned to an EJBObject. This mean that the instances do represent entity beans, but they can be used only for serving Home methods (create or findBy), since those methods do not relay on the specific values of the bean. All these instances are, in fact, exactly the same, so, they do not have meaningful state. Jon Thorarinsson has also added: It can be looked at it this way: If no client is using an entity bean of a particular type there is no need for cachig it (the data is persisted in the database). Therefore, in such cases, the container will, after some time, move the entity bean from the Ready State to the Pooled state to save memory. Then, to save additional memory, the container may begin moving entity beans from the Pooled State to the Does Not Exist State, because even though the bean's cache has been cleared, the bean still takes up some memory just being in the Pooled State.

306) Can a Session Bean be defined without ejbCreate() method?
306) The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method. However, the J2EE spec is explicit: the home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments. Stateful Session Beans can have arguments (more than one create method) stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition. You need a reference to your EJBObject to startwith. For that Sun insists on putting a method for creating that reference (create method in the home interface). The EJBObject does matter here. Not the actual bean.

307) Is it possible to share an HttpSession between a JSP and EJB? What happens when I change a value in the HttpSession from inside an EJB?
307) You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable.This has to be consider as passed-by-value, that means that it's read-only in the EJB. If anything is altered from inside the EJB, it won't be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references. While it IS possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice (1) in terms of object oriented design. This is because you are creating an unnecessary coupling between back-end objects (ejbs) and front-end objects (HttpSession). Create a higher-level of abstraction for your ejb's api. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your ejb needs to support a non-http-based client. This higher level of abstraction will be flexible enough to support it. (1) Core J2EE design patterns (2001)

308) Is there any way to read values from an entity bean without locking it for the rest of the transaction (e.g. read-only transactions)?
308) We have a key-value map bean which deadlocks during some concurrent reads. Isolation levels seem to affect the database only, and we need to work within a transaction. - The only thing that comes to (my) mind is that you could write a group accessor - a method that returns a single object containing all of your entity bean's attributes (or all interesting attributes). This method could then be placed in a Requires New transaction. This way, the current transaction would be suspended for the duration of the call to the entity bean and the entity bean's fetch/operate/commit cycle will be in a separate transaction and any locks should be released immediately. Depending on the granularity of what you need to pull out of the map, the group accessor might be overkill.

309) What is the difference between a Coarse Grained Entity Bean and a Fine Grained Entity Bean?
309) A fine grained entity bean is pretty much directly mapped to one relational table, in third normal form. A coarse grained entity bean is larger and more complex, either because its attributes include values or lists from other tables, or because it owns one or more sets of dependent objects. Note that the coarse grained bean might be mapped to a single table or flat file, but that single table is going to be pretty ugly, with data copied from other tables, repeated field groups, columns that are dependent on non-key fields, etc. Fine grained entities are generally considered a liability in large systems because they will tend to increase the load on several of the EJB server's subsystems (there will be more objects exported through the distribution layer, more objects participating in transactions, more skeletons in memory, more EJB Objects in memory, etc.)

310) What is EJBDoclet?
310) EJBDoclet is an open source JavaDoc doclet that generates a lot of the EJB related source files from custom JavaDoc comments tags embedded in the EJB source file.

JPS pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests. javax.servlet.jsp package defines two classes: JSPPage HttpJspPage These classes defines the interface for the compiled JSP page. These interfaces are: jspInit() jspDestroy() _jspService(HttpServletRequest request,HttpServletResponse response) In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.

Mediator pattern:
When a class is made up of a number of classes, the logic and comutation is divided among these classes. The more isolated classes are developed in the program, the more the complex it becomes

Class diagrams A Class diagram gives an overview of a system by showing its classes and the relationships among them. Class diagrams are static -- they display what interacts but not what happens when they do interact. association
A relationship between instances of the two classes. There is an association between two classes if an instance of one class must know about the other in order to perform its work. In a diagram, an association is a link connecting two classes. aggregation -- an association in which one class belongs to a collection. An aggregation has a diamond end pointing to the part containing the whole. In our diagram, Order has a collection of OrderDetails. Aggregation [...] is the typical whole/part relationship. This is exactly the same as an association with the exception that instances cannot have cyclic aggregation relationships (i.e. a part cannot contain its whole).

generalization -- an inheritance link indicating one class is a superclass of the other. A generalization has a triangle pointing to the superclass. Payment is a superclass of Cash, Check, and Credit.

Composition
Composition is a strong association in which the part can belong to only one whole. Composition is a stronger form of aggregation where the whole and parts have coincident lifetimes, and it is very common for the whole to manage the lifecycle of its parts Composition is exactly like Aggregation except that the lifetime of the 'part' is controlled by the 'whole'. This control may be direct or transitive. That is, the 'whole' may take direct responsibility for creating or destroying the 'part', or it may accept an already created part, and later pass it on to some other whole that assumes responsibility for it.

Use case
Use case diagrams describe what a system does from the standpoint of an external observer. The emphasis is on what a system does rather than how. Use case diagrams are closely connected to scenarios. A scenario is an example of what happens when someone interacts with the system.

sequence diagram
A sequence diagram is an interaction diagram that details how operations are carried out -- what messages are sent and when. Sequence diagrams are organized according to time. The time progresses as you go down the page. The objects involved in the operation are listed from left to right according to when they take part in the message sequence.


teacherone learning
teacherone provides educational and learning material, printable worksheet, online worksheet for elementary, middle and high school.
teacherone provides material for training only. We do not warrant the correctness of its contents. The risk from using it lies entirely with the user. teacherone is not liable for any damage or loss.
All/any other trademarks are property of their respective owners