Java FAQs Final
Java FAQs Final
Nazar Babu 1
Java Technoloies
Nazar Babu 2
Java Technoloies
CONTENTS
Core Java 4
Exception Handling 20
Multi Threading 23
Collection Framework 26
JDBC Concept 33
All Packages 41
Servlets 47
JSP 68
Struts 80
Hibernate FAQs 89
Nazar Babu 3
Java Technoloies
CORE JAVA
Q) What is difference between Java and C++?
A) (i) Java does not support pointers. Pointers are inherently insecure and
troublesome. Since pointers do not exist in Java. (ii) Java does not support operator
overloading. (iii) Java does not perform any automatic type conversions that result in
a loss of precision (iv) All the code in a Java program is encapsulated within one or
more classes. Therefore, Java does not have global variables or global functions. (v)
Java does not support multiple inheritance.
Java does not support destructors, but rather, add the finalize() function. (vi) Java
does not have the delete operator. (vii) The << and >> are not overloaded for I/O
operations
Q) Opps concepts
Polymorphism
Ability to take more than one form, in java we achieve this using Method Overloading
(compile time polymorphism), Method overriding (runtime polymorphism)
Inheritance
Is the process by which one object acquires the properties of another object. The
advantages of inheritance are reusability of code and accessibility of variables and
methods of the super class by subclasses.
Encapsulation
Wrapping of data and function into a single unit called encapsulation.
Ex:- all java programs.
(Or)
Nothing but data hiding, like the variables declared under private of a particular class
are accessed only in that class and cannot access in any other the class. Or Hiding
the information from others is called as Encapsulation. Or Encapsulation is the
mechanism that binds together code and data it manipulates and keeps both safe
from outside interference and misuse.
Abstraction
Nothing but representing the essential futures without including background details.
Dynamicbinding
Code associated with a given procedural call is not known until the time of the
call at runtime. Dynamic binding is nothing but late binding.
Q) Object creation?
Object is constructed either on a memory heap or on a stack.
Memory heap
generally the objects are created using the new keyword. Some heap memory is
allocated to this newly created object. This memory remains allocated throughout
the life cycle of the object. When the object is no more referred, the memory
allocated to the object is eligible to be back on the heap.
Nazar Babu 4
Java Technoloies
Stack
During method calls, objects are created for method arguments and method
variables. These objects are created on stack.
Q) System.out.println()
println() is a methd of java.io.printWriter.
“out” is an instance variable of java.lang.System class.
Q) Default Values
Q) Byte code & JIT compiler & JVM & JRE & JDK
Byte code is a highly optimized set of instructions. JVM is an interpreter for byte
code. Translating a java program into byte code helps makes it much easier to run
a program in a wide variety of environment.
Nazar Babu 5
Java Technoloies
JDK is bundle of software that you can use to develop Java based software, Tools
provided by JDK is
(i) javac – compiler (ii) java – interpretor (iii) jdb – debugger (iv) javap -
Disassembles
(v) appletviewer – Applets (vi) javadoc - documentation generator (vii) javah -
'C' header file generator
Q) Wrapper classes
Primitive data types can be converted into objects by using wrapper classes. These
are java.lang.package.
Q) Constructor
The automatic initialization is performed through the constructor, constructor
has same name has class name. Constructor has no return type not even void. We
can pass the parameters to the constructor. this() is used to invoke a constructor of
the same class. Super () is used to invoke a super class constructor. Constructor is
called immediately after the object is created before the new operator completes.
Nazar Babu 6
Java Technoloies
Constructor can use the access modifiers public, protected, private or have no
access modifier
Constructor can not use the modifiers abstract, static, final, native,
synchronized or strictfp
Constructor can be overloaded, we cannot override.
You cannot use this() and Super() in the same constructor.
Class A(
A(){
System.out.println(“hello”);
}}
Class B extends A {
B(){
System.out.println(“friend”);
}}
Class print {
Public static void main (String args []){
B b = new B();
}
o/p:- hello friend
Constructor Method
Use to instance of a class Grouping java statement
No return type Void (or) valid return type
Same name as class name As a name except the class
method name, begin with lower
case.
“This” refer to another constructor Refers to instance of class
in the same class
“Super” to invoke the super class Execute an overridden method in
constructor the super class
“Inheritance” cannot be inherited Can be inherited
We can “overload” but we cannot Can be inherited
“overridden”
Will automatically invoke when an Method has called explicitly
object is created
Q) Garbage collection
G.C is also called automatic memory management as JVM automatically
removes the unused variables/objects (value is null) from the memory. User
program cann't directly free the object from memory, instead it is the job of the
garbage collector to automatically free the objects that are no longer referenced by a
program. Every class inherits finalize() method from java.lang.Object, the
finalize() method is called by garbage collector when it determines no more
references to the object exists. In Java, it is good idea to explicitly assign null into a
Nazar Babu 7
Java Technoloies
variable when no more in use, calling System.gc() and Runtime.gc(), JVM tries to
recycle the unused objects, but there is no guarantee when all the objects will
garbage collected. Garbage collection is a low-priority thread.
G.C is a low priority thread in java, G.C cannot be forced explicitly. JVM may do
garbage collection if it is running short of memory. The call System.gc() does NOT
force the garbage collection but only suggests that the JVM may make an effort to do
garbage collection.
Finally: - Finally create a block of code that will be executed after try catch block
has completed. Finally block will execute whether or not an exception is thrown. If an
exception is thrown, the finally block will execute even if no catch statement match
the exception. Any time a method is about to return to the caller from inside
try/catch block, via an uncaught exception or an explicit return statement, the finally
clause is also execute.
Using System.exit() in try block will not allow finally code to execute
Finalize: - some times an object need to perform some actions when it is going to
destroy, if an object holding some non-java resource such as file handle (or) window
character font, these resources are freed before the object is going to destroy.
Nazar Babu 8
Java Technoloies
Q) Superclass & Subclass
A super class is a class that is inherited whereas subclass is a class that does
the inheriting
The access modifier for the overriding method may not be more restrictive
than the access modifier of the superclass method.
The throws clause of the overriding method may only include exceptions that
can be thrown by the superclass method, including its subclasses.
Nazar Babu 9
Java Technoloies
System.out.println("in Child");
}
}
class Test{
public static void main(String[] args){
Parent p = new Child();
Child c = new Child();
System.out.print("i="+p.i+" ");
p.amethod ();
System.out.print("i="+c.i+" ");
c.amethod();
}
}
o/p: - i=0 in Child i=10 in Child
Q) Final variable
Once to declare a variable as final it cannot occupy memory per instance
basis.
Q) Static block
Static block which exactly executed exactly once when the class is first loaded
into JVM. Before going to the main method the static block will execute.
When a member is declared a static it can be accessed before any object of its
class are created.
Instance variables declared as static are essentially global variables.
If you do not specify an initial value to an instance & Static variable a default
value will be assigned automatically.
Methods declared as static have some restrictions they can access only static
data, they can only call other static data, they cannot refer this or super.
Static methods cant be overriden to non-static methods.
Static methods is called by the static methods only, an ordinary method can call
the static methods, but static methods cannot call ordinary methods.
Static methods are implicitly "final", because overriding is only done based on the
type of the objects
They cannot refer “this” are “super” in any way.
Q) Class variable & Instance variable & Instance methods & class methods
Instance variable variables defined inside a class are called instance variables with
multiple instance of class, each instance has a variable stored in separate memory
location.
Nazar Babu 10
Java Technoloies
Class variables you want a variable to be common to all classes then we crate
class variables. To create a class variable put the “static” keyword before the
variable name.
Q) Conversions
String to Int Conversion: -
int I = integer.valueOf(“24”).intValue();
int x = integer.parseInt(“433”);
float f = float.valueOf(23.9).floatValue();
Q) Super()
Super() always calling the constructor of immediate super class, super() must
always be the first statements executed inside a subclass constructor.
A) 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. e.g., 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
Nazar Babu 11
Java Technoloies
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.
Q) Abstract Class
Any class that contain one are more abstract methods must also be declared
as an abstract, there can be no object of an abstract class, we cannot directly
instantiate the abstract classes. A.C can contain concrete methods.
Any sub class of an Abstract class must either implement all the abstract methods
in the super class or be declared itself as Abstract.
Compile time error occur if an attempt to create an instance of an Abstract class.
You cannot declare “abstract constructor” and “abstract static method”.
An “abstract method” also declared private, native, final, synchronized,
strictfp, protected.
Abstract class can have static, final method (but there is no use).
Abstract class have visibility public, private, protected.
By default the methods & variables will take the access modifiers is <default>,
which is accessibility as package.
An abstract method declared in a non-abstract class.
An abstract class can have instance methods that implement a default behavior.
A class can be declared abstract even if it does not actually have any abstract
methods. Declaring such a class abstract indicates that the implementation is
somehow incomplete and is meant to serve as a super class for one or more
subclasses that will complete the implementation.
A class with an abstract method. Again note that the class itself is declared
abstract, otherwise a compile time error would have occurred.
Nazar Babu 12
Java Technoloies
Abstract class A{
Public abstract callme();
Void callmetoo(){
}
}
class B extends A(
void callme(){
}
}
class AbstractDemo{
public static void main(string args[]){
B b = new B();
b.callme();
b.callmetoo();
}
}
Nazar Babu 13
Java Technoloies
Why Interfaces?
“ one interface multiple methods “ signifies the polymorphism concept.
Interface A
{
final static float pi = 3.14f;
}
class B implements A
{
public float compute(float x, float y) {
return(x*y);
}
}
class test{
public static void main(String args[])
{
A a = new B();
a.compute();
}
}
Nazar Babu 14
Java Technoloies
Q) Diff Interface & Abstract Class?
A.C may have some executable methods and methods left unimplemented.
Interface contains no implementation code.
An A.C can have nonabstract methods. All methods of an Interface are abstract.
An A.C can have instance variables. An Interface cannot.
An A.C must have subclasses whereas interface can't have subclasses
An A.C can define constructor. An Interface cannot.
An A.C can have any visibility: public, private, protected. An Interface visibility
must be public (or) none.
An A.C can have instance methods that implement a default behavior. An
Interface can only declare constants and instance methods, but cannot implement
default behavior.
Nazar Babu 15
Java Technoloies
Q) Serialization
Serialization is the process of writing the state of the object to a byte stream,
this is useful when ever you want to save the state of your programme to a
persistence storage area.
Q) Synchronization
Synchronization is a process of controlling the access of shared resources by
the multiple threads in such a manner that only one thread can access one resource
at a time. (Or) When 2 are more threads need to access the shared resources they
need to some way ensure that the resources will be used by only one thread at a
time. This process which is achieved is called synchronization.
Q) Monitor
A monitor is a mutex, once a thread enter a monitor, all other threads must
wait until that thread exist the monitor.
Nazar Babu 16
Java Technoloies
(sb1==sb2); F (s1.equals(s2)); T
(sb1.equals(sb2)); F ((s1==s2)); T
(sb1.equals(ss1)); F (s3.equals(s4)); T
((s3==s4)); F
String s1 = "abc";
String s2 = new String("abc");
s1 == s2 F
s1.equals(s2)) T
URL is to identify a resource in a network, is only used to read something from the
network.
URL url = new URL(protocol name, host name, port, url specifier)
Q) Runtime class
Runtime class encapsulate the run-time environment. You cannot instantiate
a Runtime object. You can get a reference to the current Runtime object by calling
the static method Runtime.getRuntime()
Runtime r = Runtime.getRuntime()
Long mem1;
Mem1 = r.freeMemory();
Mem1 = r.totalMemory();
Nazar Babu 17
Java Technoloies
Q) System class
System class hold a collection of static methods and variables. The standard
input, output, error output of the java runtime are stored in the in, out, err
variables.
Q) Native Methods
Native methods are used to call subroutine that is written in a language other
than java, this subroutine exist as executable code for the CPU.
Q) Cloneable Interface
Any class that implements the cloneable interface can be cloned, this
interface defines no methods. It is used to indicate that a class allow a bit wise copy
of an object to be made.
Q) Clone
Generate a duplicate copy of the object on which it is called. Cloning is a
dangerous action.
Q) Comparable Interface
Classes that implements comparable contain objects that can be compared in
some meaningful manner. This interface having one method compare the invoking
object with the object. For sorting comparable interface will be used.
Ex:- int compareTo(Object obj)
Q) Class
Class encapsulate the run-time state of an object or interface. Methods in this
class are
Q) java.lang.Reflect (package)
Reflection is the ability of software to analyse it self, to obtain information
about the field, constructor, methods & modifier of class. You need this information
to build software tools that enables you to work with java beans components.
Q) InstanceOf
Instanceof means by which your program can obtain run time type
information about an object.
Ex:- A a = new A();
a.instanceOf A;
Nazar Babu 18
Java Technoloies
Q) Java lack pointers how do I implements classic pointer structures like
linked list?
A) Using object reference.
Q) java. Exe
Micro soft provided sdk for java, which includes “jexegentool”. This converts class file
into a “.Exec” form. Only disadvantage is user needs a M.S java V.M installed.
Nazar Babu 19
Java Technoloies
Exception
Handling
Object
Throwable
Error Exception
Bound.E
ArrayIndexoutOfBound.E
StirngIndexoutOfBound
Nazar Babu 20
Java Technoloies
Q) What happens if a try-catch-finally statement does not have a catch
clause to handle an exception that is thrown within the body of the try
statement?
The exception propagates up to the next higher level try-catch statement (if any) or
results in the program's termination.
OutOfMemoryError --> Signals that JVM has run out of memory and that the
garbage collector is unable to claim any more free memory.
StackOverFlow --> Signals that a stack O.F in the interpreter.
ArrayIndexOutOfbound --> For accessing an array element by providing an
index values <0 or > or equal to the array size.
StringIndexOutOfbound --> For accessing character of a string or string
buffer with index values <0 or > or equal to the array size.
Arithmetic Exception --> such as divide by zero.
ArrayStore Exception --> Assignment to an array element of an incompatible
types.
ClasscastException --> Invalid casting.
IllegalArgument Exception --> Illegal argument is used to invoke a method.
Nullpointer Exception --> If attempt to made to use a null object.
NumberFormat Exception --> Invalid conversition of string to numeric format.
ClassNotfound Exception --> class not found.
Instantion Exception --> Attempt to create an object of an Abstract class or
Interface.
NosuchField Exception --> A request field does not exist.
NosuchMethod Exception --> A request method does not exist.
Nazar Babu 21
Java Technoloies
Q) Methods in Exceptions?
A) getMessage(), toString(), printStackTrace(), getLocalizedMessage(),
Nazar Babu 22
Java Technoloies
Multi
Threading
Q) What threads will start when you start the java program?
A) Finalizer, Main, Reference Handler, Signal dispatcher.
Q) Thread
Thread is a smallest unit of dispatchable code.
Q) Yield( )
Yield method temporarily stop the callers thread and put at the end of queue
to wait for another turn to be executed. It is used to make other threads of the same
priority have the chance to run.
Thread.sleep(milliseconds);
Thread.sleep(milliseconds, nanoseconds);
Q) Multi Threading
Multithreading is the mechanism in which more than one thread run
independent of each other within the process.
Q) Daemon Thread
Daemon thread is one which serves another thread, it has no other role
normally a daemon thread carry some background program. When daemon thread
remains the program exist.
Q) Thread Priority
Nazar Babu 23
Java Technoloies
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Q) Thread Priorities
Q) What are the different levels of locking using ‘Synchronize’ key word?
A) Class level, method level, object level, block level
Nazar Babu 24
Java Technoloies
Q) Which attribute are thread safe?
Multi Threaded Single threaded Model
Objective Model
Local variables Y Y
Instance variables N Y
Class variables N N
Request attributes Y Y
Session attributes N N
Context attributes N N
Nazar Babu 25
Java Technoloies
Collections
Frame Work
Q)
Collection Collection Legacy Legacy
classes Interfaces classes interface
Abstract collection Collection Dictionary Enumerator
Abstract List List Hash Table
Abstract Set Set Stack
Array List Sorted Set Vector
Linked List Map Properties
Hash set Iterator
Tree Set
Hash Map
Tree Map
Abstract
Sequential List
Collection Classes
Abstract List Extends Abstract collection & Implements List Interface. A.L
allow “random access”.
Methods>> void add (int index, Object element), boolean add(Object o), boolean
addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int
index), void clear(), Iterator iterator().
Array List Array List extends AbstractList and implements the List interface.
ArrayList is a variable length of array of object references, ArrayList support
dynamic array that grow as needed. A.L allow rapid random access to element
but slow for insertion and deletion from the middle of the list. It will allow
duplicate elements. Searching is very faster.
A.L internal node traversal from the start to the end of the collection is
significantly faster than Linked List traversal.
A.L is a replacement for Vector.
Methods>>void add (int index, Object element), boolean add(Object o), boolean
addAll(Collection c), boolean addAll(int index, Collection c), Object remove(int
index), void clear(), object get(int index), int indexOf(Object element), int
latIndexOf(Object element), int size(), Object [] toArray().
Nazar Babu 26
Java Technoloies
first node of the list. Each subsequent node is accessed via a reference to the
first node of the list. Each subsequent node is accessed via the link-reference
number stored in the previous node.
Tree Set Extends Abstract Set & Implements Set interface. Objects are stored
in sorted, ascending order. Access and retrial times are quite fast. It will not
allow duplicate elements
Hash Map Extends Abstract Map and implements Map interface. H.M does not
guarantee the order of elements, so the order in which the elements are added to
a H.M is not necessary the order in which they are ready by the iterate. H.M
permits only one null values in it while H.T does not
Collection Interfaces
Methods >> boolean add(Object obj), boolean addAll(c), int Size(), Object[]
toArray(), Boolean isEmpty(), Object [] toArray(), void clear().Collection c),
Iterator iterator(),
boolean remove(Object obj), boolean removeAll(Collection
Exceptions >> UnSupportedPointerException, ClassCastException.
List List will extend Collection Interface, list stores a sequence of elements
that can contain duplicates, elements can be accessed their position in the list
using a zero based index, (it can access objects by index).
Nazar Babu 27
Java Technoloies
Methods >> void add(int index, Object obj), boolean addAll(int index, Collection
c), Object get(int index), int indexOf(Object obj), int lastIndexOf(Object obj),
ListIterator iterator(), Object remove(int index), Object removeAll(Collection c),
Object set(int index, Object obj).
Set Set will extend Collection Interface, Set cannot contain duplicate
elements. Set stored elements in an unordered way. (it can access objects by
value).
Sorted Set Extends Set to handle sorted sets, Sorted Set elements will be in
ascending order.
Methods >> Object last(), Object first(), compactor compactor().
Exceptions >> NullPointerException, ClassCastException,
NoSuchElementException.
Map Map maps unique key to value in a map for every key there is a
corresponding value and you will lookup the values using keys. Map cannot
contain duplicate “key” and “value”. In map both the “key” & “value” are
objects.
Methods >> Object get(Object k), Object put(Object k, Object v), int size(),
remove(Object object), boolean isEmpty()
Before accessing a collection through an iterator you must obtain one if the
collection classes provide an iterator() method that returns an iterator to the start
of the collection. By using iterator object you can access each element in the
collection, one element at a time.
List Iterator List Iterator gives the ability to access the collection, either
forward/backward direction
Legacy Classes
Nazar Babu 28
Java Technoloies
Hash Table HashTable stores key/value pairs in hash table, HashTable is
synchronized when using hash table you have to specify an object that is used
as a key, and the value that you want to linked to that key. The key is then
hashed, and the resulting hash code is used as the index at which the value is
stored with the table. Use H.T to store large amount of data, it will search as fast
as vector. H.T store the data in sequential order.
Stack is a sub class of vector, stack includes all the methods defined by vector
and adds several of its own.
Vector Vector holds any type of objects, it is not fixed length and vector is
synchronized. We can store primitive data types as well as objects. Default
length of vector is up to 10.
Methods>> final void addElement(Object element), final int size(), final int
capacity(), final boolean removeElementAt(int index), final void
removeAllElements().
Legacy Interfaces
Enumeration Define methods by which you can enumerate the
elements in a collection of objects. Enumeration is synchronized.
Q) Which is the preferred collection class to use for storing database result sets?
A) LinkedList is the best one, benefits include:
1. Retains the original retrieval order. 2. Has quick insertion at the head/tail 3.
Doesn't have an internal size limitation like a Vector where when the size is exceeded
a new internal structure is created. 4. Permits user-controlled synchronization unlike
the pre-Collections Vector which is always synchronized
ResultSet result = stmt.executeQuery("...");
List list = new LinkedList();
while(result.next()) {
list.add(result.getString("col"));
}
If there are multiple columns in the result set, you'll have to combine them into their
own data structure for each row. Arrays work well for that as you know the size,
though a custom class might be best so you can convert the contents to the proper
type when extracting from databse, instead of later.
Nazar Babu 29
Java Technoloies
certain application, the time and space cost is even higher than other data structures
(array, linked list, or tree).
Hashtable has two parameters that affect its efficiency: its capacity and its load
factor. The load factor should be between 0.0 and 1.0. When the number of entries
in the hashtable exceeds the product of the load factor and the current capacity, the
capacity is increased by calling the rehash method. Larger load factors use memory
more efficiently, at the expense of larger expected time per lookup.
If many entries are to be put into a Hashtable, creating it with a sufficiently large
capacity may allow the entries to be inserted more efficiently than letting it perform
automatic rehashing as needed to grow the table.
Q) Array
Array of fixed length of same data type; we can store primitive data types as
well as class objects.
Arrays are initialized to the default value of their type when they are created, not
declared, even if they are local variables
List Iterator
It is an interface, List Iterator extends Iterator to allow bi-directional traversal
of a list and modification of the elements. Methods are ‘hasNext()’, ‘ hasPrevious()’.
Nazar Babu 30
Java Technoloies
// Convert back to a collection
Collection c2 = new HashSet();
for(int i = 0; i < array.length; i++) {
c2.add(array[i]);
}
Nazar Babu 31
Java Technoloies
}
// POST: Collection only has parameters that start with -
Nazar Babu 32
Java Technoloies
JDBC
Nazar Babu 33
Java Technoloies
Q) JDBC Drivers
Q) JDBC connection
import java.sql.*;
public class JDBCSample {
public static void main(java.lang.String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("Unable to load Driver Class");
return;
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:companydb","", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME FROM EMPLOYEES");
while(rs.next()) {
System.out.println(rs.getString("FIRST_NAME"));
}
rs.close();
stmt.close();
con.close();
}
Nazar Babu 34
Java Technoloies
catch (SQLException se) {
System.out.println("SQL Exception: " + se.getMessage());
}
}
}
Q) Resultset Types
rs.beforeFirst() goto 1st record
rs.afterLast() goto last record
isFirst() / isLast()
res.absolute(4) will got 4th record in result set.
rs.deleteRow()
rs.updateRow(3,88) value in column 3 of resultset is set to 88.
rs.updateFloat()
rs.relative(2)
Q) Transactional Savepoints
Statement stmt = conn.createStatement ();
Int rowcount = stmt.executeUpdate ("insert into etable (event) values ('TMM')");
Int rowcount = stmt.executeUpdate ("insert into costs (cost) values (45.0)");
Savepoint sv1 = conn.setSavePoint ("svpoint1"); // create save point for inserts
Int rowcount = stmt.executeUpdate ("delete from employees");
Conn.rollback (sv1); // discard the delete statement but keep the inserts
Conn.commit; // inserts are now permanent
Nazar Babu 35
Java Technoloies
Q Retreiving / Storing / Updating Array of Objects
Array a = rs.getArray(1);
Pstmt.setArray(2, member_array);
Rs.updateArray(“last_num”,num);
Q) Batch Updates
CallableStatement stmt = con.prepareCall(“{call employeeInfo (?)}”);
stmt.addBatch("INSERT INTO employees VALUES (1000, 'Joe Jones')");
stmt.addBatch("INSERT INTO departments VALUES (260, 'Shoe')");
// submit a batch of update commands for execution
int[] updateCounts = stmt.executeBatch();
Q) Multiple Resultset
A) The methods getMoreResults, getUpdateCount, and getResultSet can be used to
retrieve all the results.
CallableStatement cstmt = connection.prepareCall(procCall);
boolean retval = cstmt.execute();
if (retval == false) {
} else {
ResultSet rs1 = cstmt.getResultSet();
retval = cstmt.getMoreResults(Statement.KEEP_CURRENT_RESULT);
if (retval == true) {
ResultSet rs2 = cstmt.getResultSet();
rs2.next();
rs1.next();
}
}
CLOSE_ALL_RESULTS All previously opened ResultSet objects should
be closed when calling getMoreResults().
CLOSE_CURRENT_RESULT The current ResultSet object should be closed
when calling getMoreResults().
KEEP_CURRENT_RESULT The current ResultSet object should not be
closed when calling getMoreResults().
Nazar Babu 36
Java Technoloies
ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("SELECT COLUMN_1, COLUMN_2 FROM
TABLE_NAME");
rs.afterLast();
while (srs.previous()) {
String name = rs.getString("COLUMN_1");
float salary = rs.getFloat("COLUMN_2");
rs.absolute(4); // cursor is on the fourth row
int rowNum = rs.getRow(); // rowNum should be 4
rs.relative(-3);
int rowNum = rs.getRow(); // rowNum should be 1
rs.relative(2);
int rowNum = rs.getRow(); // rowNum should be 3
//...
}
Delete: -
uprs.absolute(5);
uprs.deleteRow(); // will delete row 5.
Nazar Babu 37
Java Technoloies
Q) Does the JDBC-ODBC Bridge support multiple concurrent open
statements per connection?
A) No. You can open only one Statement object per connection when you are using
the JDBC-ODBC Bridge.
Q) Statements in JDBC
Nazar Babu 38
Java Technoloies
Q) In which interface the methods commit() & rollback() savepoint() defined ?
A) Java.sql.Connection interface
Q) ResultSetMetaData
It is used to find out the information of a table in a data base.
ResultSet rs = stmt.executeQuery("SELECT * FROM "+ table);
ResultSetMetaData rsmd = rs.getMetaData();
Q) Database MetaData
You need some information about the “data base” & “dictionary” we use this .To find
out tables, stored procedure names, columns in a table, primary key of a table we
use this, this is the largest interface in java.sql package
Q) SQL Warnings
Warnings may be retrieved from Connection, Statement, and ResultSet objects.
Trying to retrieve a warning on a connection after it has been closed will cause an
exception to be thrown. Similarly, trying to retrieve a warning on a statement after it
has been closed or on a result set after it has been closed will cause an exception to
be thrown. Note that closing a statement also closes a result set that it might have
produced.
Connection.getWarnings()
Statement.getWarnings(),
ResultSet.getWarnings(), Serialized Form
Nazar Babu 39
Java Technoloies
System.out.println(warning.getErrorCode());
warning = warning.getNextWarning();
}
}
Q) Procedure
Procedure is a subprogram will perform some specific action; sub programs
are naming PL/SQL blocks that can take parameters to be invoked.
create (or) replace procedure procedure-name (id IN INTEGER , bal IN OUT FLOAT)
IS
BEGIN
select balance into bal from accounts where account_id = id;
Bal: = bal + bal * 0.03;
Update accounts set balance = bal where account_id = id;
END;
Q) Trigger
Trigger is a stored PL/SQL block associated with a specific database table.
Oracle executes triggers automatically when ever a given SQL operation effects the
table, we can associate 12 data base triggers with in a given table.
Create/Replace trigger before Insert (or) Delete (or) Update on emp for each row
Begin
Insert into table-name values(:empno; :name)
end
Retrieve Image
Statement st = con.CreateStatement();
ResultSet rs = st.executeQuery(“select * from img”);
Rs.next();
InputStream is = rs.getBinaryStream(1);
FileOutPutStream fos = new FileOutPutStream(“g2.gif”);
Int ch;
While((ch=is.read(1))!=!-1)
{
fos.write(ch);
}
Nazar Babu 40
Java Technoloies
All Packages
Q) Thread Class
Methods: -
getName() run()
getPriority() Sleep()
isAlive() Start()
join()
Q) Object class
All other classes are sub classes of object class, Object class is a super class
of all other class.
Methods: -
void notify() void notifyAll()
Object clone() Sting toString()
boolean equals(Object void wait()
object)
void finalize() void wait(long milliseconds, int
nanoseconds)
int hashcode()
Q) throwable class
Methods: -
String getMessage() Void printStackTrace()
String toString() Throwable fillInStackTrace()
Q) Javax.servlet Package
Interfaces Classes Exceptions
Servlet GenericServlet ServletExceptio
n
ServletConfig ServletInputStream UnavaliableExc
eption
ServletContext ServletOutputStream
ServletRequest ServletContextAttribut
eEvent
ServletResponse
SingleThreadModel
ServletContextListener
ServletContextAttributeList
ener
ServletContextInitialization
parameters
ServletRequestAttributeList
ener
ServletRequestListner
Filter
FilterChain
FilterConfig
RequestDispatcher
Nazar Babu 41
Java Technoloies
GenericServlet (C) public void destroy();
public String getInitParameter(String name);
public Enumeration getInitParameterNames();
public ServletConfig getServletConfig();
public ServletContext getServletContext();
public String getServletInfo();
public void init(ServletConfig config) throws ServletException;
public void log(String msg);
public abstract void service(ServletRequest req, ServletResponse
res)
ServletInputStream (C) public int readLine(byte b[], int off, int len)
Nazar Babu 42
Java Technoloies
RequestDispatcher getRequestDispatcher(String path);
public int getLocalPort(); // servlet 2.4
public int getRemotePort(); // servlet 2.4
public String getLocalName(); // servlet 2.4
public String getLocalAddr(); // servlet 2.4
Q) Javax.servlet.Http Package
Interfaces Classes Exceptions
HttpServletRequest Cookies ServletException
HttpServletResponse HttpServlet (Abstarct UnavaliableExcep
Class) tion
HttpSession HttpUtils
HttpSessionListener HttpSessionBindingEven
t
HttpSessionActivationLis
tener
HttpSessionAttributeList
ener
HttpSessionBindingListe
ner
HttpSessionContext
(deprecated)
Filter
ServletContextInitilazation parameters
Nazar Babu 43
Java Technoloies
public void setMaxAge(int expiry);
public void setPath(String uri);
public void setValue(String newValue);
public void setVersion(int v);
Nazar Babu 44
Java Technoloies
public abstract void setDateHeader(String header,
long value);
public void setStatus();
HttpSession (I) public abstract long getCreationTime();
public abstract String getId();
public setAttribute(String name, Object value);
public getAttribute(String name, Object value);
public remove Attribute(String name, Object value);
public abstract long getLastAccessedTime();
public abstract HttpSessionContext getSessionContext();
public abstract Object getValue(String name);
public abstract String[] getValueNames();
public abstract void invalidate();
public abstract boolean isNew();
public abstract void putValue(String name, Object value);
public abstract void removeValue(String name);
public setMaxInactiveIntervel();
HttpSessionBindingListener (I)
public void
HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)
public void
HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent event)
HttpSessionActivationListener (I)
public void sessionDidActivate(HttpSessionEvent event)
public void sessionWillpassivate(HttpSessionEvent event)
Filter (i)
public void doFilter (ServletRequest request, ServletResponse response,
FilterChain chain)
public FilterConfig getFilterConfig()
public void setFilterConfig (FilterConfig filterConfig)
Q) java.sql Package
Interfaces Classes Exceptions
Connection DriverManager
CallableStatement Date ClassNotFoundException
Driver TimeStamp Instantiation Exception
Nazar Babu 45
Java Technoloies
PreparedStatement Time
ResultSet Types
ResultSetMetaData SQL Exception, SQL
Warnings
Statement
DatabaseMetaData
Array
ParameterMetaData
Clob, Blob
SQLInput, SQLOutput,
SQLPermission
Savepoint
Q) javax.sql Package
Interfaces Classes Exceptions
ConnectionEventListener ConnectionEvent
ConnectionPoolDataSource RowsetEvent
DataSource
PooledConnection
RowSet
RowSetListener
RowSetMetaDate
RowSetReader/Writer
XAConnection
XADataSource
Q) java.lang Package
Interfaces Classes Exceptions
Cloneable Double, Float, Long, ArithmeticException,
Integer, Short, Byte, ArrayIndexOutOfBoundOf.E,
Boolean, Character, ClassCast.E, ClassNotFound.E
Runnable Class, ClassLoader IlleAcess.E, IllegalArgument.E
Comparable Process, RunTime, Void IllegalSate.E, NullPointer.E
String, StringBuffer NoSuchField.E,
NoSuchMethod.E
Thread, ThreadGroup NumberFormat.E
Q) java.IO Package
Interfaces Classes Exceptions
DataInputstream BufferInputstream,
BufferOutputStream
DataOutputstream BufferReader, BufferWriter
ObjectInputStream ByteArrayInputStream,
ByteArrayOutputstream
ObjectOutputstrea CharacterarrayReader,
m CharacterArayWriter
Serializable DataInputStream,
DataOutputStream
Externializable Filereader, FileWriter
ObjectInputStream,
ObjectOutputStream
Nazar Babu 46
Java Technoloies
SERVLETs
Class path: -
set path= c:\j2sdk1.4.2\bin
set classpath= c:\ j2sdk1.4.2\lib\tools.jar;c:\servlet.jar
C:\Tomcat5\bin\startup.bat shortcut
Q) Servlet
Servlet is server side component, a servlet is small plug gable extension to
the server and servlets are used to extend the functionality of the java-enabled
server. Servlets are durable objects means that they remain in memory specially
instructed to be destroyed. Servlets will be loaded in the Address space of web
server.
Servlet are loaded 3 ways 1) When the web sever starts 2) You can set this in the
configuration file 3) Through an administration interface.
Q) Servlet Container
The servlet container is a part of a Web server (or) Application server that
provides the network services over which requests and responses are sent, decodes
MIME-based requests, and formats MIME-based responses. A servlet container also
contains and manages servlets through their lifecycle.
A servlet container can be built into a host Web server, or installed as an add-on
component to a Web Server via that server’s native extension API. All servlet
containers must support HTTP as a protocol for requests and
responses, but additional request/response-based protocols such as HTTPS (HTTP
over SSL) may be supported.
Q) Generally Servlets are used for complete HTML generation. If you want to
generate partial HTML's that include some static text as well as some dynamic text,
what method do you use?
A) Using 'RequestDispather.include(“xx.html”) in the servlet code we can mix the
partial static HTML Directory page.
Ex: - RequestDispatcher rd=ServletContext.getRequestDispatcher(“xx.html”);
rd.include(request,response);
Nazar Babu 47
Java Technoloies
Q) Servlet Life cycle
The Web server when loading the servlet calls the init method once. (The init
method typically establishes database connections.)
Any request from client is handled initially by the service () method before
delegating to the doXxx () methods in the case of HttpServlet. If u put “Private”
modifier for the service() it will give compile time error.
When your application is stopped (or) Servlet Container shuts down, your
Servlet's destroy () method will be called. This allows you to free any resources you
may have got hold of in your Servlet's init () method, this will call only once.
ServletException Signals that some error occurred during the processing of the
request and the container should take appropriate measures to clean up the request.
Q) Can we leave init() method empty and insted can we write initilization
code inside servlet's constructor?
A) No, because the container passes the ServletConfig object to the servlet only
when it calls the init method. So ServletConfig will not be accessible in the
constructor.
Nazar Babu 48
Java Technoloies
+ web.xml / (taglib.tld)
|
+ weblogic.xml
Q) Web.xml: -
<web-app>
<!-- Defines WebApp initialization parameters.-->
<context-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</context-param>
<init-param>
<param-name>locale</param-name>
<param-value>US</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Test Filter</filter-name>
<servlet-name>TestServlet</servlet-name>
</filter-mapping>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
Nazar Babu 49
Java Technoloies
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
<security-role-ref>
<!-- role-name is used in HttpServletRequest.isUserInRole(String
role) method. -->
<role-name>manager</role-name>
<!-- role-link is one of the role-names specified in security-role
elements. -->
<role-link>supervisor</role-link>
</security-role-ref>
</servlet>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<error-page>
<exception-type>java.sql.SQLException</exception-type>
<location>sqlexception.jsp</location>
</error-page>
<taglib>
<taglib-uri>http://abc.com/testlib</taglib-uri>
<taglib-location>/WEB-INF/tlds/testlib.tld</taglib-location>
</taglib>
<taglib>
<taglib-uri>/examplelib</taglib-uri>
<taglib-location>/WEB-INF/tlds/examplelib.tld</taglib-location>
</taglib>
<web-resource-collection>
<web-resource-name>Another Protected Area</web-resource-name>
Nazar Babu 50
Java Technoloies
<url-pattern>*.hello</url-pattern>
</web-resource-collection>
</web-app>
<servlet servlet-name='test.HelloWorld'>
<run-at>0:00, 6:00, 12:00, 18:00</run-at>
</servlet>
Ex:-
<web-app>
<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>TestServlet</servlet-class>
<init-param>
<param-name>driverclassname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
<init-param>
<param-name>dburl</param-name>
<param-value>jdbc:odbc:MySQLODBC</param-value>
</init-param>
</servlet>
</web-app>
--------------------------------------
Nazar Babu 51
Java Technoloies
public void init()
{
ServletConfig config = getServletConfig();
String driverClassName = config.getInitParameter("driverclassname");
String dbURL = config.getInitParameter("dburl");
Class.forName(driverClassName);
dbConnection = DriverManager.getConnection(dbURL,username,password);
}
Servlet Context is a grouping under which related servlets run. They can share data,
URL namespace, and other resources. There can be multiple contexts in a single
servlet container.
Q) Diff between HttpSeassion & Stateful Session bean? Why can't HttpSessionn be
used instead of of Session bean?
A) HttpSession is used to maintain the state of a client in webservers, which are
based on Http protocol. Where as Stateful Session bean is a type of bean, which can
also maintain the state of the client in Application servers, based on RMI-IIOP.
Q) Servlet Listeners
(i) ServletContextListener
void contextDestroyed (ServletContextEvent sce)
void contextInitialized (ServletContextEvent sce)
Implementations of this interface receive notifications about changes to the
servlet context of the web application they are part of. To receive notification events,
the implementation class must be configured in the deployment descriptor for the
web application.
Nazar Babu 52
Java Technoloies
events, the implementation class must be configured in the deployment descriptor
for the web application.
Q) HttpListeners
(iv) HttpSession Binding Listener (** If session will expire how to get the
values)
Some objects may wish to perform an action when they are bound (or)
unbound from a session. For example, a database connection may begin a
transaction when bound to a session and end the transaction when unbound. Any
object that implements the javax.servlet.http.HttpSessionBindingListener interface is
notified when it is bound (or) unbound from a session. The interface declares two
methods, valueBound() and valueUnbound(), that must be implemented:
Methods: -
public void HttpSessionBindingListener.valueBound(HttpSessionBindingEvent event)
public void HttpSessionBindingListener.valueUnbound(HttpSessionBindingEvent
event)
Nazar Babu 53
Java Technoloies
=========
public class SessionBindings extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/plain");
PrintWriter out = res.getWriter ();
HttpSession session = req.getSession(true);
session.putValue("bindings.listener",
new CustomBindingListener(getServletContext())); // Add a
CustomBindingListener
}
}
=============
class CustomBindingListener implements HttpSessionBindingListener
{
ServletContext context;
Q) Filter
Filter is an object that intercepts a message between a data source and a data
destination, and then filters the data being passed between them. It acts as a guard,
preventing undesired information from being transmitted from one point to another.
When a servlet container receives a request for a resource, it checks whether a filter
is associated with this resource. If a filter is associated with the resource, the servlet
container routes the request to the filter instead of routing it to the resource. The
filter, after processing the request, does one of three things:
• It generates the response itself and returns it to the client.
• It passes on the request (modified or unmodified) to the next filter in the chain
• It routes the request to a different resource.
Nazar Babu 54
Java Technoloies
Q) Session Tracking
Session tracking is the capability of the server to maintain the single client
sequential list.
Nazar Babu 55
Java Technoloies
Q) Servlet chaining
Is a technique in which two are more servlets cooperating in servicing a single
client sequential request, where one servlet output is piped to the next servlet
output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest
Servlet Aliasing allow you to setup a single alias name for a comma delimited list
of servlets. To make a servlet chain open your browser and give the alias name in
URL.
HttpRequest construct a URL string and append a comma delimited list of servlets
to the end.
Q) HttpTunnelling
Is a method used to reading and writing serializes objects using a http
connection. You are creating a sub protocol inside http protocol that is tunneling
inside another protocol.
Q) Can I catch servlet exception and give my own error message? (or)
custom error pages?
A) Yes, you can catch servlet errors and give custom error pages for them, but if
there are exceptional conditions you can anticipate, it would be better for your
application to address these directly and try to avoid them in the first place. If a
servlet relies upon system or network resources that may not be available for
unexpected reasons, you can use a RequestDispatcher to forward the request to an
error page.
Nazar Babu 56
Java Technoloies
Web.xml
<error-page>
<error-code>
HTTP error code (404)
<error-code>
<exception-type>
java.lang.RuntimeException
</exception-type>
<location>
/err/RuntimeException.jsp
</location>
</error-page>
Client pull
Client pull is similar to redirection, with one major difference: the browser
actually displays the content from the first page and waits some specified amount of
time before retrieving and displaying the content from the next page. It's called
client pull because the client is responsible for pulling the content from the next
page.
Client pull information is sent to the client using the Refresh HTTP header. This
header's value specifies the number of seconds to display the page before pulling the
next one, and it optionally includes a URL string that specifies the URL from which to
pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells
the client to reload this same servlet after showing its current content for three
seconds: setHeader("Refresh", "3");
And here's a call that tells the client to display Netscape's home page after the three
seconds:
setHeader("Refresh", "3; URL=http://home.netscape.com");
Server push
Server push because the server sends, or pushes, a sequence of response
pages to the client. With server push, the socket connection between the client and
the server remains open until the last page has been sent.
<META HTTP-EQUIV="Refresh" CONTENT="5;URL=/servlet/stockquotes/">
Nazar Babu 57
Java Technoloies
Q) How can a servlet refresh automatically if some new data has entered the
database?
A) You can use client side refresh are server push
URL Rewriting
URL rewriting is a technique in which the requested URL is modified with the
session id.
URL rewriting is another way to support anonymous session tracking. With URL
rewriting, every local URL the user might click on is dynamically modified, or
rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123 added parameter
Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can
later be read back from that browser. When a browser receives a cookie, it saves the
cookie and thereafter sends the cookie back to the server each time it accesses a
page on that server, subject to certain rules. Because a cookie's value can uniquely
identify a client, cookies are often used for session tracking. Because cookies are
sent using HTTP headers, they should be added to the response before you send any
content. Browsers are only required to accept 20 cookies per site, 300 total per user,
and they can limit each cookie's size to 4096 bytes.
Nazar Babu 58
Java Technoloies
Sending cookies from a servlet
You can set the maximum age of a cookie with the cookie.setMaxAge(int
seconds) method:
Zero means to delete the cookie
+ value is the maximum number of seconds the cookie will live, before it expires
- value means the cookie will not be stored beyond this browser session (deleted
on browser close)
This will return the session for this user or create one if one does not already exist.
Values can be stored for a user session using the HttpSession method putValue():
session.putValue("valueName", valueObject);
Nazar Babu 59
Java Technoloies
Session objects can be retrieved using getValue(String name), while a array of all
value names can be retrieved using getValueNames(). Values can also be removed
using removeValue(String valueName)
User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The
user is required to enter a user name and password. Once they are verified the client
re-sends the authorisation with requests for documents to that site in the http
header.
Servlets can use the username authorisation sent with request to keep track of user
data. For example, a hashtable can be set up to contain all the data for a particular
user. When a user makes another request the user name can be used to add new
items to their cart using the hashtable.
while (params.hasMoreElements()) {
paramName = (String) params.nextElement();
paramValues = request.getParameterValues(paramName);
System.out.println("\nParameter name is " + paramName);
for (int i = 0; i < paramValues.length; i++) {
System.out.println(", value " + i + " is " +
paramValues[i].toString());
}
}
Q) Session
Session is a persistence network connection between client and server that
facilitate the exchange of information between client and server. The container
generates a session ID, when you create a session the server saves the session ID
on the clients machine as a cookie. A session object created for each user persists on
the server side, either until user closes the browser or user remains idle for the
session expiration time.
Nazar Babu 60
Java Technoloies
Invalidating a Session
There are 6 different ways to invalidate the session.
1 Httpsession.setMaxInactiveIntervel(int sec)
2 Session will automatically expire after a certain time of inactivity
3 User closes browser window, notice that the session will time out rather than
directly triggering session invalidate.
4 calling invalidate()
5 if server cashes
6 put <session-timeout> in web.xml
Q) If the cookies at client side are disabled then session don't work, in this
case how can we proceed?
A) 1. (from servlet) write the next page with a hidden field containing a unique ID
that serves as "session ID". So next time when the user clicks submit, you can
retrieve the hidden field.
2. If you use applet, you may avoid "view source" (so that people can't see the
hidden field). Your applet reads back an ID from the servlet and use that from then
on to make further requests
Q) Diff between Multiple Instances of Browser and Multiple Windows? How does this
affect Sessions?
A) From the current Browser window, if we open a new Window, then it referred to
as Multiple Windows. Sessions properties are maintained across all these windows,
Nazar Babu 61
Java Technoloies
even though they are operating in multiple windows.
Instead, if we open a new Browser, by either double clicking on the Browser
Shortcut then we are creating a new Instance of the Browser. This is referred to as
Multiple Instances of Browser. Here each Browser window is considered as different
client. So Sessions are not maintained across these windows.
Q) SingleThread model
SingleThreadModel is a tag interface with no methods. In this model no two
threads will execute concurrently the service method of the servlet, to accomplish
this each thread uses a free servlet instance from the servlet pool. So any servlet
implementing this can be considered thread safe and it is not required synchronize
access to its variables.
(or)
If a servlet implements this interface, the server ensures that each instance
of the servlet handles only one service request at a time. Servers implement this
functionality by maintaining a pool of servlet instances and dispatching incoming
requests to free servlets within the pool. SingleThreadModel provides easy thread
safety, but at the cost of increased resource requirements as more servlet instances
are loaded at any given time.
Q) Request Headers
User-agent: - Gives the information about client software, browser name, version
and information about the machine on which it is running.
request.getHeader(“user-agent”);
Nazar Babu 62
Java Technoloies
Servlet1
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher (“/../srevlet2”) ;
rd.forward(req, res);
Servlet2
Ex:- ServletContext.getRequestDispatcher(HttpRequest,
HttpResponse).forward("NextServlet") ;
You can pass in the current request and response object from the latest form
submission to the next servlet/JSP. You can modify these objects and pass them so
that the next servlet/JSP can use the results of this servlet.
There are some Servlet engine specific configurations for servlet chaining.
Servlets can also call public functions of other servlets running in the same server.
This can be done by obtaining a handle to the desired servlet through the
ServletContext Object by passing it the servlet name ( this object can return any
servlets running in the server). And then calling the function on the returned Servlet
object.
You must be careful when you call another servlet's methods. If the servlet that you
want to call implements the SingleThreadModel interface, your call could conflict with
the servlet's single threaded nature. (The server cannot intervene and make sure
your call happens when the servlet is not interacting with another client.) In this
case, your servlet should make an HTTP request to the other servlet instead of direct
calls.
Nazar Babu 63
Java Technoloies
2) Get a request dispatcher from the servlet context instance, specifying the page-
relative or application-relative path of the target JSP page as input to the
getRequestDispatcher() method:
RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");
Prior to or during this step, you can optionally make data available to the JSP page
through attributes of the HTTP request object. See "Passing Data Between a JSP
Page and a Servlet" below for information.
3) Invoke the include() or forward() method of the request dispatcher, specifying the
HTTP request and response objects as arguments.
Q) context.getRequestDispatcher()
request.getRequestDispatcher()
context.getNamedDispatcher()
Nazar Babu 64
Java Technoloies
1) ServletContext.getRequestDispatcher( / ) —> You must use
Absolute paths, it can extend outside current servlet context.
Ex :-
public class ServletToServlet extends HttpServlet {
public void doGet (HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
try {
getServletConfig()
.getServletContext().getRequestDispatcher("/HelloWorldExample").forward(re
quest, response);
} catch (Exception ex) {
ex.printStackTrace ();
}
}
}
Q) How can I pass data from a servlet running in one context (webapp) to a
servlet running in another context?
A) You can bind this information to a context that is accessible to all servlet
contexts, such as the application server's context. This way, you can keep the data
you want to share in memory.
Nazar Babu 65
Java Technoloies
Q) How can I share data between two different web applications?
A) Different servlets may share data within one application via ServletContext. If
you have a compelling to put the servlets in different applications.
GetRequestURI servlets/HelloServlet/jdata/userinfo
GetServletPath servlets/HelloServlet/
GetPathInfo /jdata/userinfo
GetQueryString pagetype=s3&pagenum=4
Class.forName(driverClassName);
this.dbURL = dbURL;
this.user = user;
this.password = password;
this.increment = increment;
Nazar Babu 66
Java Technoloies
Connection con = null;
Enumeration cons = connections.keys();
synchronized (connnections) {
while(cons.hasMoreElements()) {
con = (Connection)cons.nextElement();
Boolean b = (Boolean)connections.get(con);
if (b == Boolean.FALSE) {
// So we found an unused connection. Test its integrity with a quick
setAutoCommit(true) call.
// For production use, more testing should be performed, such as executing a
simple query.
try {
con.setAutoCommit(true);
}
catch(SQLException e) {
// Problem with the connection, replace it.
con = DriverManager.getConnection(dbURL, user, password);
}
// Update the Hashtable to show this one's taken
connections.put(con, Boolean.TRUE);
return con;
}
}
}
// If we get here, there were no free connections.
// We've got to make more.
for(int i = 0; i < increment; i++) {
connections.put(DriverManager.getConnection(dbURL, user, password),
Boolean.FALSE);
}
// Recurse to get one of the new connections.
return getConnection();
}
public void returnConnection(Connection returned) {
Connection con;
Enumeration cons = connections.keys();
while (cons.hasMoreElements()) {
con = (Connection)cons.nextElement();
if (con == returned) {
connections.put(con, Boolean.FALSE);
break;
}
}
}
}
Nazar Babu 67
Java Technoloies
JSP
Why JSP Technology?
Directives:
XML syntax: -
Nazar Babu 68
Java Technoloies
<%@ taglib uri="uriToTagLibrary"
prefix="prefixString" %> Taglib directive enables
you to create your own
Taglib XML syntax: - custom tags.
Directive <Jsp: root xmlns:prefix1=”http://..”
version=”1.2” />
</Jsp: root>
Actions:
Nazar Babu 69
Java Technoloies
the http parameters of
the previous page to the
destination page. It will
work at server side.
<Jsp: plugin type="bean/applet" This action is used to
code="classFileName" generate client browser
codebase="classFileDirectoryName" specific html tags that
<Jsp: name="instanceName" archive="” ensures the java plug in
plugin> align="" height=" " width=" " software is available,
hspace=" " vspace=" </jsp: followed by execution of
plugin> applet or java bean
component specified in
tag.
Implicit Objects
Objects Type / purpose Scope Sum useful
methods
Request Subclass of Request getAttribute,
javax.servlet.http.Servl - Objects getParameter,
etRequest accessible from getParameterName
pages processing s,
- Refers to the current the request where getParameterValue
request passed to the they were created. s, setAttribute
_jspService() method
Response Subclass of Page Not typically used
javax.servlet.http.Servl by JSP page
etResponse authors
Nazar Babu 70
Java Technoloies
Out javax.servlet.jsp.JspWri Page clear, clearBuffer,
ter flush,
getBufferSize,
- Refers to the output getRemaining
stream of the JSP page.
Config javax.servlet.ServletCo Page getInitParameter,
nfig getInitParameterN
ames
- The initialization
parameters given in the
deployment descriptor
can be retrieved from
this object.
page java.lang.Object. Page Not typically used
- Objects by JSP page
- Refers to the current accessible only authors
instance of the servlet within jsp pages
generated from the JSP where it was
page. created.
pageCont javax.servlet.jsp.PageC Page findAttribute,
ext ontext. getAttribute,
getAttributesScope
- Provides certain ,
convenience methods getAttributeNames
and stores references to InScope,
the implicit objects. setAttribute.
exception java.lang.Throwable. Page getMessage,
getLocalizedMessa
- Available for pages ge,
that set the page printStackTrace,
directive attribute toString
isErrorPage to true. It
can be used for
exception handling.
Scripting Elements:
Type / purpose Sum useful methods
Elements
<% Java_code %> A scriptlet can contain
variable (or) method
declarations (or)
XML syntax: - expressions. Scriptlets
<Jsp: scriptlet> are executed at request
Scriptlet time, when the JSP
Date today = new Date();
</jsp: scriptlet> engine processes the
client request. If the
scriptlet produces output,
the output is stored in
the out object, from
which you can display it.
Nazar Babu 71
Java Technoloies
Ex: <%! int a, b, c; %>
<%! int accountnumber=23468; A declaration declares
%> one or more variables
<%! private void processAmount (or) methods for use
() { ... } %> later in the JSP source
Declaration file. This is used for
XML syntax: - “Global declaration”.
<jsp: declaration>
int counter=0;
</jsp: Declaration>
Ex: <%= (new An expression tag
java.util.Date()).toLocaleString() %> contains a scripting
XML syntax: - language expression that
Expressions <jsp: expression> is evaluated, converted
// ------- to a String, and inserted
</jsp: expression> where the expression
appears in the JSP file.
Html comment Creates a Comments are removed
comment that is sent to the client in from the viewable source
Comments the viewable page source. of your HTML files by
Ex: <! -- <%= expression %> --> using only JSP comment
tags. HTML comments
Hidden Comment Documents the remain visible when the
JSP file, but is not sent to the client. user selects view source
Ex: <%-- comment --%> in the browser.
Explicit Explicit objects are declared and created within the code of your JSP page,
accessible to that page and other pages according to the scope setting you choose.
Explicit objects are typically JavaBean instances declared and created in
jsp:useBean action statements. <jsp:useBean id="pageBean"
class="mybeans.NameBean" scope="page" />
Implicit Implicit objects are created by the underlying JSP mechanism and
accessible to Java scriptlets (or) expressions in JSP pages according to the inherent
scope setting of the particular object type.
Q) MVC
Nazar Babu 72
Java Technoloies
Model: - model is a java bean/entity bean that represent the data being transmitted
are received
Controller: - Controller is a servlet that performs necessary manipulations to the
model.
View: - is a screen representation of the model.
Major benefits of using the MVC design pattern is separate the view & model this
make it is possible to create are change views with out having to change the model.
1) The browser makes a request to the controller servlet 2) Servlet performs
necessary actions to the java bean model and forward the result to the jsp view. 3)
The jsp formats the model for display and send the html results back top the web
browser.
Q) WebApplication scopes?
A) Request, Session, Application.
Request :- Life time is until the response is return to the user
Session :- Until the session timeout (or) session id invalidate.
Application :- Life of container (or) explicitly killed
Q) Life-cycle of JSP
Page translation
Jsp compilation
Load class
Create Instance
jspInit( ), _jspservice( ), jspDestroy( )
jspDestroy( ) container calls this when it decides take the instance out of
service. It is the last method called n the servlet instance.
Destroy is not called if the container crashes.
jspInit() & jspDestroy() called only once so we cannot override these methods.
Q) RequestDispatcher.forward(req, res)
RequestDispatcher.include(req, res)
PageContext.forward()
res.sendRedirect(url)
<jsp:forward>
res.sendRedirect(url) when ever the client request will come just it will
take the request and the request to be forwarded to another page. It cannot forward
the http parameters of the previous page. This will work at “client side”. If
page1.jsp redirects to page2.jsp, the browser's address bar be updated to show
page2.jsp.
Nazar Babu 73
Java Technoloies
The difference between the two is that sendRedirect always sends a header back to
the client/browser. this header then contains the resource(page/servlet) which you
wanted to be redirected. the browser uses this header to make another fresh
request. thus sendRedirect has a overhead as to the extra remort trip being incurred.
it's like any other Http request being generated by your browser. the advantage is
that you can point to any resource(whether on the same domain or some other
domain). for eg if sendRedirect was called at www.mydomain.com then it can also be
used to redirect a call to a resource on www.theserverside.com.
In the case of forward() call, the above is not true. resources from the server, where
the fwd. call was made, can only be requested for. But the major diff between the
two is that forward just routes the request to the new resources which you specify in
your forward call. that means this route is made by the servlet engine at the server
level only. no headers are sent to the browser which makes this very efficient. also
the request and response objects remain the same both from where the forward call
was made and the resource which was called.
Ex -- of RequestDispatcher.forward(req, res)
public class BookStoreServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException {
// Get the dispatcher; it gets the main page to the user
RequestDispatcher dispatcher =
config.getServletContext().getRequestDispatcher("/bookstore.html");
if (dispatcher == null) {
// No dispatcher means the resource (bookstore.html in this
case) cannot be found
res.sendError(response.SC_NO_CONTENT);
} else {
// Send the user the bookstore's opening page
dispatcher.forward(request, response);
}
Nazar Babu 74
Java Technoloies
Q) Diff res.sendRedirect( ) & req.forward( )
Nazar Babu 75
Java Technoloies
Q) How do I prevent the output of my JSP or Servlet pages from being
cached by the Web browser? And Proxy server?
A) Web browser caching
<% response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>
Proxy server caching
response.setHeader("Cache-Control","private");
Nazar Babu 76
Java Technoloies
Q) How do you pass an InitParameter to a JSP?
<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames();
e.hasMoreElements();)
{
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>
Nazar Babu 77
Java Technoloies
Q) How do I pass values from a list box (with multiple selects) to a Java
Bean?
Consider the following HTML, which basically allows the user to select multiple values
by means of a checkbox:
package foo;
public class MovieBean {
private String[] movies;
public MovieBean() {
String movies[] = new String[0];
}
public String[] getMovies() {
return movies;
}
public void setMovies(String[] m) {
this.movies = m;
}
}
Although a good design pattern would be to have the names of the bean properties
match those of the HTML input form elements, it need not always be the case, as
indicated within this example. The JSP code to process the posted form data is as
follows:
<html> <body>
<%! String[] movies; %>
Nazar Babu 78
Java Technoloies
out.println ("<li>"+movies[i]+"</li>");
}
out.println("</ul>");
} else
out.println ("Don't you watch any movies?!");
%>
</body></html>
Q) Tag Libraries
These all methods are callback methods.
Tag methods: doStartTag()
doEndTag()
Body Tag : doAfterBody()
Nazar Babu 79
Java Technoloies
Struts
Q) Framework?
A) A framework is a reusable, ``semi-complete'' application that can be specialized
to produce custom applications
Q) ActionServlet (controller)
The class org.apache.struts.action.ActionServlet is the called the
ActionServlet. In 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. The Controller receives the request from the browser;
invoke a business operation and coordinating the view to return to the client.
Q) Action Class
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
Nazar Babu 80
Java Technoloies
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.
Ex: -
package com.odccom.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BillingAdviceAction extends Action {
Nazar Babu 81
Java Technoloies
Q) execute
Is called by the controller when a request is received from a client. The
controller creates an instance of the Action class if one does not already exist. The
frame work will create only a single instance of each Action class.
Q) Validate: -
This method is called by the controller after the values from the request has
been inserted into the ActionForm. The ActionForm should perform any input
validation that can be done and return any detected errors to the controller.
Flowing steps: -
1. Enabling the Validator plug-in: This makes the Validator available to the
system.
2. Create Message Resources for the displaying the error message to the user.
3. Developing the Validation rules We have to define the validation rules in the
validation.xml for the address form. Struts Validator Framework uses this rule for
generating the JavaScript for validation.
4. Applying the rules: We are required to add the appropriate tag to the JSP for
generation of JavaScript.
Nazar Babu 82
Java Technoloies
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/technology/WEB-INF/validator-
rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
This definition tells Struts to load and initialize the Validator plug-in for your
application. Upon initialization, the plug-in loads the comma-delimited list of
Validator config files specified by the pathnames property.
Validator-rules.xml
<form-validation>
<global>
<Validator name="required" classname="org.apache.struts.validator.FieldChecks"
method="validateRequired"
methodParams="java.lang.Object,
org.apache.commons.validator.ValidatorAction,
org.apache.commons.validator.Field,
org.apache.struts.action.ActionErrors,
javax.servlet.http.HttpServletRequest"
msg="errors.required">
<javascript>
<![CDATA[
function validateRequired(form) {
]]>
</javascript>
</validator>
</global>
</form-validation>
Q) What is Tiles?
A) Tiles is a framework for the development user interface, Tiles is enables the
developers to develop the web applications by assembling the reusable tiles.
Nazar Babu 83
Java Technoloies
1. Add the Tiles Tag Library Descriptor (TLD) file to the web.xml.
2. Create layout JSPs.
3. Develop the web pages using layouts.
Q) How you will save the data across different pages for a particular client
request using Struts?
A) If the request has a Form object, the data may be passed on through the Form
object across pages. Or within the Action class, call request.getSession and use
session.setAttribute(), though that will persist through the life of the session until
altered.
(Or) Create an appropriate instance of ActionForm that is form bean and store that
form bean in session scope. So that it is available to all the pages that for a part of
the request
<message-resource parameter=”title.empname”/>
<bean:message key=”title.empname”/>
Nazar Babu 84
Java Technoloies
DynaActionForm which allows you to configure the bean in the struts-config.xml file.
We are going to use a subclass of DynaActionForm called a DynaValidatorForm which
provides greater functionality when used with the validation framework.
<struts-config>
<form-beans>
<form-bean name="employeeForm"
type="org.apache.struts.validator.DynaValidatorForm">
<form-property name="name" type="java.lang.String"/>
<form-property name="age" type="java.lang.String"/>
<form-property name="department" type="java.lang.String" initial="2" />
<form-property name="flavorIDs" type="java.lang.String[]"/>
<form-property name="methodToCall" type="java.lang.String"/>
</form-bean>
</form-beans>
</struts-config>
This DynaValidatorForm is used just like a normal ActionForm when it comes to how
we define its use in our action mappings. The only 'tricky' thing is that standard
getter and setters are not made since the DynaActionForms are backed by a
HashMap. In order to get fields out of the DynaActionForm you would do:
A) You can have multiple controllers, but usually only one is needed
Nazar Babu 85
Java Technoloies
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<! — module configurations -- >
<init-param>
<param-name>config/exercise</param-name>
<param-value>/WEB-INF/exercise/struts-config.xml</param-value>
</init-param>
</servlet>
Q) Can you write your own methods in Action class other than execute() and call the
user method directly?
A) Yes, we can create any number of methods in Action class and instruct the action
tag in struts-config.xml file to call that user methods.
Q) Struts-config.xml
<struts-config>
<data-sources>
<data-source>
<set-property property=”key” value=”” url=”” maxcount=”” mincount=””
user=”” pwd=”” >
</data-source>
<data-sources>
Nazar Babu 86
Java Technoloies
<!— to identify the target of an action class when it returns results -- >
<global-forwards>
<forward name="error" path="/error.jsp"/>
</global-forwards>
<!—Validator plugin
<plug-in className="org.apache.struts.validator.ValidatorPlugIn">
<set-property property="pathnames" value="/WEB-INF/validator-rules.xml,
/WEB-INF/validation.xml"/>
</plug-in>
<!—Tiles plugin
<plug-in className="org.apache.struts.tiles.TilesPlugIn">
<set-property property="definitions-config" value="/WEB-INF/tiles-defs.xml
"/>
</plug-in>
</struts-config>
Nazar Babu 87
Java Technoloies
</init-param>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<filter-mapping>
<filter-name>HelloWorldFilter</filter-name>
<url-pattern>ResponseServlet</ url-pattern >
</filter-mapping>
</web-app>
Nazar Babu 88
Java Technoloies
Hibernate
1.What is ORM ?
4.What is Hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy
SQL. Apart from this, ORM provides following benefits:
• Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
• Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
• Improved maintainability
Nazar Babu 89
Java Technoloies
o A lot less code to write
• Improved portability
o ORM framework generates database-specific SQL for you
Hibernate simplifies:
Hibernate mapping file tells Hibernate which tables and columns to use to load and
store objects. Typical mapping file look as follows:
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)
Nazar Babu 90
Java Technoloies
The five core interfaces are used in just about every Hibernate application.
Using these interfaces, you can store and retrieve persistent objects and control
transactions.
• Session interface
• SessionFactory interface
• Configuration interface
• Transaction interface
• Query and Criteria interfaces
Nazar Babu 91
Java Technoloies
• Holds a mandatory (first-level) cache of persistent objects, used when
navigating the object graph or looking up objects by identifier
• Load the Hibernate configuration file and create configuration object. It will
automatically load all hbm mapping files
• Create session factory from configuration object
• Get one session from this session factory
• Create HQL Query
• Execute query to get list containing Java objects
Hibernate offers a query language that embodies a very powerful and flexible
mechanism to query, store, update, and retrieve objects from a database. This
language, the Hibernate query Language (HQL), is an object-oriented extension to
SQL.
• First we need to write Java domain objects (beans with setter and getter).
The variables should be same as database columns.
• Write hbm.xml, where we map java class to table and database columns to
Java class variables.
Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
Nazar Babu 92
Java Technoloies
16.What’s the difference between load() and get()?
load() vs. get() :
load() get()
load() method will throw an exception if the get() method will return null if the
unique id is not found in the database. unique id is not found in the database.
Use update() if you are sure that the session does not contain an already
persistent instance with the same identifier, and merge() if you want to merge your
modifications at any time without consideration of the state of the session.
Nazar Babu 93
Java Technoloies
Named SQL queries are defined in the mapping xml document and called
wherever required.
Example:
Example :
Nazar Babu 94
Java Technoloies
24.Define HibernateTemplate?
27.If you want to see the Hibernate generated SQL statements on console, what
should we do?
<property name="show_sql">true</property>
The properties that are not mapped to a column, but calculated at runtime by
evaluation of an expression are called derived properties. The expression can be
defined using the formula attribute of the element.
Nazar Babu 95
Java Technoloies
Example:
If your collection is not large, it will be If your collection is very large, it will be
more efficient way to sort it. more efficient way to sort it .
JDBC Hibernate
Nazar Babu 96
Java Technoloies
Nazar Babu 97
Java Technoloies
• Bag
• Set
• List
• Array
• Map
Nazar Babu 98
Java Technoloies
36.How can Hibernate be configured to access an instance variable directly and not
through a setter method ?
A fetching strategy is the strategy Hibernate will use for retrieving associated
objects if the application needs to navigate the association. Fetch strategies may be
declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria
query.
Nazar Babu 99
Java Technoloies
saved, or deleted. Hibernate applications don't need to implement these callbacks,
but they're useful for implementing certain kinds of generic functionality.
1.What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and
query service. This lets the users to develop persistent classes following object-
oriented principles such as association, inheritance, polymorphism, composition, and
collections.
2.What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and
translucent perseverance of objects in a Java application in to the tables of a
relational database using the metadata that describes the mapping between the
objects and the database. It works by transforming the data from one representation
to another.
3.What does an ORM solution comprises of?
• It should have an API for performing basic CRUD (Create, Read, Update, Delete)
operations on objects of persistent classes
• Should have a language or an API for specifying queries that refer to the classes
and the properties of classes
• An ability for specifying mapping metadata
• It should have a technique for ORM implementation to interact with
transactional objects to perform dirty checking, lazy association fetching, and
other optimization functions
The entire application, including the user interface, is designed around the
relational model and SQL-based relational operations.
The entities are represented as classes that are mapped manually to the
relational tables. The code is hidden from the business logic using specific design
patterns. This approach is successful for applications with a less number of entities,
The application is designed around an object model. The SQL code is generated at
build time. And the associations between objects are supported by the persistence
mechanism, and queries are specified using an object-oriented expression language.
This is best suited for medium-sized applications with some complex transactions.
Used when the mapping exceeds 25 different database products at a time.
There are many benefits from these. Out of which the following are the most
important one.
i. Productivity - Hibernate reduces the burden of developer by providing much of
the functionality and let the developer to concentrate on business logic.
ii. Maintainability - As hibernate provides most of the functionality, the LOC for the
application will be reduced and it is easy to maintain. By automated object/relational
persistence it even reduces the LOC.
iii. Performance - Hand-coded persistence provided greater performance than
automated one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time there by increasing the performance. If it is
automated persistence then it still increases the performance.
iv. Vendor independence - Irrespective of the different types of databases that are
there, hibernate provides a much easier way to develop a cross platform application.
11.What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is
provided in an xml document. This document is called as xml mapping document.
The document defines, among other things, how properties of the user defined
persistence classes' map to the columns of the relative tables in database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>
Everything should be included under <hibernate-mapping> tag. This is the main tag
for an xml mapping document.
12.Show Hibernate overview?
There are many benefits from these. Out of which the following are the most
important one.
i. Session Interface - This is the primary interface used by hibernate applications.
The instances of this interface are lightweight and are inexpensive to create and
destroy. Hibernate sessions are not thread safe.
ii. SessionFactory Interface - This is a factory that delivers the session objects to
hibernate application. Generally there will be a single SessionFactory for the whole
application and it will be shared among all the application threads.
iii. Configuration Interface - This interface is used to configure and bootstrap
hibernate. The instance of this interface is used by the application in order to specify
the location of hibernate specific mapping documents.
iv. Transaction Interface - This is an optional interface but the above three
interfaces are mandatory in each and every application. This interface abstracts the
code from any kind of transaction implementations such as JDBC transaction, JTA
transaction.
v. Query and Criteria Interface - This interface allows the user to perform queries
and also control the flow of the query execution.
18.What is the file extension you use for hibernate mapping file?
Q: What is Hibernate?
A: Hibernate is a java-based Object/relational mapping(ORM) tool.
Q: What are ORM tools?
A: ORM tools provide automated solutions for the Object/relational paradigm
mismatch problem, using metadata that describes the mapping between the objects
and the database.
Q: What is Object/relational paradigm mismatch?
A: Object-Oriented paradigm is based on software engineering principles, whereas
relational paradigm on mathematical principles. Object-oriented technology supports
the building of applications out of networks of objects with both data and behavior.
Relational technology supports the storage of data in tables and manipulation of that
data using data manipulation language (DML). Because the underlying paradigms are
different the two technologies do not work seamlessly, hence the name
Object/relational paradigm mismatch.
Q: What role does the Session interface play in Hibernate?
A: The Session is a persistence manager that manages operation like storing and
retrieving objects. Instances of Session are inexpensive to create and destroy. They
are not threadsafe.
Q: What is SessionFactory interface?
A: The application obtains Session instances from a SessionFactory. SessionFactory
instances are not lightweight and typically one instance is created for the whole
application. If the application accesses multiple databases, it needs one per database
Q: What is Configuration interface?
A: The application uses a Configuration instance to specify the location of mapping
Anybody tell me please, where exactly Hibernate is used..tell me about the mapping
and .xml file in Hibernate
Ans: To make the application developemnt more productive. its saves development
time and also mainly it deals with Objects(POJO) . and .xml file is nuthing but
mapping between database column and POJO variable. you can easily switch the
database like MySql ...
Ans: when loading an obj that has a collection, hibernate loads collection elements
ONLY when actually you ask for them; so this improves performance, among other
advantages.when u use hibernate u can make lazy=true or lazy=false. ...
Ans: You can declare it as Named queiries in one of your mapping files and give
unique name.Call it in your code. Sample code is below.SQLQuery sq = (SQLQuery)
session.getNamedQuery("findSearchResultsListSP");sq.addEntity("documentTypeCod
e", ...
5.What J2EE design problems does Hibernate solves apart from Data Base in-
dependency and being an ORM
What J2EE design problems does Hibernate solves apart from Data Base in-
dependency and being an ORM tool?
Ans: Hibernate and EJB have different purpose.EJB is for writing business logic as
well and provide Database independency just as hibernate provide for us.EJB infact
use the container services(EJB container) like transaction, securiry etc as well.Which
is ...
Ans: Update():- if you are sure that the session does not contains an already
persistent instance with the same identifier,then use update to save the data in
hibernateMerge():-if you want to save your modificatiions at any time with out
knowing abot ...
Ans: Proxies are created dynamically by subclassing your object at runtime. The
subclass has all the methods of the parent, and when any of the methods are
accessed, the proxy loads up the real object from the DB and calls the method for
you. Very nice in ...
9.What is the difference between hibernate and spring JDBC template? List any
advantages and disadvantages
What is the difference between hibernate and spring JDBC template? List any
advantages and disadvantages
Ans: 1)Â In Entity Bean at a time we can interact with only one data Base. Where
as in Hibernate we can able to establishes the connections to more than One Data
Base. Only thing we need to write one more configuration file.  2) Entity Beans
does not support ...
Ans: Those are .. 1Â to many, many to many, many to one.. relations. these
relational mappings are done by using the hibernates utilities such as list, set, bags,
object... In detail Go thru.... www.hibernate.org ...
Ans: Add the hibernate related jar files into lib directory of any web application using
net beans.http://www.netbeans.org/kb/41/hibernate.html ...
Ans: cascade specifies which operations should be casecaded from the parent object
to the associated object. The meaningfull values would be persist , merge, delete,
save_update, evict , replicate, lock , refresh , all , delete_orphan. ...
Ans: Hibernate is ORM tool used for data persistency.Spring is a framework for
enterprise applications with default APIs for presentation, middle tiers and
presistence layers and allows to integrate with various presentations, middle tier and
presistence APIs ...
Ans: Its is one of the most popular ORM technology available to date in the
market.Java bean is a simple resuble component. There is no persistency on bean
hibernate provides the service to make the bean persistent so that we can make use
of it. In hibernate ...
Ans: We can also specify primary key using annotations in the POJO
using:@javax.persistence.Id before the appropriate field in POJO with @Column
@Id@Column(name="user_id") ...
Ans: Hibernate is based on object oriented concept like java. so it has better
compatibility with java than sql.In Jdbc we have to mannualy handle exception and
every time we need to open/cose the connection,create/close the statement ,
resultset whatever ...
Ans: Basically we need Hibernate like tools for the purpose of developing the
application in short period of time. The product like Hibernate used for the
productivity. When large amount of data have to handle that time instead of using
JDBC we used Hibernate. ...
24.How do you handle the situation where persistence class attribute name is one of
the reserved keyword
How do you handle the situation where persistence class attribute name is one of the
reserved keyword in database; e.g. user ? Will this cause any issue while hibenrate
executes SQL statements behind the scene?
Ans: first things first ..i have just seen ppl venting thier personal grudge over java /
jpa or whatever over this forum.suns official sacceptence that jpa is a failure. please
lets keep it out.as for the answer , JPA is a specification , its nt a frame work ...
Ans: There are two types of Loading in application. Eager loading and Lazy loading.
In eager loading we will fetch all the values from the Persistent storage and cache it.
It will make serious performance issues. There we use lazy loading to avoid that ...
Q2: Which one, among EJB 2.1 and Hibernate, is better?Explain with reason.
Q3: When to use EJB 2.1 and when to use Hibernate? Explain with scenarios.
EJB
Q) SessionBeans
Session beans are not persistence there are short lived beans. S.B can
perform database operations but S.B it self is not a persistence objects. S.B are
business process objects they implements business logic, business rules and
workflow.
Q) Entity Bean
Entity beans are permanent business entities because their state is saved in
permanent data storage. E.B are persistence objects, E.B contain data related logic.
E.B are permanent so if any machine crashes, the E.B can be reconstructed in
memory again by simple reading the data back in from the database.
Q) Object-Relational Mapping
Mapping of objects to relational database is a technology called O.R.M. O.R.M
is a persistence mechanism of persistence objects than simple object serialization.
Q) Deployment Descriptor
D.D contains information for all the beans in the “ejb.jar” file. D.D enables ejb
container to provide implicit services to enterprise bean components, these services
can gain your bean with out coding. D.D is a XML file.
Q) ejbCreate()
In stateless session bean can have only one ejbCreate() method it must take
no arguments. Remember that ejbCreate() is essentially analogous to a constructor
for ejb; it initializes an instance internal state variable. Because the stateless session
bean has no client specific variables.
- 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
Q) How do you determine whether two entity beans are the same?
A) By invoking the EntityBean.isIdentical method. This method should be
implemented by the entity bean developer to determine when two references are to
the same object.
Q) How can you capture if findBy method returns more than one row?
A) If finder method returns more than one row, create or instantiate an object
(which has instance variable equal to number of columns to be stored) each time and
add the object to vector that stores. Vector stores only the memory address not
object reference. So every time when you instantiate and store object into vector a
separate memory address will be allocated and the same is stored in the vector.
There is EntityContext too which is also and EJBContext object that'll be provided to
an EntityBean for the purpose of the EntityBean accessing the container details. In
general, the EJBContext (SessionContext and EntityContext), AppletContext and
ServletContext help the corresponding Java objects in knowing about its 'context'
[environment in which they run], and to access particular information and/or service.
Where as, the javax.naming.Context is for the purpose of 'NAMING' [by the way of
referring to] an object.
SessionContext S.C is your beans gateway to interact with the container, S.C
query the container about your current transactional state, your security state.
ejbCreate()
ejbPassivate( ) If too many beans are instantiated, the container can passivate
some of them .ie write the bean to some temp storage. The container should release
all resources held by the bean. Just before passivating, the container calls the
ejbPassivate() method. So release all resources here, i.e. close socket
connections..etc.
ejbRemove() container wants to remove your bean instance it will call this
method.
Q) What is the need of Remote and Home interface. Why cant it be in one?
The home interface is your way to communicate with the container, that is who is
responsible of creating, locating even removing one or more beans. The remote
interface is your link to the bean, that will allow you to remotely access to all its
methods and members. As you can see there are two distinct elements (the
container and beans) and you need two different interfaces for accessing to both of
them.
Q) Life cycle
- Stateful session bean has 3 states Does Not Exist, Method Ready Pool and
Passivated states.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- Once a container creates one are more instance of a Stateful Session bean it
sets them in a Method Ready State. In this state it can serve requests from
its clients. Like Stateless beans, a new instance is
created(Class.newInstance()), the context is passed (setSessionContext())
and finally the bean is created with the ejbCreate().
- ejbPassivate( ) If too many beans are instantiated, the container can
passivate some of them .ie write the bean to some temp storage. The
container should release all resources held by the bean. Just before
passivating, the container calls the ejbPassivate() method. So release all
resources here,ie,close socket connections..Etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated.
The container then calls the ejbActivate() method. Acquire all the required
resources for the bean in this method. ie get socket connection
- A S.S.B has only two states: Does Not Exist and Method Ready Pool.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- When the EJB container needs one are more beans, it creates and set then in
the Method Ready Pool Sate. This happens through the creation of a new
instance(Class.newInstance()), then it is set its context (setSessionContext())
and finally calls the ejbCreate() method.
TRANSACTION_READ_UNCOMMITTED
The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and
phantom reads can occur. Bean methods with this isolation level can read
uncommitted change.
TRANSACTION_READ_COMMITTED
The transaction cannot read uncommitted data; data that is being changed by a
different transaction cannot be read. Dirty-reads are prevented; nonrepeatable reads
and phantom reads can occur. Bean methods with this isolation level cannot read
uncommitted data.
TRANSACTION_REPEATABLE_READ
The transaction cannot change data that is being read by a different transaction.
Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean
methods with this isolation level have the same restrictions as Read Committed and
can only execute repeatable reads.
TRANSACTION_SERIALIZABLE
The transaction has exclusive read and update privileges to data; different
transactions can neither read nor write the same data. Dirty reads, nonrepeatable
reads, and phantom reads are prevented. This isolation level is the most restrictive.
Dirty-read When your application reads data from a database that has not been
committed to permanent storage yet.
Un-repeatable read When a component reads some data from a database, but
upon reading the data, the data has been changed. This can arise when another
concurrently executing transaction modifies the data being read.
Q) Transaction Attributes
TX_SUPPORTS When a client call this it runs only in a transaction if the client
had one running already; it then joins that transaction. If no transaction, the bean
runs with no transaction at all.
Q) ACID Properties
When you properly use transaction your operations will execute ACID
properties.
Atomicity Guarantees that many operations are bundled together and appears as
one contiguous unit of work.
Ex:- When you transfer money from one bank account to another you want to add
funds to one account and remove funds from the other transaction and you want
both operations to occur or neither to occur.
DOM SAX
1. Tree of nodes 1.Sequence of events
2. Occupies more memory 2.Does not use any memory
preferred for small XML preferred for large documents.
documents 3.Faster at runtime
3. Slower at runtime 4.Objects are to be created
4. Stored as objects 5.Need to write code for
5. Programmatically easy, since creating objects are to referred
objects 6.backward navigation is not
6. Easy of navigation possible
7. DOM creates a tree structure in
memory
Q) Hot deployment
Hot Deployment in Web Logic is he acts of deploying, re-deploying and un-deploying
EJBs while the server is still running.
Q) Clustering
In J2ee container can be distributed, a distributed container consists of
number of JVM’s running on one are more host machines. In this setup, application
components can be deployed on a number of JVM’s. Subject to the type of loading
strategy and the type of the component the container can distributed the load of
incoming request to one of these JVM’s.
Each web application should be contained in a war (web archive) file. War files are
nothing but a jar file containing atleast one descriptor called web.xml. The file
structure of war file is:
/--
|
| WEB-INF
| |
| |-- WEB.XML (Deployment descriptor)
| |-- classes (Folder containing servlets and JSPs
|
| META-INF
| |
| |-- MANIFEST.MF
|
| all utility files and resources like error pages etc.
Each enterprise bean is stored in a jar file. The jar file contains all standard files like
manifest and atleast one additional file called ejb-jar.xml. The structure of a jar file
is:
/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- ejb-jar.xml
|
| all classes as in a normal jar file.
Both jar and war files are placed inside a ear (enterprise archive) file. The structure
of an ear file is
/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- application.xml
|
| jar and war files.
<ejb-jar>
<description>
This Deployment includes all the beans needed to make a reservation:
TravelAgent, ProcessPayment, Reservation, Customer, Cruise, and Cabin.
</description>
<enterprise-beans>
<session>
<ejb-name>TravelAgentBean</ejb-name>
<remote>com.titan.travelagent.TravelAgent</remote>
...
</session>
<entity>
<ejb-name>CustomerBean</ejb-name>
<remote>com.titan.customer.Customer</remote>
...
</entity>
</enterprise-beans>
<! – Transactions in EJB -- >
Q) Weblogic-ejb-jar.xml
<weblogic-ejb-jar>
<weblogic-enterprise-bean>
<ejb-name>demo.Story</ejb-name>
<entity-descriptor>
<entity-cache>
<max-beans-in-cache>100</max-beans-in-cache>
<idle-timeout-seconds>600</idle-timeout-seconds>
<read-timeout-seconds>0</read-timeout-seconds>
<concurrency-strategy>Database</concurrency-strategy>
</entity-cache>
<lifecycle>
<passivation-strategy>default</passivation-strategy>
</lifecycle>
<persistence>
<delay-updates-until-end-of-tx>true</delay-updates-until-end-of-tx>
<finders-load-bean>true</finders-load-bean>
<persistence-type>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
<type-storage>META-INF/weblogic-rdbms11-persistence-
600.xml</type-storage>
</persistence-type>
<db-is-shared>true</db-is-shared>
<persistence-use>
<type-identifier>WebLogic_CMP_RDBMS</type-identifier>
<type-version>5.1.0</type-version>
</persistence-use>
</persistence>
<entity-clustering>
<home-is-clusterable>true</home-is-clusterable>
</entity-clustering>
</entity-descriptor>
<transaction-descriptor>
<trans-timeout-seconds>30</trans-timeout-seconds>
</transaction-descriptor>
<enable-call-by-reference>true</enable-call-by-reference>
<jndi-name>demo.StoryHome</jndi-name>
</weblogic-enterprise-bean>
</weblogic-ejb-jar>
Remote Interface
public interface Hello extends javax.ejb.EJBObject {
public String hello() throws java.rmi.RemoteException;
}
Home Interface
public interface HelloHome extends javax.ejb.EJBHome {
Hello create() throws java.rmi.RemoteException; javax.ejb.CreateException;
}
Bean Class
public class HelloBean implements javax.ejb.SessionBean {
private SessionContex ctx;
public void ejbCreate();
public abstract void ejbRemove();
public abstract void ejbActivate();
public abstract void ejbPassivate();
public abstract void setSessionContext(SessionyContext ctx);
Client
public class HelloClient {
public static void main(String args[ ])
properties props = system.getProperties();
Context ctx = new InitialContext(props);
Object obj = ctx.lookup(“HelloHome”);
HelloHome home = (HelloHome)
javax.rmi.protableRemoteObject.narrow(obj, HelloHome.class);
Hello hello = home.create();
System.out.println(hello.hello());
Hello.remove();
}
Client
package test.entity.home;
import javax.naming.*;
Design
Patterns
J2EE Design Patterns
Tier Pattern Name
Presentation Tier ? Intercepting Filter
? Front Controller
? View Helper
? Composite view
? Service to Worker
? Dispacther View
Business Tier ? Business Delegate
? Value Object
? Session Façade
? Composite Entity
? Value Object Assembler
? Value List Handler
? Service Locator
Integration Tier ? Data Access Object
? Service Activator
Q) What is a Desing Pattern? Why use patterns?
A) A pattern describes a proven solution to a recurring design problem. Patterns
provide a ready-made solution that can be adapted to different problems as
necessary.
Composite Entity :It model, represent, and manage a set of interrelated persistent
objects rather than representing them as individual fine-grained entity beans. A
Composite Entity bean represents a graph of objects.
Front Controller
It will dispatch the request to the correct resource, Centralized controller for
managing and holding of a request.
Service Locator
To access different resources/services, J2EE compatible server binds these
resources/services to the JNDI server so that the clients can lookup those
resources/services through JNDI lookup process from anywhere in the network. The
resources/services can be
1. EJBHome objects 2. DataSource objects 3. JMS
ConnectionFactory 4. JMS Topic/Queue etc.
All these services need to bind to the JNDI services and the clients need to lookup
JNDI to get those services. Clients have to go through JNDI lookup process every
time to work with these services. JNDI lookup process is expensive because clients
need to get network connection to the JNDI server if the JNDI server is located on a
different machine and need to go through lookup process every time, this is
redundant and expensive.
The solution for the redundant and expensive JNDI lookup process problem is
to cache those service objects when the client performs JNDI lookup first time and
reuse that service object from the cache second time onwards for other clients. This
technique maintains a cache of service objects and looks up the JNDI only first time
for a service object.
Session Façade
EJB clients (swing, servlets, jsps etc) can access entity beans directly. If EJB
clients access entity beans directly over the network, it takes more network calls and
Here the servlet calls multiple entity beans directly to accomplish a business process,
thereby increasing the number of network calls.
The solution for avoiding number of network calls due to directly accessing
multiple entity beans is to wrap entity beans with session bean (Facade). The EJB
client accesses session bean (Facade) instead of entity beans through coarse grained
method call to accomplish a business process.
Message Facade
Session bean and entity bean methods execute synchronously that means the
method caller has to wait till a value is returned. In some situations like sending
hundred's of mails or firing a batch process or updating processes, the client does
not have to bother about return value. If you use synchronous session and entity
beans in such situations, they take a long time to process methods and clients have
to wait till the method returns a value.
The solution for avoiding many network calls due to fine-grained method calls is to
use coarse-grained approach. For example:
// Create a Value Object and fill that object locally
PersonInfo person = new PersonInfo();
person.setName("Ravi");
person.setCity("Austin");
// send Value Object through network
Value Object is an object that is passed over the network rather than passing each
attributes separately thus increasing performance by reducing network calls.
ValueObjectFactory
For a single request, a client might need to access multiple server side
components such as different session beans and entity beans. In such
situations the client accesses multiple components over the network, this increases
the network traffic and has an impact on the performance.
J2EE applications generally have the search facility and have to search huge
data and retrieve results. If an application returns huge queried data to the client,
the client takes long time to retrieve that large data and if that application uses
entity bean to search data, it has an impact on.
Singleton
You can achieve this by having the private constructor in the class, so that other
classes can't create a new instance. Its intent is to ensure that a class has only one
instance, and to provide a global point of access to it. There are many situations in
which a singleton object is necessary: a GUI application must have a single mouse,
an active modem needs one and only one telephone line, an operating system can
only have one window manager, and a PC is connected to a single keyboard
1.Create a Private constructor, so that outside class can not access this
constructor. And declare a private static reference of same class.
Q) What is the difference between J2EE design patterns and the Gang of
Four patterns?
A) The GOF design patterns apply generically to any object-oriented programming
language. J2EE design patterns address common problems encountered in designing
J2EE architecture. This course presents the key J2EE design patterns required when
implementing a J2EE system.
Database
Concepts
Q) DML insert, update, delete
DDL create, alter, drop, truncate, rename.
DQL select
DCL grant, revoke.
TCL commit, rollback, savepoint.
Q) Normalization
Normalization is the process of simplifying the relationship between data
elements in a record.
(i) 1st normal form: - 1st N.F is achieved when all repeating groups are removed,
and P.K should be defined. big table is broken into many small tables, such that each
table has a primary key.
(ii) 2nd normal form: - Eliminate any non-full dependence of data item on record
keys. I.e. The columns in a table which is not completely dependant on the primary
key are taken to a separate table.
(iii) 3rd normal form: - Eliminate any transitive dependence of data items on P.K’s.
i.e. Removes Transitive dependency. Ie If X is the primary key in a table. Y & Z are
columns in the same table. Suppose Z depends only on Y and Y depends on X. Then
Z does not depend directly on primary key. So remove Z from the table to a look up
table.
Foreign key constraint prevents any actions that would destroy link between tables
with the corresponding data values. A foreign key in one table points to a primary
key in another table. Foreign keys prevent actions that would leave rows with foreign
key values when there are no primary keys with that value. The foreign key
constraints are used to enforce referential integrity.
CHECK constraint is used to limit the values that can be placed in a column. The
check constraints are used to enforce domain integrity.
NOT NULL constraint enforces that the column will not accept null values. The not
null constraints are used to enforce domain integrity, as the check constraints.
Q) How to find out duplicate rows & delete duplicate rows in a table?
A) MPID EMPNAME EMPSSN
----- ---------- -----------
1 Jack 555-55-5555
2 Mike 555-58-5555
3 Jack 555-55-5555
4 Mike 555-58-5555
SQL> select count (empssn), empssn from employee group by empssn
having count (empssn) > 1;
Syntax: -
Create [or replace] [public] synonym [schema.] synonym_name for [schema.]
object_name;
or replace -- allows you to recreate the synonym (if it already exists) without having
to issue a DROP synonym command.
Public -- means that the synonym is a public synonym and is accessible to all users.
Schema -- is the appropriate schema. If this phrase is omitted, Oracle assumes that
you are referring to your own schema.
object_name -- is the name of the object for which you are creating the synonym. It
can be one of the following:
Table Package
View materialized view
sequence java class schema object
stored procedure user-defined object
Function Synonym
example:
Create public synonym suppliers for app. suppliers;
Example demonstrates how to create a synonym called suppliers. Now, users of
other schemas can reference the table called suppliers without having to prefix the
table name with the schema named app. For example:
Select * from suppliers;
If this synonym already existed and you wanted to redefine it, you could always use
the or replace phrase as follows:
Create or replace public synonym suppliers for app. suppliers;
Dropping a synonym
It is also possible to drop a synonym.
drop [public] synonym [schema .] Synonym_name [force];
public -- phrase allows you to drop a public synonym. If you have specified public,
then you don't specify a schema.
Force -- phrase will force Oracle to drop the synonym even if it has dependencies. It
is probably not a good idea to use the force phrase as it can cause invalidation of
Oracle objects.
Example:
Drop public synonym suppliers;
This drop statement would drop the synonym called suppliers that we defined earlier.
Q) What techniques are used to retrieve data from more than one table in a
single SQL statement?
A) Joins, unions and nested selects are used to retrieve data.
Q) DISTINCT clause?
A) The DISTINCT clause allows you to remove duplicates from the result set.
> SELECT DISTINCT city FROM supplier;
Q) COUNT function?
A) The COUNT function returns the number of rows in a query
> SELECT COUNT (*) as "No of emps" FROM employees WHERE salary >
25000;
Q) What keyword does an SQL SELECT statement use for a string search?
A) The LIKE keyword allows for string searches. The % sign is used as a wildcard.
Q) What is a NULL value? What are the pros and cons of using NULLS?
A) NULL value takes up one byte of storage and indicates that a value is not present
as opposed to a space or zero value. A NULL in a column means no entry has been
made in that column. A data value for the column is "unknown" or "not available."
Unique Index :
A unique index means that two rows cannot have the same index value.
>CREATE UNIQUE INDEX index_name ON table_name (column_name)
When the UNIQUE keyword is omitted, duplicate values are allowed. If you want to
index the values in a column in descending order, you can add the reserved word
DESC after the column name:
>CREATE INDEX PersonIndex ON Person (LastName DESC)
If you want to index more than one column you can list the column names within the
parentheses.
>CREATE INDEX PersonIndex ON Person (LastName, FirstName)
The comparison operator is the equality and the logical operation between
IN
values is OR.
ANY Allows to check if at least a value of the list satisfies condition.
ALL Allows to check if condition is realized for all the values of the list.
If the subquery returns a result, the value returned is True otherwise the
EXISTS
value returned is False.
Q) What are some sql Aggregates and other Built-in functions?
A) AVG, SUM, MIN, MAX, COUNT and DISTINCT.
Security
Concepts
Basic Authentication Is a security model in this the client must authenticate itself
with user id and password for each resource to access. In this the user id and
password are sent by the client in base-64 encoded string, the server decode the
string and looks in the data base for match. If it finds a match grant access to the
requested resource.
Digest Authentication In this the user id and password does not send across the
network instead send a digest representation of password.