Sunday, August 4, 2013

50 JDBC Interview Question

JDBC Interview Questions

1.What is the JDBC?
Ans. Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers.

2. What are the new features added to JDBC 4.0?
Ans. The major features added in JDBC 4.0 include :
  • Auto-loading of JDBC driver class
  • Connection management enhancements
  • Support for RowId SQL type
  • DataSet implementation of SQL using Annotations
  • SQL exception handling enhancements
  • SQL XML support

3. Explain Basic Steps in writing a Java program using JDBC?
Ans. JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database :
  • Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded).
  • Open the connection to database which is then used to send SQL statements and get results back.
  • Create JDBC Statement object. This object contains SQL query.
  • Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
  • Process the result set.
  • Close the connection.

4. Exaplain the JDBC Architecture.
Ans. The JDBC Architecture consists of two layers:
  • The JDBC API, which provides the application-to-JDBC Manager connection.
  • The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the Java application is shown in Figure 1.

Figure 1: JDBC Architecture

5. What are the main components of JDBC ?
Ans. The life cycle of a servlet consists of the following phases:
  • DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

  • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.

  • Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.

  • Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.

  • ResultSet: The ResultSet represents set of rows retrieved due to query execution.


6. How the JDBC application works?
Ans. A JDBC application can be logically divided into two layers:
1. Driver layer
2. Application layer
  • Driver layer consists of DriverManager class and the available JDBC drivers.
  • The application begins with requesting the DriverManager for the connection.
  • An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer.
  • The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.


7. How do I load a database driver with JDBC 4.0 / Java 6?
Ans.Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.

8. What is JDBC Driver interface?
Ans. The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

9. What does the connection object represents?
Ans. The connection object represents communication context, i.e., all communication with database is through connection object only.

10. What is Statement ?
Ans. Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects.
Through the connection object we create statement kind of objects.
               Statement stmt  = conn.createStatement();
This method returns object which implements statement interface.

11. What is PreparedStatement?
Ans. A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.
 
PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);

Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.


12. What is the difference between a Statement and a PreparedStatement?
Statement
PreparedStatement
A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database.
A PreparedStatement is a precompiled  statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
Statement has to verify its metadata against the database every time.
While a prepared statement has to verify its metadata against the database only once.
If you want to execute the SQL statement once go for STATEMENT
If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries

13. What are callable statements ?
Ans. Callable statements are used from JDBC application to invoke stored procedures and functions.

14. How to call a stored procedure from JDBC ?
Ans. PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class.
The following line of code illustrates this:
 
CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");

Here conn is an instance of the Connection class.

15. What are types of JDBC drivers?
Ans. There are four types of drivers defined by JDBC as follows:
  • Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.

  • Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.

  • Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.

  • Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.

Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.

16. Which type of JDBC driver is the fastest one?
Ans. JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.

17. Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?
Ans. No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.

18. Which is the right type of driver to use and when?
  • Type I driver is handy for prototyping
  • Type III driver adds security, caching, and connection control
  • Type III and Type IV drivers need no pre-installation.

19. What are the standard isolation levels defined by JDBC?
Ans. The values are defined in the class java.sql.Connection and are:
  • TRANSACTION_NONE
  • TRANSACTION_READ_COMMITTED
  • TRANSACTION_READ_UNCOMMITTED
  • TRANSACTION_REPEATABLE_READ
  • TRANSACTION_SERIALIZABLE
Any given database may not support all of these levels.

20. What is resultset ?
Ans. The ResultSet represents set of rows retrieved due to query execution.
                               ResultSet rs = stmt.executeQuery(sqlQuery);

21. What are the types of resultsets?
Ans. The values are defined in the class java.sql.Connection and are:
  • TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can be advanced only in the forward direction.
  • TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.
  • TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.
Note: A TYPE_FORWARD_ONLY resultset is always insensitive.

22. What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?
TYPE_SCROLL_INSENSITIVE
TYPE_SCROLL_SENSITIVE
An insensitive  resultset is like the snapshot of the data in the database when query was executed.
A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive.
After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive.
Since a trip is made for every ‘get’ operation, the performance drastically get affected.

22. What is rowset?
Ans. A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification mechanism.

24. What are the different types  of RowSet ?
Ans. There are two types of RowSet are there. They are:
  • Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.
  • Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.

25. What is the need of BatchUpdates?
Ans. The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip.

26. What is a DataSource?
Ans. A DataSource object is the representation of a data source in the Java programming language. In basic terms,
  • A DataSource is a facility for storing data.
  • DataSource can be referenced by JNDI.
  • Data Source may point to RDBMS, file System , any DBMS etc..

27. What are the advantages of DataSource?
Ans. The few advantages of data source are :
  • An application does not need to hardcode driver information, as it does with the DriverManager.
  • The DataSource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details.
  • The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.

28. What is connection pooling? what is the main advantage of using connection pooling?
Ans. A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested..

29. how can we store and retrieve images from the database?
Ans. By using PreparedStaement interface, we can store and retrieve images.

import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
                                   
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
                       
FileInputStream fin=new FileInputStream("d:\\g.jpg");
                       
ps.setString(1,"sonoo");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
                       
con.close();
                                   
}catch (Exception e) {e.printStackTrace();}
}
}

30. What is JDBC Driver interface?
Ans. The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendors driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

31. What Class.forName will do while loading drivers?
Ans. 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.

32. How can you retrieve data from the ResultSet?
Ans. First 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.

E.g.
ResultSet rs = stmt.executeQuery(”SELECT COF_NAME, PRICE FROM COFFEES”);

Second:
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.

33. How can you use PreparedStatement?
Ans. This special type of statement is derived from the more general class, Statement. If you want to execute a Statement object many times, it will normally reduce execution time 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.

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

34. How to call a Stored Procedure from JDBC?
Ans. The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure;

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

35. How to Retrieve Warnings?
Ans. 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

E.g.
SQLWarning warning = stmt.getWarnings();
    if (warning != null) {

        while (warning != null) {
          System.out.println(”Message: ” + warning.getMessage());
          System.out.println(”SQLState: ” + warning.getSQLState());
          System.out.print(”Vendor error code: “);
          System.out.println(warning.getErrorCode());
          warning = warning.getNextWarning();
        }
    }

36. How to Make Updates to Updatable Result Sets?
Ans. 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.

E.g.
Connection con = DriverManager.getConnection(”jdbc:mySubprotocol:mySubName”);
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = (”SELECT COF_NAME, PRICE FROM COFFEES”);

37. What is new in JDBC 2.0?
Ans. With the JDBC 2.0 API, you will be able to do the following:

* Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_SENSITIVE,previous(), last(), absolute(), relative(), etc.)

* Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.)

* Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch())
* Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.

38. How to move the cursor in scrollable resultsets?(new feature in JDBC 2.0)
Ans.
a. create a scrollable ResultSet object.

    Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
         ResultSet.CONCUR_READ_ONLY);
    ResultSet srs = stmt.executeQuery("SELECT COLUMN_1,
 COLUMN_2 FROM TABLE_NAME");

b. Use a built in methods like afterLast(), previous(), beforeFirst(), etc. to scroll the resultset.
   srs.afterLast();
    while (srs.previous()) {
        String name = srs.getString("COLUMN_1");
        float salary = srs.getFloat("COLUMN_2");
        //...

c. to find a specific row, use absolute(), relative() methods.
       srs.absolute(4); // cursor is on the fourth row
       int rowNum = srs.getRow(); // rowNum should be 4
       srs.relative(-3);
       int rowNum = srs.getRow(); // rowNum should be 1
       srs.relative(2);
       int rowNum = srs.getRow(); // rowNum should be 3

d. use isFirst(), isLast(), isBeforeFirst(), isAfterLast() methods to check boundary status.

39.  How to update a resultset programmatically? (new feature in JDBC 2.0)
Ans.
a. create a scrollable and updatable ResultSet object.
Statement stmt = con.createStatement
         (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
   ResultSet uprs = stmt.executeQuery("SELECT COLUMN_1,
         COLUMN_2 FROM TABLE_NAME");

b. move the cursor to the specific position and use related method to update data and then, call updateRow() method.
uprs.last();
   uprs.updateFloat("COLUMN_2", 25.55);//update last row's data
   uprs.updateRow();//don't miss this method, otherwise,
    // the data will be lost.

40. How to insert and delete a row programmatically? (new feature in JDBC 2.0)

Make sure the resultset is updatable.
1. move the cursor to the specific position.
uprs.moveToCurrentRow();
2. set value for each column.
   uprs.moveToInsertRow();//to set up for insert
   uprs.updateString("col1" "strvalue");
   uprs.updateInt("col2", 5);
   ...
3. call insertRow() method to finish the row insert process.
uprs.insertRow();

To delete a row: move to the specific position and call deleteRow() method:

   uprs.absolute(5);
   uprs.deleteRow();//delete row 5

To see the changes call refreshRow();
uprs.refreshRow();

41. Variables Available in CallableStatement ?
Ans. Three types of parameters exist: IN, OUT, and INOUT. The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all three.
Here are the definitions of each:

Parameter
Description
IN
A parameter whose value is unknown when the SQL statement is created. You bind values to IN parameters with the setXXX() methods.
OUT
A parameter whose value is supplied by the SQL statement it returns. You retrieve values from theOUT parameters with the getXXX() methods.
INOUT
A parameter that provides both input and output values. You bind variables with the setXXX() methods and retrieve values with the getXXX() methods.

71 Servlet Interview Questions

Servlets Interview Questions

1. What is the Servlet?
Ans. A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request- response programming model.

2.What are the new features added to Servlet 2.5?
Ans. Following are the changes introduced in Servlet 2.5:
  • A new dependency on J2SE 5.0
  • Support for annotations
  • Loading the class
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications

3. What are the uses of Servlet?
Ans. 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.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • 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.

4.What are the advantages of Servlet over CGI?
Ans. Servlets have several advantages over CGI:
  • A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
  • A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications

5. What are the phases of the servlet life cycle?
The life cycle of a servlet consists of the following phases:
  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.
  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

6. Why do we need a constructor in a servlet if we use the init method?
Ans. Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.

7. How the servlet is loaded?
Ans. A servlet can be loaded when:
  • First request is made.
  • Server starts up (auto-load).
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Administrator manually loads.

8. How a Servlet is unloaded?
Ans. A servlet is unloaded when:
  • Server shuts down.
  • Administrator manually unloads.

9. What is Servlet interface?
Ans. The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.

Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

  •  
10.What is the GenericServlet class?
Ans. GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.

11.What's the difference between GenericServlet and HttpServlet?
GenericServlet
HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods.
An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers.
The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol.
HttpServlet only supports HTTP and HTTPS protocol.


12.Why is HttpServlet declared abstract?
Ans. The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

13. Can servlet have a constructor ?
Ans. One can definitely have constructor in servlet. Even you can use the constrctor in servlet for initialization purpose, but this type of approach is not so common. You can perform common operations with the constructor as you normally do. The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do. In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

14. What are the types of protocols supported by HttpServlet ?
Ans. It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

15.What is the difference between doGet() and doPost()?

doGet()
doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information.
In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters.
You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent)
doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encrypted
Parameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance
doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many times
This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsible
This method does not need to be either safe
8
It allows bookmarks.
It disallows bookmarks.

16.When to use doGet() and when doPost()?
Ans. Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:
  • If data is sensitive
  • Data is greater than 1024 characters
  • If your application don't need bookmarks.

17. How do I support both GET and POST from the same Servlet?
Ans. The easy way is, just support POST, then have your doGet method call your doPost method:

 public void doGet(HttpServletRequest request, HttpServletResponse response)

                        throws ServletException, IOException

{

    doPost(request, response);   

}

18.Should I override the service() method?
Ans.We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request. For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

19.How the typical servlet code look like ?

20. What is a servlet context object?
Ans. A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.

21.What are the differences between the ServletConfig interface and the ServletContext interface?
ServletConfig
ServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig parameter per servlet.
There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object are specified in the <init-param> within the <servlet> tags in the web.xml file
The param-value pairs for ServletContext object are specified in the <context-param> tags in the web.xml file.

22.What's the difference between forward() and sendRedirect() methods?
forward()
sendRedirect()
A forward is performed internally by the servlet.
A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
The  browser is completely unaware that it has taken place, so its original URL remains intact.
The browser, in this case, is doing the work and knows that it's making a new request.
Any browser reload of the resulting page will simple repeat the original request, with the original URL
A browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable)
This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Since both resources are part of same context, the original request context is retained
Because this involves a new request, the previous request scope objects, with all of its parameters and attributes are no longer available after a redirect.
(Variables will need to be passed by via the session object).
Forward is marginally faster than redirect.
redirect is marginally slower than a forward, since it requires two browser requests, not one.

23.What is the difference between the include() and forward() methods?
include()
forward()
The RequestDispatcher include() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet.
The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored.
The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets.
The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.

24.What's the use of the servlet wrapper classes?
Ans. The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.

25.What is the directory structure of a WAR file?

26.What is a deployment descriptor?
Ans. A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean. The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.

27.What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?

ServletRequest.getRequestDispatcher(String path)
ServletContext.getRequestDispatcher(String path)
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are   interpreted as relative to current context root.

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

29.What is the <load-on-startup> element?
Ans. The <load-on-startup> element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The <load-on-startup> element is written in the deployment descriptor as follows:
<servlet>

   <servlet-name>ServletName</servlet-name>

   <servlet-class>ClassName</servlet-class>

   <load-on-startup>1</load-on-startup>

</servlet>
 
30.What is session?
Ans. A session refers to all the requests 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.

31.What is Session Tracking?
Ans. Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

32.What is the need of Session Tracking in web application?
Ans. HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is referred as "state". To keep track of this state we need session tracking.

Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests.

33.What are the types of Session Tracking ?
Ans. Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:
  • URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.

  • Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

  • Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.

  • Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.
34. How do I use cookies to store session state on the client?
Ans. In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.
  • To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
  • To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest

35. What are some advantages of storing session state in cookies?
  • Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction.
  • For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.

36.What are some disadvantages of storing session state in cookies?
  • Cookies are controlled by programming a low-level API, which is more difficult to implement than some other approaches.
  • All data for a session are kept on the client. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information.
  • Cookies may not be available for many reasons: the user may have disabled them, the browser version may not support them, the browser may be behind a firewall that filters cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and then switching to an alternate client-side session state strategy in cases where cookies aren't available, complicates development and maintenance.
  • Browser instances share cookies, so users cannot have multiple simultaneous sessions.
  • Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the HTTP protocol. Notice that the while package javax.servlet.http supports session management (via class HttpSession), package javax.servlet has no such support.

37. What is URL rewriting?
Ans. URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.
Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.

E.g., http://abc/path/index.jsp;jsessionid=123465hfhs
Advantages
  • URL rewriting works just about everywhere, especially when cookies are turned off.
  • Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
  • Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.

DisAdvantages
  • Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
  • URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
  • URL rewriting does not work well with JSP technology.
  • If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.

38. How can an existing session be invalidated?
Ans. An existing session can be invalidated in the following two ways:
  • Setting timeout in the deployment descriptor: This can be done by specifying timeout between the <session-timeout>tags as follows:
<session-config>

       <session-timeout>10</session-timeout>

</session-config>
This will set the time for session timeout to be ten minutes.

  • Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
                   public void setMaxInactiveInterval(int interval)

The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.
Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.

39. How can the session in Servlet can be destroyed?
Ans. An existing session can be destroyed in the following two ways:
  • Programatically : Using session.invalidate() method, which makes the container abonden the session on which the method is called.
  • When the server itself is shutdown.

40. A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?
Ans. Creates only one session i.e., they end up with using same session .
Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.

41.What is servlet lazy loading?
  • A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
  • The servlet specification defines the <load-on-startup> element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
  • The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

42. What is Servlet Chaining?
Ans. Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.

43. How are filters?
Ans. Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:
  • Security checks
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression
Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.

44.What are the functions of an intercepting filter?
Ans. The functions of an intercepting filter are as follows:
  • It intercepts the request from a client before it reaches the servlet and modifies the request if required.
  • It intercepts the response from the servlet back to the client and modifies the request if required.
  • There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.


45. What are the functions of the Servlet container?
Ans. The functions of the Servlet container are as follows:
  • Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
  • Communication support : It handles the communication between the servlet and the Web server.
  • Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
  • Declarative security : It manages the security inside the XML deployment descriptor file.
  • JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.

46. What is the difference between the getRequestDispatcher(String) and getNamedDispatcher(String) methods in the ServletContext Class?
Ans.
NamedDispatcher :
Returns a RequestDispatcher object that acts as a wrapper for the named servlet.

getNamedDispatcher(String) method takes the name of the Servlet as parameter which is declared via Deployment descriptor.

Example: Deployment Descriptor
<servlet>
<servlet-name>ServletTest</servlet-name>
<servlet-class>com.example.ServletTest</servlet-class>
</servlet>

RequestDispatcher dispatch = request.getNamedDispatcher("ServletTest");
dispatch.forward(request, response);

Note: A servlet instance can determine its name using servletConfig.getServletName(); This method returns the name of the class that implements the Servlet interface or extends the HttpServlet class.

RequestDispatcher

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
RequestDispatcher dispatch = request.getRequestDispatcher("/satya");
Here "/satya" represents the url-pattern element value of the servlet class.

<servlet-mapping>
<servlet-name>Test</servlet-name>
<url-pattern>/satya</url-pattern>
</servlet-mapping>

47. What is load-on-startup in servlet ?
Ans. On server startup servlet will be called by the server.
the value 1 in <load-on-startup>1</load-on-startup> specifies the order in which the servlet must be loaded by the server..
if you have 2 servlet you can specify <load-on-startup>2</load-on-startup> for the next servlet
Below is the servlet tag entry in web.xml:
<servlet>
<servlet-name>InitServlet</servlet-name>
<servlet-class>util.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>

48. Why do servlets have an init method? Can't we make use of the servlet constructor for initialization?
Ans. You can't make use of the constructor because the container calls it and therefore you can't pass any parameters to the constructor. Also at the point the constructor is called the class is not really a Servlet because it doesn't have a reference to the ServletConfig, which provides all the initialisation parameters etc.

Because the servlet container manages the servlet lifecycle, one should never call the constructor, the init and destroy methods.

49. Why can't a container call constructor having parameters?
Ans. As it is the container that manages a servlets lifecycle, you must define a generic way of working for all servlets. You can't use the constructor because otherwise you would have to modify the container to tell him to instantiate this particular servlet.

50. How can I use servlets with protocols other than HTTP, e.g. FTP?
Ans. The javadocs for javax.servlet.Servlet and GenericServlet make it sound as if protocols other than HTTP can be used simply by extending GenericServlet, and implementing the methods that deal with the protocol, much like HttpServlet does for HTTP. That is not the case. The protocol needs to be supported by the servlet engine (which does all the network handling for the servlet), and no servlet engine exists that supports anything other than HTTP(S). Adding a different protocol would be a big project, especially since other protocols don't have the same request/response nature of HTTP. If you find yourself contemplating such a project, post your requirements to the Servlet forum, and a better solution will probably be suggested.

For JSPs, the specification says "Most JSP pages use the HTTP protocol, but other protocols are allowed by this specification.". Since a non-HTTP JSP implementation would depend on a non-HTTP servlet implementation, that too is just a theoretical possibility.

(Note that all of this has nothing to do with a servlet's ability to be a client for other protocols. E.g., by using the JavaMail or Jakarta Commons Net APIs a servlet can access SMTP and FTP servers without problems.)

51. How do I implement security for my web application ?
Ans. The use of HTTPS/SSL can be required by adding the following to the web.xml file:

<security-constraint>
<web-resource-collection>
<web-resource-name>Entire Application</web-resource-name>
<url-pattern>/*</url-pattern>
</web-resource-collection>

<user-data-constraint>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>

52. Why IllegalStateException in jsp/servet?
Ans. by attempting to redirect from within the middle of a JSP page you will get IllegalStateException .
For Example
<div>News </div>
<%  if ("not logged in")
response.sendRedirect("login.jsp"); %>
<div>more news</div>

You can avoid this by using return ;
 Example :
<div>News </div>
<%  if ("not logged in")
response.sendRedirect("login.jsp");
return; %>
<div>more news</div>

or
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
            if("client".equals(request.getParameter("user_type"))){
            response.sendRedirect("client-screen.jsp");
            return; // <------- This return statement prevents any further writing to the outputStream
}

//
// Other code that may write to the outputStream....
//

53. When a client request is sent to the servlet container, how does the container choose which servlet to invoke?
Ans. The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
For Example---
<servlet>
<servlet-name>admin</servlet-name>
<servlet-class>com.servlet.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
    <servlet-name>admin</servlet-name>
    <url-pattern>/artadmin</url-pattern>
</servlet-mapping>
if the url in browser is http://localhost:8080/artadmin

then server will call LoginServlet. Based on the above mapping.

54. Request parameter How to find whether a parameter exists in the request object?
Ans. 1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals(""));
2. boolean hasParameter = request.getParameterMap().contains(theParameter);

55. Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time?

Ans. Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet?s service() method to finish.

56. Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()?

Ans. Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.

57. When we don't write any constructor for the servlet, how does container create an instance of servlet?

Ans. Container creates instance of servlet by calling Class.forName(className).newInstance().

58. Why don't we write a constructor in a servlet?

Ans. Container writes a no argument constructor for our servlet.

59. What is the difference between ServletContext and PageContext?

Ans. ServletContext: Gives the information about the container
PageContext: Gives the information about the Request

60. What's the difference between init() & init(ServletConfig) in genericServlet ?

Ans. init(ServletConfig ):
The default implementation of init(ServletConfig) does some initialization then calls init(). If you use init(ServletConfig) and forget to call super.init(config) at the start of the method then your Servlet will not be initialized correctly.
Called by the servlet container to indicate to a servlet that the servlet is being placed into service.
You will get the ServletConfig object.

init():
You can get the ServletConfig using getServletConfig().
A convenience method which can be overridden so that there's no need to call super.init(config).
Instead of overriding init(ServletConfig), simply override this method and it will be called by GenericServlet.init(ServletConfig config). The ServletConfig object can still be retrieved via getServletConfig().

It is BETTER to use init(). If you use init() you have no such worries as calling super.init().

Details :

Before start we have to understand the servlet flow.
For example you have servlet LoginServlet which extends HttpServlet

public class LoginServlet extends HttpServlet{ }

And your HttpServlet internally extends GenericServlet.

public abstract class GenericServlet implements Servlet, ServletConfig, Serializable {     
public GenericServlet() { }
public void init() throws ServletException { }
public ServletConfig getServletConfig() { return config; }
public void init(ServletConfig config) throws ServletException {
this.config = config;
init();
}

public abstract void service(ServletRequest servletrequest, ServletResponse servletresponse)
throws ServletException, IOException;
      private transient ServletConfig config; }

Now servlet container flow

Step 1. Loads the servlet class and create instance of the servlet class (LoginServlet).
LoginServlet login = new LoginServlet();

Step 2. Then servlet container create ServletConfig object for that servlet and
Call login.init(ServletConfig);

Case 1 :
If you have overridden init(ServletConfig) method in your servlet then call goes to your
init(ServletConfig) method .

public void init(ServletConfig config) throws ServletException {
       System.out.println("\n**** Initializing LoginServlet Init Servlet ********** \n"); 
       super.init(config);
    }

It will print "Initializing LoginServlet Init Servlet" and call goes to supper class GenericServlet init(ServletConfig) method.

In the GenericServlet init(ServletConfig) method there is code
This.config= config // initialize the Servlet config object and it is available to you.

Case 2 :
If you overridden init() method and not overridden init(ServletConfig) method.
Servlet container call login.init(ServletConfig);

There is no method like init(ServletConfig) in your servlet so call directly goes to super class GenericServlet init(ServletConfig) method.
This.config= config
// initialize the Servlet config object and it is available to you.

You can get the Servlet config object using getServletConfig() method.
Conclusion: It is BETTER to use init(). If you use init() you have no such worries as calling super.init().
If you use init(servletconfig) and forgot to call super.init(config) then servletconfig object will not set and you will not get the servletconfig object.

 

61. Can we override service method in HttpServlet ?

Ans. You can override service method in HttpServlet also.
If you override service method in HttpServlet then call will go to service() method instead of doGet() or doPost() method.

If the jsp form you mentioned
<form name="reg" method="post">
then also call will go to service method of the servlet. Call don't go to doPost() method. you can call doPost() method explicitly from servive() method.
If the jsp form you mentioned
<form name="reg" method="get">
then also call will go to service method of the servlet. Call don't go to doGet() method. you can call doGet () method explicitly from servive() method.

62. How does one choose between overriding the doGet(), doPost(), and service() methods?
Ans. The differences between the doGet() and doPost() methods are that they are called in the HttpServlet that your servlet extends by its service() method when it recieves a GET or a POST request from a HTTP protocol request.
A GET request is a request to get a resource from the server. This is the case of a browser requesting a web page. It is also possible to specify parameters in the request, but the length of the parameters on the whole is limited. This is the case of a form in a web page declared this way in html: <form method="GET"> or <form>.
A POST request is a request to post (to send) form data to a resource on the server. This is the case of of a form in a web page declared this way in html: <form method="POST">. In this case the size of the parameters can be much greater.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are (you must do the parsing yourself).
The HttpServlet instead has doGet() and doPost() methods that get called when a client request is GET or POST. This means that the parsing of the request is done by the servlet: you have the appropriate method called and have convenience methods to read the request parameters.
NOTE: the doGet() and doPost() methods (as well as other HttpServlet methods) are called by the service() method.
Concluding, if you must respond to GET or POST requests made by a HTTP protocol client (usually a browser) don't hesitate to extend HttpServlet and use its convenience methods.
If you must respond to requests made by a client that is not using the HTTP protocol, you must use service().

63. How can my application get to know when a HttpSession is removed?
Ans. Define a Class HttpSessionNotifier which implements HttpSessionBindingListener and implement the functionality what you need in valueUnbound() method.

Create an instance of that class and put that instance in HttpSession. 

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

65. How does a servlet communicate with a JSP page?

Ans. In the service method
protected void service(HttpServletRequest request,HttpServletResponse response)
        throws ServletException, java.io.IOException {

User user = (User)request.getSession().getAttribute("user");
                
        String imgId = (String)request.getParameter("imgId");
        String path = request.getContextPath()+"/jsp/addnetwork.jsp";
        
        //do some thing
User user = DAO.getUser(imgId);
request.getSession().setAttribute("user",user);    
         response.sendRedirect(path);

66. How to create and retrieve a multiple selections list in jsp/servlet?

Ans. This is the code to display multiple selections list in jsp.
List medList = DAO.getallMedium(); // this method retun list of Medium objects.
medList list contains list of Medium objects.

Java :
bean class.
public class Medium {
    int medId;
    String medName;
    public int getMedId() {
        return medId;
    }
    public void setMedId(int medId) {
        this.medId = medId;
    }
    public String getMedName() {
        return medName;
    }
    public void setMedName(String medName) {
        this.medName = medName;
    }
}

DAO Clas to retrive mediums in data base.
public static List getMediums(){
        PreparedStatement pStmt = null;
     Connection conn = null;
     boolean success = false;
     ResultSet rs = null;
     List medList = new ArrayList();
    
     try{
         conn = getConnection();
         
         String sql = " select * from MEDIUM ";
         pStmt = conn.prepareStatement(sql);
                  
         rs = pStmt.executeQuery();
         while(rs.next()){
             Medium med = new Medium();
             med.setMedId(rs.getInt("MED_ID"));
             med.setMedName(rs.getString("MEDIUM_NAME"));
             medList.add(med);
             }
  }catch(Exception e){
         e.printStackTrace();
         
     }finally{
         closeConnectionProp(conn,pStmt,rs);
     }
     return medList;
    }

JSP :
<select name="Medium" id="medium" multiple=true>
<option value="0">Choose A Medium</option>

<%
     for(int i=0; i<medList.size();i++){
         Medium med = (Medium)medList.get(i);
     %>
<option value="<%=med.getMedId()%>"><%=med.getMedName()%></option>
<%}%>
</select>

Servlet :
Retrive the multiple selections from jsp
String[] mediums = request.getParameterValues("medium");
for(int i=0;i<mediums.length;i++)
{ System.out.println(mediums[i]); }

67. Why to use the HttpServlet Init method to perform expensive operations that need only be done once?
Ans. Because the servlet init() method is invoked when servlet instance is loaded, it is the perfect location to carry out expensive operations that need only be performed during initialization. By definition, the init() method is thread-safe. The results of operations in the HttpServlet.init() method can be cached safely in servlet instance variables, which become read-only in the servlet service method.

68. When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?
Ans. I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML valuators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.

69. What is filter? Can filter be used as request or response?
Ans. A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.

70. When a client request is sent to the servlet container, how does the container choose .which servlet to invoke?
Ans. The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.

71. If a servlet is not properly initialized, what exception may be thrown?
Ans. During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.