Monday, 22 September 2014

Features:
New features in J2SE 1.4

    * XML Processing
    * Java Print Service
    * Logging API
    * Java Web Start
    * JDBC 3.0 API
    * Assertions
    * Preferences API
    * Chained Exception
    * IPv6 Support
    * Regular Expressions
    * Image I/O API

New features in J2SE 5.0

    * Generics
    * Enhanced for Loop
    * Autoboxing/Unboxing
    * Typesafe Enums
    * Varargs
    * Static Import
    * Metadata (Annotations)
    * Instrumentation

New features in Java SE 6

    * Scripting Language Support
    * JDBC 4.0 API
    * Java Compiler API
    * Pluggable Annotations
    * Native PKI, Java GSS, Kerberos and LDAP support.
    * Integrated Web Services.
    * Lot more enhancements.


New features in Java SE 7

    * Strings in switch Statement
    * Type Inference for Generic Instance Creation
    * Multiple Exception Handling
    * Support for Dynamic Languages
    * Try with Resources
    * Java nio Package
    * Binary Literals, underscore in literals
    * Diamond Syntax
    * Automatic null Handling

New features in Java SE 8

   * Lamda Expressions
    * Parallel Sort
    * Generic Type changes and improvements
    * Stream Collection Types (java.util.stream)
    * Functional Interfaces (java.util.function)
    * Nashorn – The Node.js on JVM
    * Date/Time changes (java.time)
    * Type Annotations
    * Addition of Calendar.Builder
    * Replacement of PremGen with Metaspace
    * Other – (nice to have) Changes

JAVA SE:
Describe what happens when an object is created in Java?

Several things happen in a particular order to ensure the object is constructed properly: 
1. Memory is allocated from heap to hold all instance variables and implementation-specific data of the object and its superclasses. Implementation-specific data includes pointers to class and method data. 
2. The instance variables of the objects are initialized to their default values. 
3. The constructor for the most derived class is invoked. The first thing a constructor does is call the constructor for its uppercase. This process continues until the constructor for java.lang.Object is called, as java.lang.Object is the base class for all objects in java. 
4. Before the body of the constructor is executed, all instance variable initializers and initialization blocks are executed. Then the body of the constructor is executed. Thus, the constructor for the base class completes first and constructor for the most derived class completes last.


In Java, you can create a String object as below : String str = "abc"; & String str = new String("abc");  Why cant a button object be created as : Button bt = "abc"? Why is it compulsory to create a button object as: Button bt = new Button("abc"); Why this is not compulsory in String’s case?

Button bt1= "abc"; It is because "abc" is a literal string (something slightly different than a String object, by-the-way) and bt1 is a Button object. That simple. The only object in Java that can be assigned a literal String is java.lang.String. Important to not that you are NOT calling a java.lang.String constuctor when you type String s = "abc"; For example String x = "abc"; String y = "abc"; refer to the same object. While String x1 = new String("abc"); 
String x2 = new String("abc"); refer to two different objects.

What is the advantage of OOP? 

You will get varying answers to this question depending on whom you ask. Major advantages of OOP are: 
1. Simplicity: software objects model real world objects, so the complexity is reduced and the program structure is very clear; 
2. Modularity: each object forms a separate entity whose internal workings are decoupled from other parts of the system; 
3. Modifiability: it is easy to make minor changes in the data representation or the procedures in an OO program. Changes inside a class do not affect any other part of a program, since the only public interface that the external world has to a class is through the use of methods; 
4. Extensibility: adding new features or responding to changing operating environments can be solved by introducing a few new objects and modifying some existing ones; 
5. Maintainability: objects can be maintained separately, making locating and fixing problems easier; 
6. Re-usability: objects can be reused in different programs

What are the main differences between Java and C++?

Everything is an object in Java( Single root hierarchy as everything gets derived from java.lang.Object). Java does not have all the complicated aspects of C++ ( For ex: Pointers, templates, unions, operator overloading, structures etc..)  The Java language promoters initially said "No pointers!", but when many programmers questioned how you can work without pointers, the promoters began saying "Restricted pointers." You can make up your mind whether it’s really a pointer or not. In any event, there’s no pointer arithmetic. There are no destructors in Java. (automatic garbage collection),  Java does not support conditional compile (#ifdef/#ifndef type). Thread support is built into java but not in C++. Java does not support default arguments. There’s no scope resolution operator :: in Java. Java uses the dot for everything, but can get away with it since you can define elements only within a class. Even the method definitions must always occur within a class, so there is no need for scope resolution there either. There’s no "goto " statement in Java. Java doesn’t provide multiple inheritance (MI), at least not in the same sense that C++ does. Exception handling in Java is different because there are no destructors. Java has method overloading, but no operator overloading. The String class does use the + and += operators to concatenate strings and String expressions use automatic type conversion, but that’s a special built-in case. Java is interpreted for the most part and hence platform independent

What are interfaces?

Interfaces provide more sophisticated ways to organize and control the objects in your system. 
The interface keyword takes the abstract concept one step further. You could think of it as a “pure” abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but The interface keyword takes the abstract concept one step further. You could think of it as a “pure” abstract class. It allows the creator to establish the form for a class: method names, argument lists, and return types, but no method bodies. An interface can also contain fields, but an interface says: “This is what all classes that implement this particular interface will look like.” Thus, any code that uses a particular interface knows what methods might be called for that interface, and that’s all. So the interface is used to establish a “protocol” between classes. (Some object-oriented programming languages have a keyword called protocol to do the same thing.)  Typical example from "Thinking in Java": 

import java.util.*; 
interface Instrument { 
int i = 5; // static & final 
// Cannot have method definitions: 
void play(); // Automatically public 
String what(); 
void adjust(); 
class Wind implements Instrument { 
public void play() { 
System.out.println("Wind.play()"); 
public String what() { return "Wind"; } 
public void adjust() {} 
}

How can you achieve Multiple Inheritance in Java?

Java’s interface mechanism can be used to implement multiple inheritance, with one important difference from c++ way of doing MI: the inherited interfaces must be abstract. This obviates the need to choose between different implementations, as with interfaces there are no implementations. 

interface CanFight { 
void fight(); 
}
interface CanSwim { 
void swim(); 
}
interface CanFly { 
void fly(); 
}
class ActionCharacter { 
public void fight() {} 
}
class Hero extends ActionCharacter implements CanFight, CanSwim, CanFly { 
public void swim() {} 
public void fly() {} 
}

You can even achieve a form of multiple inheritance where you can use the *functionality* of classes rather than just the interface:

interface A { 
void methodA(); 
class AImpl implements A { 
void methodA() { //do stuff } 
interface B { 
void methodB(); 
class BImpl implements B { 
void methodB() { //do stuff } 
class Multiple implements A, B { 
private A a = new A(); 
private B b = new B(); 
void methodA() { a.methodA(); } 
void methodB() { b.methodB(); } 
This completely solves the traditional problems of multiple inheritance in C++ where name clashes occur between multiple base classes. The coder of the derived class will have to explicitly resolve any clashes. Don’t you hate people who point out minor typos? Everything in the previous example is correct, except you need to instantiate an AImpl and BImpl. So class Multiple would look like this: 
class Multiple implements A, B { 
private A a = new AImpl(); 
private B b = new BImpl(); 
void methodA() { a.methodA(); } 
void methodB() { b.methodB(); } 

What is the difference between StringBuffer and String class?

A string buffer implements a mutable sequence of characters. A string buffer is like a String, but can be modified. At any point in time it contains some particular sequence of characters, but the length and content of the sequence can be changed through certain method calls. The String class represents character strings. All string literals in Java programs, such as "abc" are constant and implemented as instances of this class; their values cannot be changed after they are created. Strings in Java are known to be immutable. What it means is that every time you need to make a change to a String variable, behind the scene, a "new" String is actually being created by the JVM. For an example: if you change your String variable 2 times, then you end up with 3 Strings: one current and 2 that are ready for garbage collection. The garbage collection cycle is quite unpredictable and these additional unwanted Strings will take up memory until that cycle occurs. For better performance, use StringBuffers for string-type data that will be reused or changed frequently. There is more overhead per class than using String, but you will end up with less overall classes and consequently consume less memory. Describe, in general, how java’s garbage collector works? The Java runtime environment deletes objects when it determines that they are no longer being used. This process is known as garbage collection. The Java runtime environment supports a garbage collector that periodically frees the memory used by objects that are no longer needed. The Java garbage collector is a mark-sweep garbage collector that scans Java’s dynamic memory areas for objects, marking those that are referenced. After all possible paths to objects are investigated, those objects that are not marked (i.e. are not referenced) are known to be garbage and are collected. (A more complete description of our garbage collection algorithm might be "A compacting, mark-sweep collector with some conservative scanning".) The garbage collector runs synchronously when the system runs out of memory, or in response to a request from a Java program. Your Java program can ask the garbage collector to run at any time by calling System.gc(). The garbage collector requires about 20 milliseconds to complete its task so, your program should only run the garbage collector when there will be no performance impact and the program anticipates an idle period long enough for the garbage collector to finish its job. Note: Asking the garbage collection to run does not guarantee that your objects will be garbage collected. The Java garbage collector runs asynchronously when the system is idle on systems that allow the Java runtime to note when a thread has begun and to interrupt another thread (such as Windows 95). As soon as another thread becomes active, the garbage collector is asked to get to a consistent state and then terminate. 

What’s the difference between == and equals method? 

equals checks for the content of the string objects while == checks for the fact that the two String objects point to same memory location ie they are same references. 

What are abstract classes, abstract methods? 

Simply speaking a class or a method qualified with "abstract" keyword is an abstract class or abstract method. You create an abstract class when you want to manipulate a set of classes through a common interface. All derived-class methods that match the signature of the base-class declaration will be called using the dynamic binding mechanism. If you have an abstract class, objects of that class almost always have no meaning. That is, abstract class is meant to express only the interface and sometimes some default method implementations, and not a particular implementation, so creating an abstract class object makes no sense and are not allowed ( compile will give you an error message if you try to create one). An abstract method is an incomplete method. It has only a declaration and no method body. Here is the syntax for an abstract method declaration: abstract void f(); If a class contains one or more abstract methods, the class must be qualified an abstract. (Otherwise, the compiler gives you an error message.). It’s possible to create a class as abstract without including any abstract methods. This is useful when you’ve got a class in which it doesn’t make sense to have any abstract methods, and yet you want to prevent any instances of that class. Abstract classes and methods are created because they make the abstractness of a class explicit, and tell both the user and the compiler how it was intended to be used. 
For example: 
abstract class Instrument { 
int i; // storage allocated for each 
public abstract void play(); 
public String what() { 
return "Instrument"; 
public abstract void adjust(); 
class Wind extends Instrument { 
public void play() { 
System.out.println("Wind.play()"); 
public String what() { return "Wind"; } 
public void adjust() {} 
Abstract classes are classes for which there can be no instances at run time. i.e. the implementation of the abstract classes are not complete. Abstract methods are methods which have no defintion. i.e. abstract methods have to be implemented in one of the sub classes or else that class will also become Abstract.

JDBC:

1. Why do I get UnsatisfiedLinkError when I try to use my JDBC driver? 

The first thing is to be sure that this does not occur when running non-JDBC apps. If so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then it’s time to check the documentation that came with the driver or the driver/DBMS support. JDBC driver types 1 through 3 have some native code aspect and typically require some sort of client install. Along with the install, various environment variables and path or classpath settings must be in place. Because the requirements and installation procedures vary with the provider, there is no reasonable way to provide details here. A type 4 driver, on the other hand, is pure Java and should never exhibit this problem. The trade off is that a type 4 driver is usually slower.

2. How do I check in my code whether a maximum limit of database connections have been reached? 

Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited or, unfortunately, unknown. Of course, driverManager.getConnection() will throw an exception if a Connection can not be obtained.

3. What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?

You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

4. How do you handle your own transaction ?

A Connection Object has a method called setAutocommit. For handling our own transaction we can set the parameter to false and begin your transaction . Finally commit the transaction by calling the commit method.

5. What does Class.forName return?

A class as loaded by the classloader.

6. What does setAutoCommit do?

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

7. What are the different types of Statements?

Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)
How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a
Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.
PreparedStatement updateSales =
con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

8. What is DriverManager ?

A DriverManager is a class in java.sql package. It is the basic service for managing a set of JDBC drivers.

9. How can you retrieve data from the ResultSet?

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.
ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString(”COF_NAME”);

10. What is the advantage of denormalization?

A Data denormalization is reverse procedure, carried out purely for reasons of improving performance. It maybe efficient for a high-throughput system to replicate data for certain data.

11. What is cold backup, hot backup, warm backup recovery?

A Cold backup means all these files must be backed up at the same time, before the database is restarted. Hot backup (official name is ‘online backup’ ) is a backup taken of each tablespace while the database is running and is being accessed by the users

12. Is the JDBC-ODBC Bridge multi-threaded?

No. The JDBC-ODBC Bridge does not support multi threading. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading.

13. What are the different JDB drivers available?

Type 1 : JDBC-ODBC Bridge Driver – A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun.

Type 2: Native API Partly Java Driver- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Type 3: Network protocol Driver- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.

Type 4: JDBC Net pure Java Driver – A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

14. What is Connection pooling?

A Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.

15. What is a ResultSet ?

A table of data representing a database result set, which is usually generated by executing a statement that queries the database.
A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row.

16. What is the fastest type of JDBC driver? 

JDBC driver performance will depend on a number of issues:
(a) the quality of the driver code,
(b) the size of the driver code,
(c) the database server and its load,
(d) network topology,
(e) the number of times your request is translated to a different API.


17. How does a custom RowSetReader get called from a CachedRowSet? 

The Reader must be registered with the CachedRowSet using CachedRowSet.setReader(javax.sql.RowSetReader reader). Once that is done, a call to CachedRowSet.execute() will, among other things, invoke the readData method.


18 How can I create a custom RowSetMetaData object from scratch? 

One unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most commonly available and offers the sun.jdbc.rowset.RowSetMetaDataImpl class. After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to set the Column Count for a row and the Column Types for each column in the row. For a working code example that includes a custom RowSetMetaData.


19. Where can I find info, frameworks and example source for writing a JDBC driver? 

There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open Source JDBC driver framework. Any driver writer should also review For Driver Writers

20. How can I retrieve a String or other object type without creating a new object each time? 

Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object.


21. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection? 

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.


22. Is the JDBC-ODBC Bridge multi-threaded? 

No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won’t get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.


23. How do I retrieve a whole row of data at once, instead of calling an individual ResultSet.getXXX method for each column?

The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.


24. I want to learn java connectivity with oracla.How?

You should have Driver for connectivity and
1) Load that driver in your class
   By help of Class.forNamr(Driver)
2) Than get the connection
   Connection con = null;
   con =   DriverManger.getDataBaseConnection(url,user,password).
3) Create statement help of connection
   Statement st = con.createStatement("Select * From tbl......");
4) Execute Statement
     ResultSet rs = null;
      rs= st.execute();
5) Get you result from resultset



25. What are the steps involved in establishing a JDBC connection?

This action involves two steps: loading the JDBC driver and making the connection.

26. How can you load the drivers?

Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:

Class.forName(”sun.jdbc.odbc.JdbcOdbcDriver”);

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ, you would load the driver with the following line of code:

Class.forName(”jdbc.DriverXYZ”);


27. What will Class.forName do while loading drivers? 

It is used to create an instance of a driver and register it with the
DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.
4.How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
The following line of code illustrates the general idea:

String url = “jdbc:odbc:Fred”;
Connection con = DriverManager.getConnection(url, “Fernanda”, “J8?);

28. How can you create JDBC statements and what are they?

A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object

Statement stmt = con.createStatement();

29. How can you retrieve data from the ResultSet?

JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.

ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);
String s = rs.getString(”COF_NAME”);

The method getString is invoked on the ResultSet object rs, so getString() will retrieve (get) the value stored in the column COF_NAME in the current row of rs. 

30. What are the different types of Statements?

Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall)

31. How can you use PreparedStatement? This special type of statement is derived from class 
Statement.If you need a Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first.

PreparedStatement updateSales =
con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");

32. What does setAutoCommit do?

When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

con.setAutoCommit(false);

Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly.

con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);

33. How do you call a stored procedure from JDBC?

The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored procedure.

CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();

34. How do I retrieve warnings?

SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object:

SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
System.out.println("n---Warning---n");
while (warning != null)
{
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}

35. How can you move the cursor in scrollable result sets?

One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.

Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);

The first argument is one of three constants added to the ResultSet API to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must also specify whether it is read-only or updatable. Also, you must specify the type first, and because both parameters are of type int , the compiler will not complain if you switch the order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set, that is, one in which the cursor moves only forward. If you do not specify any constants for the type and updatability of a ResultSet object, you will automatically get one that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.

36. What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?

You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened:

Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet srs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}

37. How to Make Updates to Updatable Result Sets?

Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method.

Connection con =
DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs =

stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");

Servlets:

LIFE CYCLE OF SERVLET

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. The life cycle of a servlet can be categorized into four parts:

   1.  Loading and instantiation:-The servlet container loads the servlet during startup or when the first request is made .After loading of servlet container create the instance of the servlet
   2.  Initialization:-When creating the instances,after that the servlet container calls the init() method .then passes the servlet initialization parameters to the init() method. init() method is called once through out the life cycle of servlet
   3.  Servicing the request :-After successfully initialization ,servlet container  call the service method for servising any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object
   4.  The servlet Destroying :-If  the servlet is no longer required for servicing any request, the servlet container will  calls the destroy() method .

ADVANTAGES OF JAVA SERVLET
Java servlet provide various advantages to build a server side programming. Following are the advantages of java

   1.  Portable:- As servlets are written in java and follow  APIs of java so they are very high portable over operating systems and serve implementations.
   2.  Efficient:- As compared to CGI applications servlet is more efficient
   3.  Extensibility:-The servlet API is designed in such a way that it can be easily extensible. As for now   the servlet API support Http Servlets, but in later  it can be extended for another type of servlet
   4.  Safety:- as java is safe servlets are also safe ,garbage collection prevent the leakage of memory and exception handling throws the exceptions for the errors.

BASIC SERVLET STRUCTURE

import java.io.*;
import  javax.servlet.*;
import javax.servlet.http.*;
public class Servletname extends HttpServlet

{
public void doGet (HttpRequest request,HttpResponse response) throws ServletException, IOException
{
//code for business logic
//use request object to read client request
//user response object to throw output back to the client
}//close do get
}

Servlet life cycle include mainly four steps init()--->service()--->doGet() or doPost()--->destroy

A SERVLET PROGRAM (using its life cycle)


//servlet program using its life-cycle
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Testservlet extends HttpServlet
{
int i;
public void init() trows ServletException
{
i=0; //initializing i value
}
//incrementing i value in doGet method
public void doGet(HttpServletRequest request, HttpServletReponse response)
throws IOEXception ,ServletException
{

response.setContentType("text/html");
PrintWriter out= resonse.getWriter():
if (i==0)
{
out.println("<html>");
out.prinln ("<head>");
out.println ("<title> Hello world </title>");
out.println ("</head>");
out.println ("<body>");
out.println ("<h1> value of i is initialized in init method </h1>"+"<h1>" + i + "</h1>"
out.println("</body>");
out.println ("</html>");

}

i = i+;
if ((i == 10)
{
out.println("<html>");
out.println("<head>");
out.println ("<title> HEllo world</title>");
out.println ("</head>");
out.println ("<body>");
out.println ("<h1> i's value reaches 10 hence calling destroy method to reset it </h1>' + "<h1>" + "</h1>");
out.println ("</body>")
out.println ("<html>");
destroy(); //call destroy method if i=10
}
            if (i<10) //display increment value of i
            {
out.prinln("<html>");
out.prinln("<head>");
out.prinln("<title> Hello world </title>");
   out.prinln("<head>");
out.prinln("<body>");
    out.prinln("<h1> value of i incremented in doGet </h1>"  + "<h1>" + i + "<h1>");
out.prinln("</body>");
out.prinln("</html>");
            }
}

public void destroy()//reset i value here

{
i=0;

}
}

RUNNING SERVLET
To run servlet first install and configure the server on your system. web server is required to install to run the servlet.

To compileAnd Run:
javac ExampServlet.java
Servlets can be called directly by typing their uniform resource locator (URL) into a browser's location window after you've started the server.
Servlets can also be invoked from an HTML form by specifying their URL in the definition for a Submit button, for example.
Servlets can be called by any program that can open an hypertext transfer protocol (HTTP) request.

web.xml file?
Web. xml file also called "web Deployment descriptor" allows us to configure our web application inside the Servlet containerHere we can specify the name of our web application, define our Java Servlets, specify initialization parameters for Servlets, define tag libraries, and a whole lot more. This file is placed inside the /WEB-INF folder. we use two of the features of 'web.xml' file; name of Servlet and the Servlet mapping to a URL. This will allow us to access our Servlet using a URL like /TestServlet.


<?xml version="1.0"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>servlets.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>

To run a Servlet
Now we need to start Tomcat server. Type the following command at DOS prompt and hit Enter to start the Tomcat server:
C:\apache_tomcat_6.0.14\bin\startup Now open your browser and point to this address: http://localhost:8080/star/Testservlet. You should a get response like following image in your browser window:

1. What is a servlet filter?

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page. Filters provide the ability to encapsulate recurring tasks in reusable units and can be used to transform the response from a servlet or a JSP page. Filters can perform many different types of functions:
  * Authentication
  * Logging and auditing
  * Data compression
  * Localization

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. Filters must be configured in the deployment descriptor :

<!--Servlet Filter that handles site authorization.-->
<filter>
     <filter-name>AuthorizationFilter</filter-name>
     <filter-class>examples.AuthorizationFilter</filter-class>
     <description>This Filter authorizes user access to application components based upon request URI.</description>
     <init-param>
        <param-name>error_page</param-name>
        <param-value>../../error.jsp</param-value>
     </init-param>
</filter>

<filter-mapping>
     <filter-name>AuthorizationFilter</filter-name>
     <url-pattern>/restricted/*</url-pattern>
</filter-mapping>

2. What is a WAR file?

A Web archive (WAR) file is a packaged Web application. WAR files can be used to import a Web application into a Web server. The WAR file also includes a Web deployment descriptor file. There are special files and directories within a WAR file. The /WEB-INF directory in the WAR file contains a file named web.xml which defines the structure of the web application. If the web application is only serving JSP files, the web.xml file is not strictly necessary. If the web application uses servlets, then the servlet container uses web.xml to ascertain to which servlet a URL request is to be routed. One disadvantage of web deployment using WAR files in very dynamic environments is that minor changes cannot be made during runtime. WAR file is created using the standard Java jar tool. For example:

    cd /home/alex/webapps/mywebapp
    jar cf ../mywebapp.war * 

3. What is servlet exception?

ServletException is a subclass of the Exception. It defines a general exception a servlet can throw when it encounters difficulty. ServletException class define only one method getRootCause() that returns the exception that caused this servlet exception. It inherit the other methods like fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString etc from the Throwable class.
Packages that use ServletException :
  * javax.servlet
  * javax.servlet.http


4. What is the difference between an application server and a web server?

A web server deals with Http protocols and serves the static pages as well as it can ask the helper application like CGI program to generate some dynamic content. A web server handles the client request and hands the response back to the client.
An application server exposes business logic to client applications through various protocols, possibly including HTTP. An application server provides access to business logic for use by client application programs. In addition, J2EE application server can run EJBs - which are used to execute business logic. An Application server has a 'built-in' web server, in addition to that it supports other modules or features like e-business integration, independent management and security module, portlets etc.

5. How can you implement singleton pattern in servlets ?

Singleton is a useful Design Pattern for allowing only one instance of your class. you can implement singleton pattern in servlets by using using Servlet init() and <load-on-startup> in the deployment descriptor.

6. Do objects stored in a HTTP Session need to be serializable? Or can it store any object?

It's important to make sure that all objects placed in the session can be serialized if you are building a distributed applicatoin. If you implement Serializable in your code now, you won't have to go back and do it later.

7. What is deployment descriptor?

Deployment descriptor is a configuration file named web.xml that specifies all the pieces of a deployment. It allows us to create and manipulate the structure of the web application. Deployment descriptor describes how a web application or enterprise application should be deployed. For web applications, the deployment descriptor must be called web.xml and must reside in a WEB-INF subdirectory at the web application root. Deployment descriptor allows us to modify the structure of the web application without touching the source code.

8. What is the web container?

The Web container provides the runtime environment through components that provide naming context and life cycle management, security and concurrency control. A web container provides the same services as a JSP container as well as a federated view of the Java EE. Apache Tomcat is a web container and an implementation of the Java Servlet and JavaServer Pages technologies.

9. Is HTML page a web component?

No! Html pages are not web component, even the server-side utility classes are not considered web components. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification.

10. How HTTP Servlet handles client requests?

HTTP Servlet is an abstract class that must be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
  * doDelete(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a DELETE request.
  * doGet(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a GET request.
  * doOptions(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.
  * doPost(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a POST request.
  * doPut(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a PUT request.
  * doTrace(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a TRACE request. etc.

11. What are the uses of ServletResponse interface?

ServletResponse interface defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

Packages that use ServletResponse :
  * javax.servlet
  * javax.servlet.http
  * javax.servlet.jsp  

12. What are the uses of ServletRequest?

LIFE CYCLE OF SERVLET

The life cycle of a servlet is controlled by the container in which the servlet has been deployed. The life cycle of a servlet can be categorized into four parts:

   1. Loading and instantiation:-The servlet container loads the servlet during startup or when the first request is made .After loading of servlet container create the instance of the servlet
   2. Initialization:-When creating the instances,after that the servlet container calls the init() method .then passes the servlet initialization parameters to the init() method. init() method is called once through out the life cycle of servlet
   3. Servicing the request :-After successfully initialization ,servlet container  call the service method for servising any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object
   4. The servlet Destroying :-If  the servlet is no longer required for servicing any request, the servlet container will  calls the destroy() method .

ADVANTAGES OF JAVA SERVLET
Java servlet provide various advantages to build a server side programming. Following are the advantages of java

   1.  Portable:- As servlets are written in java and follow  APIs of java so they are very high portable over operating systems and serve implementations.
   2.  Efficient:- As compared to CGI applications servlet is more efficient
   3.  Extensibility:-The servlet API is designed in such a way that it can be easily extensible. As for now   the servlet API support Http Servlets, but in later  it can be extended for another type of servlet
   4.  Safety:- as java is safe servlets are also safe ,garbage collection prevent the leakage of memory and exception handling throws the exceptions for the errors.

BASIC SERVLET STRUCTURE

import java.io.*;
import  javax.servlet.*;
import javax.servlet.http.*;
public class Servletname extends HttpServlet

{
public void doGet (HttpRequest request,HttpResponse response) throws ServletException, IOException
{
//code for business logic
//use request object to read client request
//user response object to throw output back to the client
}//close do get
}

Servlet life cycle include mainly four steps init()--->service()--->doGet() or doPost()--->destroy

A SERVLET PROGRAM (using its life cycle)


//servlet program using its life-cycle
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Testservlet extends HttpServlet
{
int i;
public void init() trows ServletException
{
i=0; //initializing i value
}
//incrementing i value in doGet method
public void doGet(HttpServletRequest request, HttpServletReponse response)
throws IOEXception ,ServletException
{

response.setContentType("text/html");
PrintWriter out= resonse.getWriter():
if (i==0)
{
out.println("<html>");
out.prinln ("<head>");
out.println ("<title> Hello world </title>");
out.println ("</head>");
out.println ("<body>");
out.println ("<h1> value of i is initialized in init method </h1>"+"<h1>" + i + "</h1>"
out.println("</body>");
out.println ("</html>");

}

i = i+;
if ((i == 10)
{
out.println("<html>");
out.println("<head>");
out.println ("<title> HEllo world</title>");
out.println ("</head>");
out.println ("<body>");
out.println ("<h1> i's value reaches 10 hence calling destroy method to reset it </h1>' + "<h1>" + "</h1>");
out.println ("</body>")
out.println ("<html>");
destroy(); //call destroy method if i=10
}
            if (i<10) //display increment value of i
            {
out.prinln("<html>");
out.prinln("<head>");
out.prinln("<title> Hello world </title>");
   out.prinln("<head>");
out.prinln("<body>");
    out.prinln("<h1> value of i incremented in doGet </h1>"  + "<h1>" + i + "<h1>");
out.prinln("</body>");
out.prinln("</html>");
            }
}

public void destroy()//reset i value here

{
i=0;

}
}

RUNNING SERVLET
To run servlet first install and configure the server on your system. web server is required to install to run the servlet.

To compileAnd Run:
javac ExampServlet.java
Servlets can be called directly by typing their uniform resource locator (URL) into a browser's location window after you've started the server.
Servlets can also be invoked from an HTML form by specifying their URL in the definition for a Submit button, for example.
Servlets can be called by any program that can open an hypertext transfer protocol (HTTP) request.

web.xml file?
Web. xml file also called "web Deployment descriptor" allows us to configure our web application inside the Servlet containerHere we can specify the name of our web application, define our Java Servlets, specify initialization parameters for Servlets, define tag libraries, and a whole lot more. This file is placed inside the /WEB-INF folder. we use two of the features of 'web.xml' file; name of Servlet and the Servlet mapping to a URL. This will allow us to access our Servlet using a URL like /TestServlet.


<?xml version="1.0"?>

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">

<servlet>
<servlet-name>TestServlet</servlet-name>
<servlet-class>servlets.TestServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>TestServlet</servlet-name>
<url-pattern>/TestServlet</url-pattern>
</servlet-mapping>
</web-app>

To run a Servlet
Now we need to start Tomcat server. Type the following command at DOS prompt and hit Enter to start the Tomcat server:
C:\apache_tomcat_6.0.14\bin\startup Now open your browser and point to this address: http://localhost:8080/star/Testservlet. You should a get response like following image in your browser window:

1. What is a servlet filter?

A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page. Filters provide the ability to encapsulate recurring tasks in reusable units and can be used to transform the response from a servlet or a JSP page. Filters can perform many different types of functions:
  * Authentication
  * Logging and auditing
  * Data compression
  * Localization

The filter API is defined by the Filter, FilterChain, and FilterConfig interfaces in the javax.servlet package. You define a filter by implementing the Filter interface. A filter chain, passed to a filter by the container, provides a mechanism for invoking a series of filters. Filters must be configured in the deployment descriptor :

<!--Servlet Filter that handles site authorization.-->
<filter>
     <filter-name>AuthorizationFilter</filter-name>
     <filter-class>examples.AuthorizationFilter</filter-class>
     <description>This Filter authorizes user access to application components based upon request URI.</description>
     <init-param>
        <param-name>error_page</param-name>
        <param-value>../../error.jsp</param-value>
     </init-param>
</filter>

<filter-mapping>
     <filter-name>AuthorizationFilter</filter-name>
     <url-pattern>/restricted/*</url-pattern>
</filter-mapping>

2. What is a WAR file?

A Web archive (WAR) file is a packaged Web application. WAR files can be used to import a Web application into a Web server. The WAR file also includes a Web deployment descriptor file. There are special files and directories within a WAR file. The /WEB-INF directory in the WAR file contains a file named web.xml which defines the structure of the web application. If the web application is only serving JSP files, the web.xml file is not strictly necessary. If the web application uses servlets, then the servlet container uses web.xml to ascertain to which servlet a URL request is to be routed. One disadvantage of web deployment using WAR files in very dynamic environments is that minor changes cannot be made during runtime. WAR file is created using the standard Java jar tool. For example:

    cd /home/alex/webapps/mywebapp
    jar cf ../mywebapp.war *

3. What is servlet exception?

ServletException is a subclass of the Exception. It defines a general exception a servlet can throw when it encounters difficulty. ServletException class define only one method getRootCause() that returns the exception that caused this servlet exception. It inherit the other methods like fillInStackTrace, getLocalizedMessage, getMessage, printStackTrace, printStackTrace, printStackTrace, toString etc from the Throwable class.
Packages that use ServletException :
  * javax.servlet
  * javax.servlet.http


4. What is the difference between an application server and a web server?

A web server deals with Http protocols and serves the static pages as well as it can ask the helper application like CGI program to generate some dynamic content. A web server handles the client request and hands the response back to the client.
An application server exposes business logic to client applications through various protocols, possibly including HTTP. An application server provides access to business logic for use by client application programs. In addition, J2EE application server can run EJBs - which are used to execute business logic. An Application server has a 'built-in' web server, in addition to that it supports other modules or features like e-business integration, independent management and security module, portlets etc.


5. How can you implement singleton pattern in servlets ?

Singleton is a useful Design Pattern for allowing only one instance of your class. you can implement singleton pattern in servlets by using using Servlet init() and <load-on-startup> in the deployment descriptor.

6. Do objects stored in a HTTP Session need to be serializable? Or can it store any object?

It's important to make sure that all objects placed in the session can be serialized if you are building a distributed applicatoin. If you implement Serializable in your code now, you won't have to go back and do it later. 


7. What is deployment descriptor?

Deployment descriptor is a configuration file named web.xml that specifies all the pieces of a deployment. It allows us to create and manipulate the structure of the web application. Deployment descriptor describes how a web application or enterprise application should be deployed. For web applications, the deployment descriptor must be called web.xml and must reside in a WEB-INF subdirectory at the web application root. Deployment descriptor allows us to modify the structure of the web application without touching the source code.

8. What is the web container?

The Web container provides the runtime environment through components that provide naming context and life cycle management, security and concurrency control. A web container provides the same services as a JSP container as well as a federated view of the Java EE. Apache Tomcat is a web container and an implementation of the Java Servlet and JavaServer Pages technologies.


9. Is HTML page a web component?

No! Html pages are not web component, even the server-side utility classes are not considered web components. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification.

10. How HTTP Servlet handles client requests?

HTTP Servlet is an abstract class that must be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:
  * doDelete(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a DELETE request.
  * doGet(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a GET request.
  * doOptions(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a OPTIONS request.
  * doPost(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a POST request.
  * doPut(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a PUT request.
  * doTrace(HttpServletRequest req, HttpServletResponse resp) :  Called by the server (via the service method) to allow a servlet to handle a TRACE request. etc.


11. What are the uses of ServletResponse interface?

ServletResponse interface defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
To send binary data in a MIME body response, use the ServletOutputStream returned by getOutputStream(). To send character data, use the PrintWriter object returned by getWriter(). To mix binary and text data, for example, to create a multipart response, use a ServletOutputStream and manage the character sections manually.

Packages that use ServletResponse :
  * javax.servlet
  * javax.servlet.http
  * javax.servlet.jsp
  

12. What are the uses of ServletRequest?

ServletRequest defines an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and passes it as an argument to the servlet's service method.

A ServletRequest object provides data including parameter name and values, attributes, and an input stream. Interfaces that extend ServletRequest can provide additional protocol-specific data (for example, HTTP data is provided by HttpServletRequest.

Packages that use ServletRequest :
  * javax.servlet
  * javax.servlet.http
  * javax.servlet.jsp

13. What is pre initialization of a servlet?

Servlets are loaded and initialized at the first request come to the server and stay loaded until server shuts down. However there is another way you can initialized your servlet before any request come for that servlet by saying <load-on-startup>1</load-on-startup> in the deployment descriptor. You can specify <load-on-startup>1</load-on-startup> in between the <servlet></servlet> tag.

14. Explain the directory structure of a web application?

The directory structure of a web application consists of two parts.
A private directory called WEB-INF
A public resource directory which contains public resource folder.

WEB-INF folder consists of
1. web.xml file that consist of deployment information.
2. classes directory cosists of business logic.
3. lib directory consists of jar files.

15. How do servlets handle multiple simultaneous requests?

Servlets are under the control of web container. When a request comes for the servlet, the web container find out the correct servelt based on the URL, and create a separeate thread for each request. In this way each request is processed by the different thread simultaneously.

16. Can we call a servlet with parameters in the URL?

Yes! We can call a servlet with parameters in the URL using the GET method. Parameters are appended to the URL separated with the '?' with the URL and if there are more than one parameter, these are separated with the '&' sign.

17. How will you communicate from an applet to servlet?

You can write a servlet that is meant to be called by your applet.
Applet-Servlet Communication with HTTP GET and POST :
The applet can send data to the applet by sending a GET or a POST method. If a GET method is used, then the applet must URL encode the name/value pair parameters into the actual URL string.
Communicating with Object Serialization :
Instead of passing each parameter of student information as name/value pairs, we'd like to send it as a true Java object. Upon receipt of the this object, the servlet would add the this to the database.
Sending Objects from a Servlet to an Applet :
After registering the object in the database. Now the servlet has to return an updated list of registered students that is then returned as a vector of  objects.

18. What is Servlet chaining?

Servlet Chaining is a phenomenon wherein response Object (Output) from first Servlet is sent as request Object (input) to next servlet and so on. The response from the last Servlet is sent back to the client browser.
In Servlets, there are two ways to achieve servlet chaining using javax.servlet.RequestDispatcher:

   1. Include:

    RequestDispatcher rd = req.getRequestDispatcher("Servlet2");
      rd.include(req, resp);

   2. Forward, where req is HttpServletRequest and resp is HttpServletResponse:

    RequestDispatcher rd = req.getRequestDispatcher("Servlet3");
      rd.forward(req, resp);


19. How do you communicate between the servlets?

Servlets can communicate using the request, session and context scope objects by setAttribute() and getAttribute() method. A servlet can placed the information in one of the above scope object and the other can find it easily if it has the reefrence to that object.

20. What is the use of setSecure() and getSecure() in Cookies ?

The setSecure(boolean flag) method indicates to the browser whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL.
The getSecure() method returns true if the browser is sending cookies only over a secure protocol, or false if the browser can send cookies using any protocol.


21. Why we are used setMaxAge() and getMaxAge() in Cookies ?

The "public void setMaxAge(int expiry)" method sets the maximum age of the cookie. After the specified time the cookie will be deleted.

The "public int getMaxAge()" method will return the maximum specified age of the cookie.

22. What is the use of setComment and getComment methods in Cookies ?

A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

The setComment(java.lang.String purpose) method Specifies a comment that describes a cookie's purpose.The getComment() method returns the comment describing the purpose of the cookie, or null if the cookie has no comment.

23. When init() and Distroy() will be called.

Both init() and destroy() method called only once within its lifecycle.
The init() method will be called after instantaition of servlet, i.e. after the constructor calling. The destroy() method will be called when servlet is removed from the server, i.e. when server shuts down.

24. What is life cycle of servlet?

A web container manages the life cycle of the servlet :

  * Loading and Inatantiation: container load the servlet class at the first request to that servlet. The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. Instantiation is done by calling the default constructor.
  * Initialization: calling the init() method.
  * Servicing the Request: calling the service() method and pass the HttpServletRequest and HttpServletResponse object as the parameters.
  * Destroying the Servlet: calling the destroy() method.

25. What is the difference between an applet and a servlet?

Applets are client side java program that are dynamically downloaded over the internet and executed by browser. Servlets are server side program runs on the server. When a request come to server for the specific servlet, then servlet handles the client request, and send response back to the client.
Servlet doesn't have GUI , while applet have GUI. Applet are very heavy to handle as compared to servlet.


26. What is URL Encoding and URL Decoding ?

Some characters are not valid in URLs like & can't be placed in a URL query string without changing the meaning of that query string.

These problems can be be fixed by 'escaping' them. This process involves scanning the text for those characters, and replacing them with a special character-code that browsers can interpret as the correct symbol, without actually using that symbol in your URL.

For example, the escaped character code for '=' is '%3d'.

27. When a session object gets added or removed to the session, which event will get notified ?

When an object is added or removed from a session, the container checks the interfaces implemented by the object. If the object implements the HttpSessionBindingListener, the container calls the matching notification method.
If session is added then sessionCreated() method, and if session is removed then sessionDestroyed() method will be callled automatically by the web container.

28. How many cookies can one set in the response object of the servlet? Also, are there any restrictions on the size of cookies?

A cookie has a maximum size of 4K, and no domain can have more than 20 cookies.

29. How can my application get to know when a HttpSession is removed?

To get notified that a HttpSession is removed or created, you should implement the HttpSessionBindingListener in the class that implements the two of its method : sessionCreated() and sessionDestroyed(). If a session is created or destroyed, the  sessionCreated() or sessionDestroyed() method respectively will be called automatically. You must register this listener implementing class inside the <listener>...</listener> element in the deployment descriptor(web.xml) file.

30. What is the difference between setting the session time out in deployment descriptor and setting the time out programmatically?

Setting the time out programmatically means calling setMaxInactiveInterval(int seconds) from your servlet.
Setting the session time out in deployment descriptor means declaratively setting the session timeout. The following setting in the deployment descriptor causes the session timeout to be set to 10 minutes:
<session-config>
<session-timeout>10</session-timeout>
</session-config>

Setting the session time out in deployment descriptor allows you to modify the time easily, hard code it into the program requires recompilation overhead.

31. How to make a context thread safe?

To make the context scope thread safe, you need a lock on context object. To synchronize the context attribute is to synchronize on context object. If a thread gets a lock on context object, then you are guaranteed that only one thread at a time can be getting or setting the context attribute. It only works if all of the other code that manipulate the context attribuet also synchronizes on the servlet context.

32. What is the difference between an attribute and a parameter?

Request parameters are the name/value pairs, and the result of submitting an HTML form. The name and the values are always strings. For example, when you do a post from html, data can be automatically retrieved by using request.getParameter() at the server side. Parameters are Strings, and generally can be retrieved, but not set.
Attributes are objects, and can be placed in the request, session, or context objects. Because they can be any object, not just a String, they are much more flexible. You can also set attributes programatically using setAttribute() method, and retrieve them later using getAttribute() method.

33. What are the different ways for getting a servlet context?

The different ways for getting a servlet context :

  * ServletConfig.getServletContext()
  * GenericServlet implements ServletConfig, so HttpServlets all have a getServletContext() method
  * In a Filter you have access to the FilterConfig which is set in the init(FilterConfig fc) callback. You can use FilterConfig.getServletContext().
  * In a ServletContextListener or a ServletContextAttributeListener, the event passed to the listener methods has a getServletContext() method.

34. What is the difference between Context init parameter and Servlet init parameter?

Context init parameter is accessible through out the web application and declared outside the <servlet>...</servlet> element tag in the deployment descriptor(DD) . Servlet init parameters are declared inside the <servlet>...</servlet> element and only accessible only to the that specific servlet. You can access the context init parameters using the getServletContext() method and Servlet init parameters using the getServletConfig() method.

Declaring the Servlet init parameter in DD :

<servlet>
   <servlet-name>My Page</servlet-name>
   <sevlet-class>/mypage</servlet-class>
   <init-param>
      <param-name>email</param-name>
      <param-value>jalees786@gmail.com</param-value) </init-param>
</servlet>

Declaring the Context init parameter in DD :

<context-param>
<param-name>webmaster</param-name>
<param-value>jalees786@gmail.com</param-value>
</context-param>

35. How will you delete a cookie?

To delete cookie from servlet, get the cookie from the request object and use setMaxAge(0) and then add the cookie to the response object.
 
     Cookie killMyCookie = new Cookie("mycookie", null);
     killMyCookie.setMaxAge(0);
     response.addCookie(killMyCookie);

36. How can I set a cookie?

The following program demonstrate that how to set the cookie :

import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request, HttpServletResponse response) {
    response.addCookie(new Cookie("cookie_name", "cookie_value"));
    }
 
  public void doGet(HttpServletRequest req, HttpServletResponse res) {
    doPost(req, res);
    }
}


37. Why in Servlet 2.4 specification SingleThreadModel has been deprecated?

There is no practical implementation to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.

38. What is HttpTunneling?

Encapsulating the information into the Http header and directed it to a server at the other end of the communication channel that takes the packets, strips the HTTP encapsulation headers and redirects the packet to its final destination.
HTTP-Tunnel acts as a socks server, allowing you to use your Internet applications safely despite restrictive firewalls and/or you not be monitored at work, school, goverment and gives you a extra layer of protection against hackers, spyware, ID theft's with our encryption.
Reason For HTTP-Tunnel :
    *  Need to bypass any firewall
    * Need secure internet browsing
    * Need to use favorite programs with out being monitored by work, school, ISP or gov.
    * Extra security for online transactions
    * Encrypt all your Internet traffic.
    * Need play online games
    * Visit sites that you are previously blocked
    * Prevent 3rd party monitoring or regulation of your Internet browsing and downloads
    * Use your favorite applications previously blocked
    * Hide your IP address
    * Make it next to impossible for you to identify online.
    * Free unlimited data transfer
    * Compatible with most major Internet applications
    * Secure and virus-free servers
    * 99% uptime
    * No spam, pop-ups, or banners

 In many cases it is not possible to establish a connection between JMS clients and a SwiftMQ message router or between two SwiftMQ message routers if one part stands behind a firewall. In general it exists a proxy server to which it is allowed exclusively to establish an internet connection by a firewall. To avoid this fact, an operation called HTTP tunneling is used.

39. What are the differences between a session and a cookie?

Differences between a session and a cookie :
  * A cookie is a special piece of data with a bit of associated metadata that an HTTP server includes in an HTTP response. A session is a series of related HTTP requests and responses that
together constitute a single conversation between a client and server.
  * Cookies are stored at the client side whereas session exists at the server side.
  * A cookie can keep information in the user's browser until deleted, whereas you close your browser you also lose the session.
  * Cookies are often used to store a session id, binding the session to the user.
  * There is no way to disable sessions from the client browser but cookies.

40. What is a output comment?

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as uninterpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page

source from your Web browser.
JSP Syntax
<!-- comment [ <%= expression %> ] -->

Example 1
<!-- This is a commnet sent to client on
<%= (new java.util.Date()).toLocaleString() %>
-->

41. Why should we go for inter servlet communication?

Due ot the following reason need inter servlet communication :

  * Two servlet want to communicate to complete the shopping cart.
  * One servlet handles the client request and forward it to another servlet to do some calculation or add some information to complete the view.
  * One servlet want to reuse the some methods of another servlet.

42. What is the Max amount of information that can be saved in a Session Object ?

There is no limit for amount of information that can be seve into the session object. It depends upon the RAM available on the server machine. The only limit is the Session ID length which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session.

43. What is Server side push?

The term 'server push' generally means that a server pushes content to the browser client. Server push is a Netscape-only scheme for providing dynamic web content. Server side push is a mechanism that support real time connection to the server with the advantage of instant updates.
Server side push may be emulated in a number of ways.

    * The client polls the server at a certain interval, say every five minutes. This technique is typically used to update news information. The client does this by reloading a page every so often.
    * The client uses the 'multipart/x-mixed-replace' content type when sending a response. The content type is expected to send a series of documents one after the other, where each one will replace the previous one. The server might delay between each part, which gives the illusion that the data is being updated after an interval. This technique requires a connection to stay open.
    

44. How can a servlet refresh automatically?

We can Refresh Servlet Page by two ways : one through client side and another through Server Push.

Client Side Refresh :
< META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet/">


Server Side Refresh :
response.setHeader("Refresh",5);

This will update the browser after every 5 seconds

45. What is the difference between ServletContext and ServletConfig?

ServletContext and ServletConfig are declared in the deployment descriptor. ServletConfig is one per servlet and can be accessed only within that specific servlet. ServletContext is one per web application and accessible to all the servlet in the web application.


46. What are the different ways for session tracking?

The concept of session tracking allows you to maintain the relation between the two successive request from the same client (browser). The browser sends the request to the server and server process the browser request generate the response and send back response to the browser. The server is not at all bothered about who is asking for the pages. The server (because of the use of HTTP as the underlying protocol) has no idea that these 2 successive requests have come from the same user. There is no connection between 2 successive requests on the Internet.

There are three ways of tracking sessions :
   * Using Cookies.
   * Using URL Rewriting.
   * Using Hidden Form Fields.



47. What mechanisms are used by a Servlet Container to maintain session information?


The mechanisms used by a Servlet Container to maintain session information :

a) Cookies

b) URL rewriting

c) Hidden form fields

d) SSL (using HTTPS protocol) Sessions



48. What Difference between GET and POST ?

Difference between GET and POST :
  * Client can send information to the server by two methods : GET and POST.
  * The GET method appends parameters (name/value) pairs to the URL. The length of a URL is limited, there is a character restriction of 255 in the URL.  so this method only works if there are only a few parameters.
  * The main difference between GET and POST is, POST has a body. Unlike GET, parameters are passed in the body of the POST insteat of appending to the URL. We can send large number of data with the POST.
  * "GET" is basically for just getting (retrieving) data whereas "POST" may involve anything, like storing or updating data, or ordering a product, or sending E-mail.
  * The data send with the GET method is visible at the browser's address bar. Don't send important and sensitive data with GET method, use POST.
  * Get is idempotent, means it has no side effects on re-requesting the same thing on the server.

49. What is session?

A session refers to all the connections that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables. A session keeps all of the state that you build up bundled up so that actions you take within your session do not affect any other users connected to other sessions.

50. What is servlet mapping?

Servlet mapping controls how you access a servlet. Servlet mapping specifies the web container of which java servlet should be invoked for a url given by client. For this purpose web container uses the Deployment Decriptor (web.xml) file. Servlets are registered and configured as a part of a Web Application. To register a servlet, you add several entries to the Web Application deployment descriptor.

Servlet Mapping :

<servlet>
  <servlet-name>MyServlet</servlet-name>
  <servlet-class>myservlets.MappingExample</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>MyServlet</servlet-name>
  <url-pattern>com/*</url-pattern>
</servlet-mapping>

A developer can map all the servelts inside its web application.


51. What is servlet context ?

Servlet context defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. A servlet context object is one per web application per JVM and this object is shared by all the servlet. You can get and set the Servlet context object. You can use servelt context object in your program by calling directly getServletContext() or getServletConfig().getServletContext().


52. Can we use the constructor, instead of init(), to initialize servlet?

Yes. But you will not get the servlet specific things from constructor. So do not use constructor instead of init(). The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor so you won't have access to a ServletConfig or ServletContext. Plus, all the other servlet programmers are going to expect your init code to be in init().

53. What is a servlet ?

Servlets are the server side programs that runs on the server allow developer to add dynamic content and hand it to the web server and web server sent back to the client. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. Servlets provide component-based, platform-independent methods for building Web-based applications, without the performance limitations of CGI programs.
The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods.

Typical uses for HTTP Servlets include :

    * Processing and/or storing data submitted by an HTML form.
    * Providing dynamic content, e.g. returning the results of a database query to the client.
    * Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.


54. Difference between forward and sendRedirect

Forward: Control can be forward to resources available within the server from where the call is made. This transfer of control is done by the container internally and browser / client is not involved. This is the major difference between forward and sendRedirect. When the forward is done, the original request and response objects are transfered along with additional parameters if needed.

Redirect: Control can be redirect to resources to different servers or domains. This transfer of control task is delegated to the browser by the container. That is, the redirect sends a header back to the browser / client. This header contains the resource url to be redirected by the browser. Then the browser initiates a new request to the given url. Since it is a new request, the old request and response object is lost.

For example, sendRedirect can transfer control from http://javapapers.com to http://anydomain.com but forward cannot do this.

‘session’ is not lost in both forward and redirect.

To feel the difference between forward and sendRedirect visually see the address bar of your browser,
in forward, you will not see the forwarded address (since the browser is not involved)
in redirect, you can see the redirected address.
When can we use forward and when can we use sendRedirect?

Technical scenario: redirect should be used

   1. If you need to transfer control to different domain
   2. To achieve separation of task.

For example, database update and data display can be separated by redirect. Do the PaymentProcess and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PyamenProcess will not be repeated. But if you use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other than the above two scenarios, forward is efficient to use since it is faster than sendRedirect.
Example for forward and sendRedirect based on real world

Consider the real world scenario, the milk man comes and asks for monthly payment to you in your house. Here house is the container and you are a resource existing in the container. Milk man is the client or browser.

He asks for the monthly payment to you, this is the request made by the browser to resource A. If you go inside your house and ask your mother (another resource B inside the same container) for the cash and come back and deliver to milkman this is called forward.

If you ask the milkman to speak himself to your mother inside your house or you ask the milkman to speak to your father who is in his office (different domain) then this is called redirect.


55. Difference between ServletConfig and ServletContext

    * Signature: public interface ServletConfig
      ServletConfig is implemented by the servlet container to initialize a single servlet using init(). That is, you can pass initialization parameters to the servlet using the web.xml deployment descriptor. For understanding, this is similar to a constructor in a java class.

Example code:
<servlet>
<servlet-name>ServletConfigTest</servlet-name>
<servlet-class>com.javapapers.ServletConfigTest</servlet-class>
<init-param>
<param-name>topic</param-name>
<param-value>Difference between ServletConfig and ServletContext</param-value>
</init-param>
</servlet>

    * Signature: public interface ServletContext
      ServletContext is implemented by the servlet container for all servlet to communicate with its servlet container, for example, to get the MIME type of a file, to get dispatch requests, or to write to a log file. That is to get detail about its execution environment. It is applicable only within a single Java Virtual Machine. If a web applicationa is distributed between multiple JVM this will not work. For understanding, this is like a application global variable mechanism for a single web application deployed in only one JVM.

The ServletContext object is contained within the ServletConfig object. That is, the ServletContext can be accessed using the ServletConfig object within a servlet. You can specify param-value pairs for ServletContext object in <context-param> tags in web.xml file.

Example code:
<context-param>
<param-name>globalVariable</param-name>
<param-value>javapapers.com</param-value>
</context-param>

JSP's:

1. What is the difference between an application server and a web server?

A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. it doesnt do any operations. that means franckly seaking it can serve only html files, if u ask for ASP/Servlets/Jsp page then the request will be redirected to the particular engine(incase of ASP-ASPEngine, Servlet-ServletEngine, no idea abt JSP but it should be like this only) then the engine will process the file then it gives a htm output that will be returned to the client thats what abt the webserver.
An application server exposes business logic to client applications through various protocols. While a Web server mainly deals with sending HTML for display in a Web browser, an application server provides access to business logic for use by client application programs. The application server exposes the business logic through a component API, such as the EJB (Enterprise JavaBean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Application Server usually refers to a server that is able to handle the entire J2EE specification (JSP, Servlets, EJBs, etc). Most Application Servers also contain web servers.

2. What is the differecnce between JspWriter and PrintWriter?

JspWriter is a buffered version of the PrintWriter. JspWriter also differs from a PrintWriter by throwing java.io.IOException, which a PrintWriter does not. If the page is not buffered, output written to this JspWriter object will be written through to the PrintWriter directly, which will be created if necessary by invoking the getWriter() method on the response object. But if the page is buffered, the PrintWriter object will not be created until the buffer is flushed and operations like setContentType() are legal. Since this flexibility simplifies programming substantially, buffering is the default for JSP pages.

3. How can I print the stack trace of an exception from a  JSP page?

To print the stack trace of an exception from a JSP page you will have to use a PrintWriter object instead of usnig JSP out implicit variable.

<%
out.println("<!--");
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
exception.printStackTrace(pw);
out.print(sw);
sw.close();
pw.close();
out.println("-->");
%>

In the above code you have import="java.io.* package.

4. How do you pass an init parameter to a JSP?

You can pass the init parameters into your JSP file by decaring them into your deployment descriptor web.xml file.

<servlet>
   <servlet-name>My Page</servlet-name>
   <jsp-file>/mypage.jsp</jsp-file>
   <init-param>
      <param-name>email</param-name>
      <param-value>jalees786@gmail.com</param-value) </init-param>
</servlet>

<servlet-mapping>
   <servlet-name>My Page</servlet-name>
   <url-pattern>/foo</url-pattern>
</servlet-mapping>

You can access init parameters into your JSP file using the following code :

<%
String email = getServletConfig().getInitParameter("email");
%>


5. How can you declare methods in your JSP page?

Mehods in the JSP Page can be declared using the JSP "declaration" elemenet.
Example :

<%!
public String  getInfo(HttpServletRequest req){
String n=req.getParameter("name");
String d=req.getParameter("designation");
return n+" is a "+d;
}
%>

<%
out.println(getInfo(request));
%>

6. How can I enable session tracking for JSP pages if the browser has disabled cookies?

URL rewriting is another way to track the session if the browser has disabled the cookies. URL rewriting essentially includes the session ID within the link itself as a name/value pair. 
We have two methods for this purpose :  response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input. Both these methods determines whether the cookies are enabled or not. If cookies are enabled then the input URL will returned unchanged since the session ID will be persisted as a cookie, otherwise append the session ID for each and every link that is part of your servlet response. 

For Example :

hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putValue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%?phpMyAdmin=70ac9566533a2665b6597346aab7f985&phpMyAdmin=f43d4e0b88acea2d2a393515f6bf38f2>'>hello2.jsp</a>

hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getValue("num");
out.println("Num value in session is " + i.intValue());
%> 

7. How can I invoke a JSP error page from a servlet?

Yes, You can invoke JSP error page from a servlet by passing the exception object as a javax.servlet.jsp.jspException request attribute.

Example : 

protected void sendErrorRedirect(HttpServletRequest request, 
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
try {
// Code that might cause exception
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/ErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}

8. Can we use  ServletOutputStream object from a JSP page?

We can't use ServletOutputStream object from a JSP page. You can use JspWriter object. A JSPWriter can be viewed as a buffered version of the stream object returned by response.getWriter(). A page author can always disable the default buffering for any page using a page directive as: <%@ page buffer="none" %>.

9. How you can perform browser redirection?

You can perform browser redirection using sendRedirect() method on response object in the servlet. Example :
response.sendRedirect("http://www.r4r.co.in/path/error.html");

You can also physically alter the Location HTTP header attribute, as shown below:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn = "/newpath/index.html";
response.setHeader("Location",newLocn);
%>

10. How will you include a static file in a JSP page?

You can include a static file in a JSP page by using include directive :

<%@ include file="relativeURL" %>

11. What JSP lifecycle methods we can override?

JSP lifecycle methodsn :

  * JspInit()
  * _JspService()
  * JspDestroy()

You can override the jspInit() and jspDestroy() methods but you can't override the _jspService() method within a JSP page. The jspInit() can be useful for allocating resources like database connections, network connections, etc. The jspDestroy() method can be useful to free up the resources.

12. How do you pass data (including JavaBeans) to a JSP from a servlet?

You can pass information to a JSP page from the servlet. Using setAttribut() on request object in the servlet and forward it as follows :

RequestDispatcher rd =
getServletContext().getRequestDispatcher("test.jsp");
rd.forward(request,response);

13. How to pass information from JSP to included JSP?

You can pass information from JSP to the included JSP using the <jsp:param> in the body of <jsp:include> action.
Example :

<jsp:include page="relativeURL">
      <jsp:param name="parameterName" value="parameterValue"/>
</jsp:include>

14. What is a Hidden Comment?

A hidden comment is a JSP comment that is not sent to the client. Syntax :

  <%-- Hidden comment --%>


15. What are JSP Actions?

JSP Actions are XML tags that are executed at run time. These tags transfer the control between the pages and also use the server side beans :
Some JSP Actions are :
  * jsp:include,
  * jsp:useBean,
  * jsp:setProperty,
  * jsp:getProperty,
  * jsp:forward,
  * jsp:plugin.

16. How do I use a scriptlet to initialize a newly instantiated bean?

The <jsp:useBean> may also optionally have a body. You can make use of a JSP expression within the <jsp:setProperty> action in the body of <jsp:useBean>.

For Example :

<jsp:useBean id="foo" class="Bar.Foo" >

<jsp:setProperty name="foo" property="today" value="<%=java.text.DateFormat.getDateInstance().format(new java.util.Date()) %>" / >
</jsp:useBean >

17. Can we implement an interface in JSP ?

No! In JSP we can't implement the interface. However we can use the class in the JSP file which has implemented the interface.

18. How to refer the "this" variable within a JSP page?

Under JSP 1.0, the "page" implicit object page is equivalent to "this", and returns a reference to the servlet generated by the JSP page.

19. How do I prevent the output of my JSP or Servlet pages from being cached by the browser?

By setting HTTP header attributes you can prevent the output of my JSP or Servlet pages from being cached by the browser. You can do this by the following code :

<%
response.setHeader("Cache-Control","no-cache"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>

20. Can I just abort processing a JSP?

Yes! We can abort the processing of JSP because at the end every JSP file turned into a servlet and we can put a return statement into the service method, so we can put a return statement into JSP code, i.e. we can put <% return; %> into the JSP file.

21. What is the difference between <%@ include ...> (directive include) and <jsp:include> ?

The include directive :-
<%@ include file="fileName" %>
is static and processed at the time when the JSP page is translated into its equivalent servlet. The file included in the page at the time translation and compiled file also contain the included file code. This directive is normally used for including static resources only - like, banner, header, footer, etc. If you make some changes in the included file then it will not affect those files which had included this file.

The include action :-
<jsp:include page="relativeURL" />
is dynamic and processed at runtime. This will simply make a function call at run time to the included file. This action allows additional parameters to be passed via <jsp:param> child element of this include action element. If you make some changes in the included file then it will also affect those files which had included this file.

22. Is JSP extensible ?

Yes! JSP is extensible. PolyJsp is an extensible JSP  implementation designed to support multiple scripting languages  and multiple JSP versions. PolyJsp is completely based on XML and XSL and supports Java, Javascript and WebL  as scripting languages.
Except JSP directives (<%@ %>), declarations (<% %>), scriptlets (<% %>) and expressions (<%= %>),  PolyJsp introduces a few (optional) extensions to JSP :

    * A <%@ version="..." > directive
      Useful to instruct the parser to use a version other than the default (currently 0.92)
    * A <%@ contenttype="..."> directive
      Useful for cases in which the expected output MIME type is other than text/html
    * A <header name="..." value="...">
      Useful to set response headers. Example: set expires to control browser chaching

23. What are the different scopes available ?

Scope tells accessibility of the object in the web application. JSP has the following scopes :
     1. page
     2. request
     3. session
     4. application

24. What's the difference between forward and sendRedirect?

When using request.forward(), request is forwarded to the another resource specified in the forward() parameter. Whereas response.sendRedirect() causes the web container to return to the browser indicating that a new URL should be requested. The browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost.

25. What are the implicit objects?

Web container provides developer to access some objects instantiated by container and available to all the jsp pages. These objects are called implicit objects because they are automatically instantiated. Within each JSP application is the complete set of implicit objects.

There are nine implicit objects in JSP.
1. pageContext
2. session
3. request
4. response
5. exception
6. out
7. application
8. config
9. page

26. What is a Scriptlet?

Scriptlet is a JSP element. It contains the java code enclosed within <% and %>. JSP Engine places these code in the _jspService() method.
Syntax of JSP Scriptles are:

  <%
  //java codes
   %>

Example:
<HTML>
<BODY>
<%
    String userName=null;
    userName=request.getParameter("userName");
    System.out.println( "Current Date is:" );
    java.util.Date date = new java.util.Date();
%>
    Hello <%= userName %> ! <br>
    The time is now :<%= date %>
</BODY>
</HTML>

Ans:
The answer of jeesan  is wrong.
System can not come in printing statement.
It must be out.println("message here");

27. What is a Declaration?

You must declare the variable or method before you use it in the JSP page. The Declaration is a JSP element use to declare the variable or methods that you can use in Java code later in the JSP page.

JSP Declaration :
  <%! code %>  :- Code is inserted in body of servlet class, outside of service method.

Example : The declaration must be valid in the scripting language used in the JSP file.

<%! int i = 0; %>
<%! int a, b, c; %>

28. What is a Expression?

Expression in JSP is used to write the output on the stream. It has the following form :

<%= Java Expression %>

The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation is performed at run-time and thus has full access to information about the request. For example, the following shows the date/time that the page was requested:

Current time is : <%= new java.util.Date() %>

29. What are context initialization parameters?

Context initialization parameters are defined in the Deployment descriptor an accessible to all the servlets in the application. You can use context initialization parameters to specify the information that is dynamically change. You can also use these to specify the URL of the database.

<context-param>
<param-name>webmaster</param-name>
<param-value>jalees786@gmail.com</param-value>  </context-param>

30. What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?

The getRequestDispatcher() can take a relative path while getRequestDispatcher() take relative to the current context's root.

Example :

With ServletRequest-
request.getRequestDispatcher("./jsp/jsppage.jsp") :- evaluated relative to the path of the request
request.getRequestDispatcher("/jsp/jsppage.jsp")  :- evaluated relative to the root are all valid.

With ServletContext only
context.getRequestDispatcher("/jsp/jsppage.jsp") is valid.

31. How can I implement a thread-safe JSP page?

To make your JSPs thread-safe, you hace to implement the SingleThreadModel interface.

This can be done by using page directive with isThreadSafe attribute by setting it to false:

<%@ page isThreadSafe="false" %>

Ques: 56 How do I include static files within a JSP page?

Ans:
We can include static files within a JSP page using the include directive :

< % @ include file="top.html" % >


32. How many JSP scripting elements are there and what are they?

Ans:
Types of Scripting Elements
  � Expressions :
      <%= expression %> :� Evaluated and inserted into the servlet�s output, i.e., results in something like out.print(expression)
  � Scriptlets :
      <% code %>  :� Inserted verbatim into the servlet�s _jspService method (called by
service)
  � Declarations  :
      <%! code %>  :- Inserted verbatim into the body of the servlet class, outside of any
existing methods.
  � Directive :
      <%@ directive %>  :- To use "import" statements in JSPs.

EJB:

1. What is EJB?


EJB technology is the server-side component architecture for the Java 2 Platform, Enterprise Edition (J2EE) platform. EJB technology enables rapid and simplified development of distributed, transactional, secure and portable applications based on Java technology

2. What is the need of Remote and Home interface. Why cant it be in one? 

The main reason is because there is a clear division of roles and responsabilities between the two interfaces. The home interface is your way to communicate with the container, that is who is responsable 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 the beans) and you need two different interfaces for accessing to both of them.

3. What is architecture of EJB?

Ans:
Session beans:
Session beans are non-persistent enterprise beans. They can be stateful or stateless. A stateful session bean acts on behalf of a single client and maintains client-specific session information (called conversational state) across multiple method calls and transactions. It exists for the duration of a single client/server session. A stateless session bean, by comparison, does not maintain any conversational state. Stateless session beans are pooled by their container to handle multiple requests from multiple clients.

Entity beans:
Entity beans are enterprise beans that contain persistent data and that can be saved in various persistent data stores. Each entity bean carries its own identity. Entity beans that manage their own persistence are called bean-managed persistence (BMP) entity beans. Entity beans that delegate their persistence to their EJB container are called container-managed persistence (CMP) entity beans.

Message-driven beans:
Message-driven beans are enterprise beans that receive and process JMS messages. Unlike session or entity beans, message-driven beans have no interfaces. They can be accessed only through messaging and they do not maintain any conversational state. Message-driven beans allow asynchronous communication between the queue and the listener, and provide separation between message processing and business logic.

Remote client view
The remote client view specification is only available in EJB 2.0. The remote client view of an enterprise bean is location independent. A client running in the same JVM as a bean instance uses the same API to access the bean as a client running in a different JVM on the same or different machine.
Remote interface:
The remote interface specifies the remote business methods that a client can call on an enterprise bean.
Remote home interface:
The remote home interface specifies the methods used by remote clients for locating, creating, and removing instances of enterprise bean classes.

Local client view
The local client view specification is only available in EJB 2.0. Unlike the remote client view, the local client view of a bean is location dependent. Local client view access to an enterprise bean requires both the local cleint and the enterprise bean that provides the local client view to be in the same JVM. The local client view therefore does not provide the location transparency provided by the remote client view. Local interfaces and local home interfaces provide support for lightweight access from enterprise bean that are local clients. Session and entity beans can be tightly couple with their clients, allowing access without the overhead typically associated with remote method calls.

Local interface:
The local interface is a lightweight version of the remote interface, but for local clients. It includes business logic methods that can be called by a local client.
Local home interface: The local home interface specifies the methods used by local clients for locating, creating, and removing instances of enterprise bean classes.

EJB client JAR file
An EJB client JAR file is an optional JAR file that can contain all the class files that a client program needs to use the client view of the enterprise beans that are contained in the EJB JAR file. If you decide not to create a client JAR file for an EJB module, all of the client interface classes will be in the EJB JAR file.

EJB container
An EJB container is a run-time environment that manages one or more enterprise beans. The EJB container manages the life cycles of enterprise bean objects, coordinates distributed transactions, and implements object security. Generally, each EJB container is provided by an EJB server and contains a set of enterprise beans that run on the server.

Deployment descriptor
A deployment descriptor is an XML file packaged with the enterprise beans in an EJB JAR file or an EAR file. It contains metadata describing the contents and structure of the enterprise beans, and runtime transaction and security information for the EJB container.

EJB server
An EJB server is a high-level process or application that provides a run-time environment to support the execution of server applications that use enterprise beans. An EJB server provides a JNDI-accessible naming service, manages and coordinates the allocation of resources to client applications, provides access to system resources, and provides a transaction service.

4. What is the difference between Container-Managed Persistent (CMP) Bean and Bean-Managed Persistent(BMP)?

CMP -- Container-managed persistence beans are the simplest for the bean developer to create and the most difficult for the EJB server to support. This is because all the logic for synchronizing the bean's state with the database is handled automatically by the container. This means that the bean developer doesn't need to write any data access logic, while the EJB server is supposed to take care of all the persistence needs automatically. With CMP, the container manages the persistence of the entity bean. Vendor tools are used to map the entity fields to the database and absolutely no database access code is written in the bean class.

BMP--bean-managed persistence (BMP) enterprise bean manages synchronizing its state with the database as directed by the container. The bean uses a database API to read and write its fields to the database, but the container tells it when to do each synchronization operation and manages the transactions for the bean automatically. Bean-managed persistence gives the bean developer the flexibility to perform persistence operations that are too complicated for the container or to use a data source that is not supported by the container.

5. What is Entity Bean?

Entity beans:
Entity beans are enterprise beans that contain persistent data and that can be saved in various persistent data stores. Each entity bean carries its own identity. Entity beans that manage their own persistence are called bean-managed persistence (BMP) entity beans. Entity beans that delegate their persistence to their EJB container are called container-managed persistence (CMP) entity beans.

6. What are the methods of Entity Bean?

1. setEntityContext()
2. ejbCreate()
3. unsetEntityContext()
4. ejbActivate()
5. ejbPassivate()
6. ejbRemove()
7. ejbPostCreate()

7. What is an EJB Context?

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

8. How EJB Invocation happens?

Step 1: Using JNDI, retrieve Home Object reference from Naming Service
Step 2: Send or return Home Object reference to the client.
Step 3: Create a new EJB Object through Home Object interface.
Step 4: Create EJB Object from the Ebb Object
Step 5: Send or return EJB Object reference to the client.
Step 6: Invoke business method using EJB Object reference.
Step 7: Delegate request to Enterprise Bean.

Steps to EJB invocation are:

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

9. What are the callback methods in Entity beans?

The bean class implements a set of callback methods that allow the container to notify the events in its life cycle.
The call back methods available in Entity Bean are public void
setEntityContext();
public void unsetEntityContext();
public void ejbLoad();
public void ejbStore();
public void ejbActivate();
public void ejbPassivate();
public void ejbRemove();

10. Can Entity Beans have no create() methods?

Entity Beans have no create() method, when entity bean is not used to store the data in the database. In this case entity bean is used to retrieve the data from database.But it's using the no create() method so we say that "Yes", In some cases the data is inserted NOT using Java application, so you may only need to retrieve the information, perform its processing, but not create your own information of this kind.

11. What is bean managed transaction?

bean-managed transactions, the bean specifies transaction demarcations using methods in the javax.transaction.UserTransaction interface. Bean-managed transactions include any stateful or stateless session beans with a transaction-type set to Bean. Entity beans cannot use bean-managed transactions.
For stateless session beans, the entering and exiting transaction contexts must match. For stateful session beans, the entering and exiting transaction contexts may or may not match. If they do not match, the WebLogic Enterprise EJB container maintains associations between the bean and the nonterminated transaction.
Session beans with bean-managed transactions cannot use the setRollbackOnly and getRollbackOnly methods of the javax.ejb.EJBContext interface.

12. What are transaction attributes?

The transaction attribute is a value associated with a method of a session or entity bean's home or component interface or with the onMessage(...) method of a message-driven bean. And the transaction attribute specifies how the Container must manage transactions for a method when a client invokes the method via the enterprise bean's home or component interface or when the method is invoked as the result of the arrival of a JMS message.

Enterprise JavaBeans defines the following (SIX) values for the transaction attribute:

NotSupported

Required

Supports

RequiresNew

Mandatory

Never

13.  What are transaction isolation levels in EJB?

Transaction_serializable- All the transactions for resource are performed serial.    
Transaction_read_uncommitted- Allows a method to read uncommitted data from a DB.
Transaction_repeatable_read - Guarantees that all reads of the database will be the same during the transaction.
Transaction_read_committed- Guarantees that the data you are getting has been committed.

14. What is the difference between EJB2.1 and EJB3.0?

No need of Home Interface (EJBHome),but it is needed in EJB2.0
No more confusions to make an EJB remote or local,it's the client which would decide and cast to appropriate.
Just write SINGLE simple Java class and annotate it to be Stateless/Stateful/Entity/MessageDriven.Container
No Deployment Descriptors , MetaData Annotations are explored which is introduced in J2SE5.0
Forget all EJB life cycles.For example Entity bean life cycle in 3.0 is new,managed,detached,removed.
Ejb 3.0 siplifies the developement of the application

Ready to develop complex query,inner/outer join with EJB3.0.
The main difference lies in the persistence In case of EJB 3.0 there is JPA Java persistence API which makes the mapping of EntityBeans with the database easy with the help of a service called as EntityManager.

15. Is it possible to share an HttpSession between a JSP and EJB? How?

You can pass the HttpSession as parameter to an EJB method, only if all objects in session are serializable. This has to be consider as passed-by-value, that means that it?s read-only in the EJB. If anything is altered from inside the EJB, it won?t be reflected back to the HttpSession of the Servlet Container.The pass-by-reference can be used between EJBs Remote Interfaces, as they are remote references.

While it is possible to pass an HttpSession as a parameter to an EJB object, it is considered to be bad practice in terms of object-oriented design. This is because you are creating an unnecessary coupling between back-end objects (EJBs) and front-end objects (HttpSession). Create a higher-level of abstraction for your EJBs API. Rather than passing the whole, fat, HttpSession (which carries with it a bunch of http semantics), create a class that acts as a value object (or structure) that holds all the data you need to pass back and forth between front-end/back-end. Consider the case where your EJB needs to support a non HTTP-based client. This higher level of abstraction will be flexible enough to support it.

16. Can the primary key in the entity bean be a Java primitive type such as int?  

The primary key can't be a primitive type--use the
primitive wrapper classes, instead. For example, you can use
java.lang.Integer as the primary key class, but not int (it
has to be a class, not a primitive)

17. What is EJB QL?

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

18. What is session façade?


A session façade is an EJB design pattern in which a session bean is works like a wrapper over entity beans. A client does not have a direct access to Entity beans but through session beans only for reducing network overhead. Usually stateless session beans are used as single access point for the clients but stateful session beans can also be used for the same purpose. A layer of session beans exposed to clients to access not only gives a clean approach towards client access to bean components but also reduce network calls so as to make the whole system of high performance.

19. What is Session Synchronization in EJB?

SessionSynchronization - it's purpose is to notify the bean about important moments in its transactional life so that the bean can synchronize the state that it is maintaining on behalf of the client with the database. For example, when the transaction begins (afterBegin), the bean can load its state variables with data from the database to be used for the whole transaction, when the transaction is about to complete (beforeCompletion), it can update the database with the state of its variables and after the transaction completes (afterCompletion), it can do what ever it needs to bring its state variables to sync with the database, for example, if the transaction rolled back, it might have to reset its state variables with the old data to bring it in sync with the database. Hence, you are basically using the bean as a poor-man's entity bean. If it is a stateless session bean, it does not have any client-specific state right? Then what will you synchronize? So stateless session beans cannot implement SessionSynchronization because they do not maintain any client-specific state in the first place that would need synchronization.

20. What is the difference between ejbstore and ejbload?

ejbLoad method:
This method is called when it is necessary to synchronize the bean with data from the database. This will most likely trigger a SELECT to occur. The ejbLoad is triggered when the client requests to use the bean, forcing activation to happen, thus moving it to the ready pool.

ejbStore method:
This method is called when it is necessary to synchronize the bean data with the database. This will most likely trigger an UPDATE to occur. The ejbStore is triggered when the bean is no longer being used by a client, and the container decides to move the ready instance back into the pooled state.nullejbLoad method:ejbStore method:

Web Services:

Q. What are the different application integration styles?
A. There are a number of different integration styles like

1. Shared database
2. batch file transfer
3. Invoking remote procedures (RPC)
4. Exchanging asynchronous messages over a message oriented middle-ware (MOM). 


Q. How does a Java EE application integrates with other systems?
A. Using various protocols like HTTP(S), SOAP, RMI, FTP, proprietary, etc.

  

Q. What are the different styles of Web Services used for application integration? 
A. SOAP WS and RESTful Web Service

Q. What are the differences between both SOAP WS and RESTful WS?  
A.  
  • The SOAP WS supports both remote procedure call (i.e. RPC) and message oriented middle-ware (MOM) integration styles. The Restful Web Service supports only RPC integration style.
  • The SOAP WS is transport protocol neutral. Supports multiple protocols like HTTP(S),  Messaging, TCP, UDP SMTP, etc. The REST is transport protocol specific. Supports only HTTP or HTTPS protocols.
  • The SOAP WS permits only XML data format.You define operations, which tunnels through the POST. The focus is on accessing the named operations and exposing the application logic as a service. The REST permits multiple data formats like XML, JSON data, text, HTML, etc. Any browser can be used because the REST approach uses the standard GET, PUT, POST, and DELETE Web operations. The focus is on accessing the named resources and exposing the data as a service. REST has AJAX support. It can use the XMLHttpRequest object. Good for stateless CRUD (Create, Read, Update, and Delete) operations.

             GET - read()
             POST - create()
             PUT - update()
             DELETE - delete() 
  • SOAP based reads cannot be cached. REST based reads can be cached. Performs and scales better.
  • SOAP WS supports both SSL security and WS-security, which adds some enterprise security features like maintaining security right up to the point where it is needed, maintaining identities through intermediaries and not just point to point SSL only, securing different parts of the message with different security algorithms, etc. The REST supports only point-to-point SSL security. The SSL encrypts the whole message, whether all of it is sensitive or not.
  • The SOAP has comprehensive support for both ACID based  transaction management  for short-lived transactions and compensation based transaction management for long-running transactions. It also supports two-phase commit across distributed resources. The REST supports transactions, but it  is neither ACID compliant nor can provide two phase commit across distributed transactional resources as it is limited by its HTTP protocol.
  • The SOAP has success or retry logic built in and provides end-to-end reliability even through SOAP intermediaries. REST does not have a standard messaging system, and expects clients invoking the service to deal with communication failures by retrying.


  • Q. How would you decide what style of Web Service to use? SOAP WS or REST?
    A. In general, a REST based Web service is preferred due to its simplicity, performance, scalability, and support for multiple data formats. SOAP is favored where service requires comprehensive support for security and transactional reliability.

    The answer really depends on the functional and non-functional requirements. Asking the questions listed below will help you choose.

    • Does the service expose data or business logic? (REST is a better choice for exposing data, SOAP WS might be a better choice for logic).
    • Do the consumers and the service providers require a formal contract? (SOAP has a formal contract via WSDL)
    • Do we need to support multiple data formats?
    • Do we need to make AJAX calls? (REST can use the XMLHttpRequest)
    • Is the call synchronous or  asynchronous?
    • Is the call stateful or stateless? (REST is suited for statless CRUD operations)
    • What level of security is required? (SOAP WS has better support for security)
    • What level of transaction support is required? (SOAP WS has better support for transaction management)
    • Do we have limited band width? (SOAP is more verbose)
    • What’s best for the developers who will build clients for the service? (REST is easier to implement, test, and maintain)


    Q. What tools do you use to test your Web Services?
    A. SoapUI tool for SOAP WS and the Firefox "poster" plugin for RESTFul services.


    Q. What is the difference between SOA and a Web service?
    A. 

    SOA is a software design principle and an architectural pattern for implementing loosely coupled, reusable and coarse grained services. You can implement SOA using any protocols such as HTTP, HTTPS, JMS, SMTP, RMI, IIOP (i.e. EJB uses IIOP), RPC etc. Messages can be in XML or Data Transfer Objects (DTOs).

    Web service is an implementation technology and one of the ways to implement SOA. You can build SOA based applications without using Web services – for example by using other traditional technologies like Java RMI, EJB, JMS based messaging, etc. But what Web services offer is the standards based  and platform-independent service via HTTP, XML, SOAP, WSDL and UDDI, thus allowing interoperability between heterogeneous technologies such as J2EE and .NET.



    Q. Why not favor traditional style middle-ware such as RPC, CORBA, RMI and DCOM as opposed to Web services?
    A. 

    The traditional middle-wares tightly couple connections to the applications and it can break if you make any modification to your application. Tightly coupled applications are hard to maintain and less reusable. Generally do not support heterogeneity. Do not work across Internet. Can be more expensive and hard to use.

    Web Services support loosely coupled connections. The interface of the Web service provides a layer of abstraction between the client and the server. The loosely coupled applications reduce the cost of maintenance and increases re-usability. Web Services present a new form of middle-ware based on XML and Web. Web services are language and platform independent. You can develop a Web service using any language and deploy it on to any platform, from small device to the largest supercomputer. Web service uses language neutral protocols such as HTTP and communicates between disparate applications by passing XML messages to each other via a Web API. Do work across internet, less expensive and easier to use.

    Q. What are the different approaches to developing a SOAP based Web service?
    A. 2 approaches.

    • The contract-first approach, where you define the contract first with XSD and WSDL and the generate the Java classes from the contract.
    • The contract-last approach where you  define the Java classes first and thengenerate the contract, which is the  WSDL file from the Java classes.

    Note: The WSDL describes all operations that the service provides, locations of the endpoints (i.e.e where the services can be invoked), and simple and complex elements that can be passed in requests and responses.

    Q. What are the pros and cons of each approach, and which approach would you prefer?

    A.

    Contract-first Web service


    PROS:

    • Clients are decoupled from the server, hence the implementation logic can be revised on the server without affecting the clients.
    • Developers can work simultaneously on client and server side based on the contract both agreed on.
    • You have full control over how the request and response messages are constructed -- for example, should "status" go as an element or as an attribute? The contract clearly defines it. You can change OXM (i.e. Object to XML Mapping) libraries without having to worry if the "status" would be generated as "attribute" instead of an element. Potentially, even Web service frameworks and tool kits can be changed as well from say Apache Axis to Apache CXF, etc

    CONS:

    • More upfront work is involved in setting up the XSDs and WSDLs. There are tools like XML Spy, Oxygen XML, etc to make things easier. The object models need to be written as well.
       
    • Developers need to learn XSDs and WSDLs in addition to just knowing Java.


    Contract-last Web service

    PROS:
    • Developers don't have to learn anything related to XSDs, WSDLs, and SOAP. The services are created quickly by exposing the existing service logic with frameworks/tool sets. For example, via IDE based wizards, etc.
        
    • The learning curve and development time can be smaller compared to the Contract-first Web service.

    CONS: 
    •  The development time can be shorter to initially develop it, but what about the on going maintenance and extension time if the contract changes or new elements need to be added? In this approach, since the clients and servers are more tightly coupled, the future changes may break the client contract and affect all clients or require the services to be properly versioned and managed.
    •  In this approach, The XML payloads cannot be controlled. This means changing your OXM libraries could cause something that used to be an element to become an attribute with the change of the OXM.


    So, which approach will you choose?

    The best practice is to use "contract-first", and here is the link that explains this much better with examples -->  contract-first versus contract-last web services In a nutshell, the contract-last is more fragile than the "contract-first".  You will have to decide what is most appropriate based on your requirements, tool sets you use, etc.