Advance Java

 

1. What is JDBC?

JDBC technology is an API that provides  connectivity to a wide range of SQL databases and access to other tabular data sources, such as spreadsheets or flat files.

Or

JDBC is java database connectivity as name implies it’s a java API for communicating to relational database. This  API has java classes and interfaces using which developer can easily interact with database.

2. What is JDBC Driver?

The JDBC Driver provides vendor-specific implementations of the abstract classes and interfaces provided by the JDBC API. This driver is used to connect to the database.

   Or

JDBC driver is used to establish a connection with the database so that you can fetch, update and maintain database tables using SQL queries.

Or

JDBC Driver is a software component that enables java application to interact with the database.

3.What are the different types of JDBC drivers available ?

1.     JDBC-ODBC Bridge  Driver (Type 1): It uses ODBC driver to connect to database. We should have ODBC drivers installed to connect to database, that’s why this driver is almost obsolete.

2.    Native  driver (Type 2): This driver converts JDBC class to the client API for the database servers. We should have database client API installed. Because of extra dependency on database client API drivers, this is also not preferred driver.

3.    Network Protocol Driver (Type 3): This driver sends the JDBC calls to a middleware server that can connect to different type of databases. We should have a middleware server installed to work with this driver. This adds to extra network calls and slow performance and hence it is  not widely used JDBC driver.

4.    Thin Driver (Type 4): This driver converts the JDBC calls to the vendor specific  protocols that are understood by the database server. This solution is simple and suitable for database connectivity over the network. However for this solution, we should use database specific drivers, for example OJDBC jars by Oracle for Oracle DB and MySQL Connector/J for MySQL databases..

Or

1) JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.

KodNest jd

Advantages:

1.easy to use.
2.can be easily connected to any database.

Disadvantages:

1.Performance degraded because JDBC method call is converted into the ODBC function calls.
2.The ODBC driver needs to be installed on the client machine.

2) Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.

KodNest njd

Advantage:

1.performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

1.The Native driver needs to be installed on the each client machine.
2.The Vendor client library needs to be installed on client machine.

3) Network Protocol driver

The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.

KodNest npjd

Advantage:

No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be don

4) Thin driver

The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.

KodNest ttt

Advantage:

Better performance than all other drivers.
No software is required at client side or server side.

Disadvantage:

Drivers depends on the Database.

4. Which is the fastest type of JDBC driver ?

    Type 4  (JDBC Net pure Java Driver) is the fastest JDBC driver.  Type 1 and Type 3 drivers will be slower than Type 2 drivers and Type 4 drivers are the fastest .

5.What are the steps required to execute a query in JDBC ?

  1. First we need to create an instance of a JDBC driver or load JDBC drivers .
  2.   we should open a connection or we should establish the connection
  3.   We should create a statement object and this object will help us to execute the query.
  4. We should Execute query
  5. We should Display the result
  6. We should Close the resources

Or

•          Load the Driver: First step is to load the database specific driver which communicates with database.

Establish the Connection: Next step is get connection from the database using connection object, which is used to send SQL statement also and get result back from the database.

Create Statement object: From connection object we can get statement object which is used to query the database

Execute the Query: Using statement object we execute the SQL or database query and get result set from the query.

 Display the result: the result obtained from Database should be displayed on the screen Close the Resources: After getting Resultset and all required operation performed the last step should be closing the Resources .

6).What Class.forName ( ) method will do?

Class.forName()  loads the class dynamically and it returns the object of type class.

Example:we can use Class.forName() to load the driver class in JDBC

Class.forName(“oracle.jdbc.driver.OracleDriver”);

7. What is Connection?

Connection  represents  a connection with a specific database. SQL statements are executed and results are returned within the context of a connection.

We can establish the connection to Database by using getConnection() method present in  DriverManager Class as shown in the example below

String url=”jdbc:oracle:thin:@//localhost:1521/XE”;
String user=”system”;
String password=”system”;
Connection con=DriverManager.getConnection(url,user,password);

8. What is a database URL or What is JDBC URL ?

A database URL (or JDBC URL) is a platform independent way of addressing a database.

A database/JDBC URL is of the form
[code language=”java”]jdbc:[subprotocol]:[node]/[databaseName][/code]

Example: oracle URL is as shown below

jdbc:oracle:thin:@//localhost:1521/XE

9. What are the different types of Statements available in JDBC ?

There are three types of statement:

1. Statement: it’s a commonly used for getting data from database useful when we are using static SQL statement at runtime. it will not accept any parameter.

Example: Statement   stmt = conn.createStatement( );      

2. PreparedStatement: when we are using same SQL statement multiple times it is useful and it will accept parameter at runtime.

                String SQL = "Update stock SET limit =? WHERE stock Type = ?";

Example:   PreparedStatement  pstmt = conn.prepareStatement(SQL);

3. Callable Statement: when we want to access stored procedures then callable statement are useful and they also accept runtime parameter. It is called like this

Example: CallableStatement cs = con.prepareCall(“{call SHOW_SUPPLIERS}”); 

10. Which are the methods that can be used to execute a Query in JDBC ?

We can make use of any one of the following methods to execute Query in JDBC

execute(): Returns true if the first object that the query returns is a ResultSet object.

executeQuery(): Returns one ResultSet object.

executeUpdate() : Returns an integer representing the number of rows affected by the SQL statement. We use this method if we are using INSERT, DELETE, or UPDATE SQL statements(DML ststements).

11).What is the difference between execute, executeQuery, executeUpdate?

Execute() – Executes the any kind of SQL statement.it returns boolean

executeQuery() – This is used generally for reading the content of the Database.The output will be in the form of ResultSet. Generally SELECT statement is used.

executeUpdate() – This is generally used for altering the databases. Generally , INSERT into TABLE, UPDATE TABLE, DELETE from TABLE statements(DML Statements) The output will be in the form of int which denotes the number of rows affected by the query.

12. What is JDBC ResltSet ?

JDBC ResultSet is like a table of data representing a database result set, which is usually generated by executing a statement that queries the database. ResultSet object maintains a cursor pointing to its current row of data.    Initially the cursor is positioned before the first row. The next() method moves the cursor to the next row. If there are no more rows, next() method returns false and it can be used in a while loop to iterate through the result set.

13. Is it mandatory to close all ResultSet, Statements and Connections ?

Yes. When you are using JDBC in your application you are allocating resources not only in your program but in a database server as well. Failure to properly closed Statements(Ststement and PreparedStatement and CallableStatement), ResultSet and Connections can cause all of the following problems

– You will run out of connections that can be opened or used

– You will not be able to create any new ResultSet

– You will not be able to execute any queries of any kind

– Your program will get very slow

– The database server get very slow

– Your program will crash

– The database server will crash

It is advisable that you should always close all the JDBC resources you obtain in the reverse order that you obtained them to avoid these issues.

14.What is metadata?

Metadata: It is nothing but a data definition of data.

In JDBC, we have two types of metadata.
1) MetaData for ResultSet(ResultSetMetaData): ResultSet is used to fetch data from tables and this MetaData keeps record like how many rows have been fetched, what are the column names etc.
 2) MetaData for Database connections(DataBaseMetaData): It has the record of database connections.

15. Why we need to use BatchUpdates ?

Batch updates are used to reduce the Database workloads. for  example if you are going to insert 120 records in database, if you do it using 120 insert SQL statements, it would definitely consume more amount of time as for each INSERT statement a connection needs to be established between DB and resources. If you perform it through batch process then all 120 statements would be inserted in table in one go, which would save time and improves resource utilization.

16. What is transaction ?

A transaction is atomic unit of Work. Which means a transaction is a collection of several tasks and if task fails then the effect will be rolled back to the previous state. In simple terms a transaction commits only when all the tasks specified in it executes successfully.

17. How do you handle your own transaction?

Connection Object has a method called setAutocommit ( boolean flag) .  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.

18.Explain JDBC Savepoint ?

A savepoint represents a point that the current transaction can roll back to. Instead of rolling all its changes back, it can choose to roll back only some of them.

19. How to rollback a JDBC transaction ?

We can use Connection object rollback() method to rollback the transaction. It will rollback all the changes made by the transaction .

20. What are the steps followed to create a batch process?

Typical sequences of steps to use Batch Processing with Statement or PrepareStatement Object are.

Create a Statement or PrepareStatement object using either createStatement() or prepareStatement() methods respectively.
Set auto-commit to false using setAutoCommit().

Add as many as SQL statements you like into batch using addBatch() method on created statement object.

Execute all the SQL statements using executeBatch() method on created statement object. Finally, commit all the changes using commit() method.

21. Explain the ways in which we can get runtime information about the JDBC Driver?

We have to Use the following DatabaseMetaData methods:

getDriverMajorVersion()

getDriverMinorVersion()

getDriverName()

getDriverVersion()

22). What are JDBC Best Practices?

Some of the JDBC Best Practices are.

        i)Database resources are heavy, so make sure you close it as soon as you are done with it. Connection, Statement, ResultSet and all other JDBC objects have close() method defined to close them

        ii) Always close the result set, statement and connection explicitly in the code, because if you are working in connection pooling environment, the connection might be returned to the pool leaving open result sets and statement objects resulting in resource leak

      iii) Close the resources in the finally block to make sure they are closed even in case of exception scenarios

      iv) Use batch processing for bulk operations of similar kind

      v) Always use PreparedStatement over Statement to avoid SQL Injection and get pre-compilation and caching benefits of PreparedStatement

23. What are SQL 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 by using which we can get SQLwarnings.

24. What is difference between java.util.Date and java.sql.Date?

java.util.Date contains information about the date and time whereas java.sql.Date contains information only about the date, it doesn’t have time information. So if you have to keep time information in the database, it is advisable to use Timestamp or DateTime fields.

25. What do you understand by DLL and DML statements ?

Data Definition Language (DDL) statements are used to define the database schema. Create, Alter, Drop, Truncate, Rename statements comes under DDL statements and usually they don’t return any result.

Data Manipulation Language (DML) statements are used to manipulate data in the database schema. Select, Insert, Update, Delete, Call etc are example of DML statements.

26. What are stored procedures ?

A stored procedure is a set of statements/commands which reside in the database. The stored procedure is precompiled.

27.Prepared Statements are faster. Why ?

Prepared statement execution is faster than direct execution because the statement is compiled only once. Prepared statements & JDBC driver are connected with each other during execution, and there are no connection overheads.

28. How to use JDBC API to call Stored Procedures ?

Stored Procedures are group of SQL queries that are compiled in the database and can be executed from JDBC API. JDBC CallableStatement can be used to execute stored procedures in the database. The syntax to intialize Callable is

CallableStatement stmt = con.prepareCall("{call insertEmployee(?,?,?,?,?,?)}");
stmt.setInt(1, id);
stmt.setString(2, name);
stmt.setString(3, role);
stmt.setString(4, city);
stmt.setString(5, country);
stmt.registerOutParameter(6, java.sql.Types.VARCHAR);
stmt.executeUpdate();

We need to register the OUT parameters before executing the CallableStatement.

29. Why “No suitable drivers” error occurs ?

No suitable driver” occurs when we are calling DriverManager.getConnection() method, it may occur because of following reasons:

1.unable to load exact JDBC drivers before calling the getConnection() method.
2.URL may be invalid or wrong JDBC URL.

30. What is the meaning of “dirty read” in database ?

As the name conveys the meaning of dirty read  is “reading  the value which may or may not be correct”. in database when one transaction is executing and changing some fields value, and at the  same time some another transaction comes and reads the changed fields value before first transaction commits or rollbacks the value then it is said to have read a wrong data . This scenario is known as dirty read.

31. What is cold backup and hot backup ?

    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

32. What is JDBC DataSource and what are its benefits ?

JDBC DataSource is the interface defined in javax.sql package and it is more powerful that DriverManager for database connections. We can use DataSource to create the database connection and Driver implementation classes does the actual work for getting connection. Apart from getting Database connection, DataSource provides some additional features such as:

1.Caching of PreparedStatement for faster processing

2. Connection timeout settings

3. Logging features

4. ResultSet maximum size threshold

5.Connection Pooling in servlet container using JNDI support

33. Explain the difference between RowSet vs. ResultSet in JDBC ?

In a ResultSet handle connection to a DB, we cannot make Result as a serialized object.Because of above issue, we cannot pass Resultset across the network.

RowSet extends the ResultSet interface, so it holds all methods from ResultSet. RowSet is serialized.So, we can pass Rowset from one class to another class because it has no connection with the database.

34. Is it possible to connect to multiple databases ? Using single statement can we ?

Yes, it is possible to connect to multiple databases, at the same time, but it depends on the specific driver.

To update and extract data from the different database we can use the single statement. But we need middleware to deal with multiple databases or a single database.

35. Explain the JDBC Architecture ?

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 below

KodNest ja

36. What is connection pooling? What is the main advantage of using connection pooling ?

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

37. Give an Example code snippet to execute the select query and display the result in ResultSet.

ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));  }

38). Write an Example Snippet to Connect Java Application with mysql database.

import java.sql.*;
class MysqlCon
{
     public static void main(String args[])
{
     try
     {
     Class.forName("com.mysql.jdbc.Driver");
     Connection con=DriverManager.getConnection(
     "jdbc:mysql://localhost:3306/Employees","root","root");
      Statement stmt=con.createStatement();
      ResultSet rs=stmt.executeQuery("select * from emp");
      while(rs.next())
      System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
      con.close();
      }
     catch(Exception e)
      {
      System.out.println(e);
       }
}
}

39. Mention Some of the Methods Present in Driver Manager class and itss uses.

The DriverManager class acts as an interface between user and drivers. It keeps track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by calling the method DriverManager.registerDriver().

Some of the methods present in DriverManager Class and its uses are shown below

  1. public static void registerDriver(Driver driver): is used to register the given driver with DriverManager.
  2. public static Connection getConnection(String url): is used to establish the connection with the specified url.
  3. public static Connection getConnection(String url,String userName,String password): is used to establish the connection with the specified url, username and password.
  4. public static Connection getConnection(String url,Properties prop): is used to establish the connection with the specified url and object of properties file.

40. Explain with a code snippet How to get object of ResultSetMetaData.

The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax:

      public ResultSetMetaData getMetaData()throws SQLException 

import java.sql.*;
class Rsmd{
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("select * from emp");
ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("Total columns: "+rsmd.getColumnCount());
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

41. Write the jdbc program to create a table in the Database.

import java.sql.*;
public class JDBCExample
 {
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
   static final String URL = "jdbc:mysql://localhost/STUDENTS";
   static final String USER = "username";
   static final String PASS = "password";
   public static void main(String[] args)
 {
   	Connection con = null;
  	 Statement stmt = null;
  	 Try
        {
      Class.forName("com.mysql.jdbc.Driver");
      con = DriverManager.getConnection(URL, USER, PASS);
      stmt = con.createStatement();
      String sql = "CREATE TABLE REGISTRATION " +
                   "(id INTEGER not NULL, " +
                   " first VARCHAR(255), " +
                   " last VARCHAR(255), " +
                   " age INTEGER, " +
                   " PRIMARY KEY ( id ))";
      stmt.executeUpdate(sql);
   }
catch(Exception e)
   {
      e.printStackTrace();
   }
finally
{
   try
    {
        con.close();
      stmt.close();
     }
     catch(Exception e)
   {
      e.printStackTrace();
   }
}
}
}

42. Write the jdbc program to insert records in to a table in the Database.

import java.sql.*;
public class JDBCExample {
   String URL = "jdbc:mysql://localhost:3306/STUDENTS";
   String USER = "username";
   String PASS = "password";
   public static void main(String[] args)
{
   Connection conn = null;
   Statement stmt = null;
   try
{
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(URL, USER, PASS);
      stmt = conn.createStatement();
      String sql = "INSERT INTO Registration " +
                   "VALUES (100, 'Zara', 'Ali', 18)";
      stmt.executeUpdate(sql);
      sql = "INSERT INTO Registration " +
                   "VALUES (101, 'Mahnaz', 'Fatma', 25)";
      stmt.executeUpdate(sql);
      sql = "INSERT INTO Registration " +
                   "VALUES (102, 'Zaid', 'Khan', 30)";
      stmt.executeUpdate(sql);
      sql = "INSERT INTO Registration " +
                   "VALUES(103, 'Sumit', 'Mittal', 28)";
      stmt.executeUpdate(sql);
   }
catch(Exception e)
{
      e.printStackTrace();
 }
finally
{
   try
    {
        con.close();
        stmt.close();
     }
     catch(Exception e)
   {
      e.printStackTrace();
   }
}
}
}

43. Write the jdbc program to Delete records in to a table in the Database.


public class JDBCExample
{
   String URL = "jdbc:mysql://localhost:3306/STUDENTS";
   String USER = "username";
   String PASS = "password";
   public static void main(String[] args)
   {
   Connection conn = null;
   Statement stmt = null;
   try{
           Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(URL, USER, PASS);
      stmt = conn.createStatement();
      String sql = "DELETE FROM Registration " +
                   "WHERE id = 101";
      stmt.executeUpdate(sql);
      sql = "SELECT id, first, last, age FROM Registration";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next())
      {
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         System.out.print(" ID:  " + id);
         System.out.print(" , Age: " + age);
         System.out.print(" , First: " + first);
         System.out.println(" , Last: " + last);
      }
   }
   catch(Exception e)
     {
            e.printStackTrace();
   }
  finally
{
   try
    {
        con.close();
      stmt.close();
       rs.close();
     }
     catch(Exception e)
   {
      e.printStackTrace();
   }
}
}
}

44. Write the jdbc program to Update records in to able in the Databse.

import java.sql.*;
public class JDBCExample
{
   static final String DB_URL = "jdbc:mysql://localhost:3306/STUDENTS";
   static final String USER = "username";
   static final String PASS = "password";
   public static void main(String[] args)
 {
   Connection conn = null;
   Statement stmt = null;
   try
{
      Class.forName("com.mysql.jdbc.Driver");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      stmt = conn.createStatement();
      String sql = "UPDATE Registration " +
                   "SET age = 30 WHERE id in (100, 101)";
      stmt.executeUpdate(sql);
      sql = "SELECT id, first, last, age FROM Registration";
      ResultSet rs = stmt.executeQuery(sql);
      while(rs.next())
     {
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
   }
   catch(Exception e)
     {
      e.printStackTrace();
     }
    finally
{
   try
    {
        con.close();
      stmt.close();
      rs.close();
     }
     catch(Exception e)
   {
      e.printStackTrace();
   }
}
}
}

45).Explain Scrollable ResultSet with an Example

In Jdbc ResultSet Interface are classified into two type;.

1.Non-Scrollable ResultSet in JDBC

2.Scrollable ResultSet

By default a ResultSet Interface is Non-Scrollable, In non-scrollable ResultSet we can move only in forward direction (that means from first record to last record), but not in Backward Direction, If you want to move in backward direction use Scrollable Interface.

KodNest rs

To create a Scrollable ResultSet, create Statement object with two parameters.

Syntax:

Statement stmt=con.CreateStatement(param1, param2);

In the above syntax param1 and param2 are modes. These type and mode are predefined in ResultSet Interface of Jdbc like below which is static final.

Types:

public static final int TYPE_FORWARD_ONLY=1003
public static final int TYPE_SCROLL_INSENSITIVE=1004
public static final int TYPE_SCROLL_SENSITIVE=1005
modes:
public static final int CONCUR_READ_ONLY=1007
public static final int CONCUR_UPDATABLE=1008

Note: To create Statement object we can pass either int value as parameter or their variable name.

Statement stmt=con.CreateStatement(1004, 1007);

Or

Statement stmt=con.CreateStatement(ResutlSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

We can use the below mentioned methods to move the cursor in scrollable ResultSet

i)afterLast ():Used to move the cursor after last row.
ii)beforeFirst(): Used to move the cursor before first row.
iii)previous(): Used to move the cursor backward.
iv)first(): Used to move the cursor first at row.
v)last(): Used to move the cursor at last row.

import java.sql.*;
class ScrollableTest
{
public static void main(String[] args) throws Exception
{
Connection con;
Statement stmt;
ResultSet rs;
try
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:@//localhost:1521/xe","system","system");
stmt=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=stmt.executeQuery("select * from student");
//reading from button to top
rs.afterLast();
while(rs.previous())
{
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getInt(3));
}
//move the cursor to 3rd record
rs.absolute(3);
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getInt(3));
//move the cursor to 2nd record using relative()
rs.relative(-1);
System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getInt(3));
int i=rs.getRow(); // get cursor position
System.out.println("cursor position="+i);
}
catch(Exception e)
{
  e.printStackTrace();
}
finally
{
try
{
rs.close();
stmt.close();
con.close();
}
catch(Exception e)
{
  e.printStackTrace();
}
}
 }
}

46. Can I get a null ResultSet ?

No, It is not possible to get null ResultSet. Database Drivers will always return a result set for a query. rs.next() can be used to see whether next record contains a row or not, here rs is a ResultSet object.

47. What is a web application ?

Web application is a collection of components assembled to provide services over the web for users to consume the service provided. Example: online train ticket reservation, internet banking.

48. How are web application accessed ?

Web applications are accessed over the web using URL address. URL stands for Uniform Resource Locator which is a unique identifier available to locate a particular service.

49. How Http works ?

HTTP stands for Hypertext Transfer Protocol. The following below steps explains about working:

Clients opens connection.

Clients sends HTTP request.

Server sends HTTP response.

Client closes connection.

50. Why HTTP is called stateless protocol ?

Since the connection is open and closed for each HTTP request, the state is not maintained across HTTP requests. Hence HTTP is called “Stateless Protocol”.

51. What is a servlet ?

A servlet is a java program that runs within a web server and serves the client request .Because it serves the client the name is  servlet. Servlets can receive and respond to requests from web clients working on HTTP protocol.

52. What is a servlet container ?

A servlet container is a container for servlets which is responsible for managing the servlets. The main functions are load, initialize and execute servlets to serve client requests. When a request is received, the container decides what servlet to call based on a configuration file.

53. What is CGI ?

Common Gateway Interface(CGI) was the most commonly used for server side scripting before the evolution of the java servlet technology. With traditional CGI, a new process is started for each HTTP request eating up more of the CPU cycles thus degrading the performance of the system.

54. What are the advantages of servlet over CGI ?

i.When a CGI script is called, a new process is created for each and every client request. But for servlets, each request is handled by a separate thread. Hence, servlet is more efficient because process creation takes more time compared to thread creation.

ii.For each new CGI requests, CGI script is copied into memory. But with servlets, there is only one copy across requests and is shared among threads.

iii.In CGI multiple process serves concurrent requests. But in  servlets, only single Process serves  concurrent request.

55. Describe about the life cycle of servlet ?

Life cycle methods of a servlet are:

init() method: During initialization web container initializes the servlet instance by calling the init() method passing a ServletConfig interface object as parameter. The ServletConfig object allows the servlet to access initialization parameters. It is called only once in the life cycle of servlet.

service() method: When client requests are serviced this method gets called. Each requests is serviced in its own thread. For every client requests web container calls the servlet’s service() method.

destroy() method: The web container calls the destroy method and takes the servlet out of service. It is called only once in the life cycle of servlet, when you stop the server or when you undeploy the application from the server.

56. Explain servlet class hierarchy.

Interface Servlet: It declares the standaed API’s which all the servlet implementations needs to define. All servlet classes must implement this interface directly or indirectly.

Class GenericServlet: It defines a generic, protocol independent servlet. Servlet developed to cater NON-HTTP requests.

Class HTTPServlet: Servlet used to cater client HTTP requests.

KodNest s

57. What is init() method of Servlet API?

It is a life cycle method of a servlet .It is called by the servlet container to indicate to a servlet that the servlet is being placed into service. Init() method takes ServletConfig object as an argument. ServletConfig object contains initialization and startup parameters for the servlet.

58. What is destroy() method of Servlet interface?

It is a life cycle method of a servlet .It is invoked by the servlet container to indicate that the servlet is taken out of service.

59. What is service() method of Servlet API ?

It is a life cycle method of a servlet .It is invoked by the servlet container to allow the servlet to respond to a request.

60. What is HTTPServlet ?

HTTPServlet is an abstract class. Any servlet that works on the HTTP should extend this class

61. Explain beiefly the doGet and doPost methods in HTTPServlet ?

protected void doGet(HTTPServletRequest req, HTTPServletResponse res)

Above method is called by the container to allow a servlet to handle a GET request. It will be called when a URL is requested or the form method is GET.

protected  void doPost(HTTPServletRequest req, HTTPServletResponse res)

It is called by the container to allow a servlet to handle a POST request. It will be called when the form method is POST.

62. What is web.xml file ?

web.xml is a configuration file which captures the application configuration and deployment details of a web application.

Hence in webapplications we call the web.xml as deploymentdescriptor

63. What are servlet initialization parameters?

Initialization parameters are used by developers to set some parameter values for the servlet to use. This will be stored as key/value pairs.

64. How do we set init oarameter in web.xml ?

Init parameters are declared inside <init-param> tag. The parameter name is declared using  <param-name> and value using  <param-value> . Init parameter is declared separately for each servlet. Each init parameter needs to declared inside a separate <init- param> tag. For example,

<servlet>
<display-name>Sample</display-name>
<servlet-name>Sample</servlet-name>
<servlet-class>Sample</servlet-class>
<init-param>
<param-name>URL</param-name>
	<param-value>jdbc:mysql:@//localhost:3306/Employees</param-value>
</init-param>
<init-param>
	<param-name>USER</param-name>
	<param-value>root</param-value>
</init-param>
	<init-param>
	<param-name>PASSWORD</param-name>
	<param-value>root</param-value>
</init-param>
</servlet>

65. How to read initialization parameter?

Init parameter can be read using the getInitParameter(ServletConfig  sc) method of ServletConfig object.

String var = sc.getInitParameter(String parameterName)

Where sc is the ServletConfig object and parameterName is the key name of the parameter set in web.xml.

Example:
public void init(ServletConfig sc)
	{
		try
		{
		String driver=sc.getInitParameter("DRIVER");
		String url=sc.getInitParameter("USER");
		String password=sc.getInitParameter("PASSWORD");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

66. What is a servlet context ?

It refers to the context in which the servlet runs. It is a gateway between the web container and the servlets. There will be only one instance of servlet context per web application shared by all the servlets in the application. It is used for storing values which can be shared across all the servlets in the web application.

<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<context-param>
 <param-name>URL</param-name>
 <param-value>jdbc:mysql:@//localhost:3306/Employees</param-value>
</context-param>
<context-param>
<param-name>USER</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<param-name>PASSWORD</param-name>
<param-value>root</param-value>
</context-param>
</web-app>

67. How can we read context parameters ?

Context parameters can be read using getInitParameter() method of the ServletContext interface.

Example:
public class Sample extends HttpServlet
{
	ServletConfig sc;
	ServletContext sct;
	public void init(ServletConfig sc)
	{
		try
		{
		sct=sc.getServletContext();
		String driver=sct.getInitParameter("DRIVER");
		String url=sct.getInitParameter("USER");
		String password=sct.getInitParameter("PASSWORD");
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

68. What is servlet chaining?

Servlet chaining is a technique in which two or more servlets orchestrate in servicing a single request.

Or

Dispatching the request from one servlet to another servlet  is called as servletchaining

 In servlet chaining, one servlet’s response is piped to next servlet’s input. This process continues until the last servlet is reached. Its output is sent back to the client. The same request and response object are available across all the servlets in the process.

 Example 1:One level servlet chaining

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
	req. getRequestDispatcher("/CHAINING/Servlet2").forward(req, res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet
{
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
			PrintWriter pw=res.getWriter();
			pw.println("HELLO..");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Example 2: Two level servlet chaining

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
	req. getRequestDispatcher("/CHAINING/Servlet2").forward(req, res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
	req. getRequestDispatcher("/CHAINING/Servlet3").forward(req, res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet
{
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
			PrintWriter pw=res.getWriter();
			pw.println("HELLO..");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

69. Explain about two ways of servlet chaining?

Two ways of servlet chaining are:

Forward: The servlet being requested by the client forwards the request to one or more servlet and finally the response is sent to the client by last servlet invoked in the Chain.

Include: This refers to the process of including the response of one or more servlets with the response of the servlet being requested and the collated response sent to the client by the servlet being requested.

KodNest fo
KodNest in 1

Example 1: ServletChaining using forward

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
	req. getRequestDispatcher("/CHAINING/Servlet2").forward(req, res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
			req.getRequestDispatcher("/CHAINING/Servlet3").forward(req, res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet
{
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
			PrintWriter pw=res.getWriter();
			pw.println("HELLO..");
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Example 2: ServletChaining using include

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet1 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
req.getRequestDispatcher("/CHAINING/Servlet2").forward(req,res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet {
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
		PrintWriter pw=res.getWriter();
		pw.println("HELLO  "); req.getServletContext().getRequestDispatcher("/CHAINING/Servlet3").include(req,res);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet2 extends HttpServlet
{
	public void service(HttpServletRequest req,HttpServletResponse res)
	{
		try
		{
			PrintWriter pw=res.getWriter();
			pw.println("World..");
		}
		catch (Exception e)
                 {
			e.printStackTrace();
		}
	}
}

70. What is a RequestDispatcher object ?

RequestDispatcher is an object which accepts the request from the client and redirects them to any resource(Servlets, JSP, HTML etc). The servlet container creates the RequestDispatcher object.

71. What is seession management ?

Session management is a mechanism for maintaining state across multiple HTTP requests. This is managed by the web container. In other words it is a technique to hold some values passed by user across multiple HTTP requests arising out from a single browser instance.

72. How long session life cycle is managed ?

Session life cycle is managed for each web browser instance opened and it exists till the browser is closed or till the session time outs(set in the server configurations).

73. What is the need for session ?

HTTP is a stateless protocol. So if developers need to develop pages where needs to maintain the application user’s state across multiple requests he can use session. For example, he can store the following information: Login name, users state/city, user ID number etc.

74. How is session trackrd for a user?

Each user session is tracked by unique ID called JSESSIONID. This is similar to how a employee is identified in a organization using employee id. JSESSIONID will be generated the first time the user visits a site. JSESSIONID will be generated for each browser instance.

75. What is a cookie ?

It is a simple piece of textual information(in key value pair format) stored on the client(browser machine). Cookies information are returned to the server with every request from the client.

76. How cookies are identified in client machine ??

The browser matches the cookies present with the site URL. If a match is found, that cookie is returned with the request.

77. What are the steps for using cookie ?

Step i: Create the cookie object.

Step ii: Set the cookie object to the HTTP response.

Step iii: Read the cookies from the next HTTP request.

Step iv: Validate the cookie value for session tracking.

78. How cookie is created ?

Cookies are created using the Cookie class of Servlet API.

Cookie cookie = new Cookie(identifier,value);

Where identifier is the name of the state information, value represents the value of the state.

Example: Cookie cookie = new Cookie(“username”,”ABC”);

79. How cookies are set to the response ?

Since cookies are stored at the client, cookies are set to the response object and sent to the client using the addCookie() method of the HTTPServletResponse interface.

Cookie cookie = new Cookie(“username”,”ABC”);

response.addCookie(cookie);

80. How cookie values are read from request ?

Cookies stored in the client will be sent to the server along with the HTTP request, each time the client requests a page. The cookies in request object can be read using the getCookies() of the HTTPServletRequest interface.

Cookie cookie[] = request.getCookies();

81. What are the advantages of using cookie ?

-> It is easy to develop and maintain.

-> Less overhead to the server since data is stored in the client.

-> It minimizes the server memory usage.

82. What are the disadvantages of using cookie ?

Size and number of cookies stored are limited.

Stored as plain text in a specific directory, everyone can view and modify them. So it is not secured.

It is browser dependent, so if client has disabled cookies this can lead to erroneous behavior of the application.

83. What is a session object ?

Session object is a container used object for storing user states in server. The session object lifecycle is maintained by web container.

The Servlet API HTTPSession interface provides features for session tracking. HTTPSession objects are objects used for storing client session information.

84. How are session values stored ?

Session values are stored in key/value format. Each value would have a name bound to it for retrieving the values.

85. How session object is accessed?

Session object associated with a user session is read from the user HTTP request using the getSession() method of the HTTPServletRequest interface.

HTTPSession session = request.getSession();

86. How to set values in HTTP Session?

We can set values in session object using setAttribute() method of the HTTPSession interface.

HTTPSession hs = request.getSession();
hs.setAttribute(String attributeName, Object value);

Let’s take a web mail application where user Name and location are stored.

HTTPSession session = request.getSession();
session.setAttribute(“user”,”ABC”);
session.setAttribute(“Location”,”Bangalore”);

87. How to retrieve attributes from session ?

We can retrieve attributes from the session object using getAttribute() method of the HTTPSession interface.

HttpSession hs = request.getSession();
Object var = hs.getAttribute(String attributeName);

Taking a web mail application where user Name and location are stored and retrieving the values.

HttpSession hs = request.getSession();
String userName = (String)hs.getAttribute(“User”);
String location = (String)hs.getAttribute(“Location”);

88. How to remove attributes from session ?

Values can be removed from the session object using removeAttribute() method of the HTTPSession interface.

HTTPSession session = request.getSession();
session.removeAttribute(String attributeName);

Example: Taking a web mail application where user Name and location are stored. Assume we need to remove the userName attribute “Tim” from the session, the following API needs to be fired on HTTP request object.

HttpSession hs = request.getSession();
session.removeAttribute(“User”);

89. How to validate a session ?

Session invalidating is the process of unbinding the session object from the user thereby removing all the previously stored data in the session and freeing the memory. To invalidate a session we call the invalidate() method.

90. When session invalidate() method is used ?

This is typically used when user logs off from a web application to free up the memory utilized by the session object.

HttpSession hs = request.getSession();
hs.invalidate();

91. Why to avoid storing bulky objects in session ?

Session objects are stored in server and it utilizes memory. So store only the needed information in sessions. Avoid bulky objects in session this can result in “out of memory error” resulting in a application crash.

92. What are the advantage of using HTTP Session ?

Simple to use since it is managed in the server. It can function even when the cookie functionality is turned off in the browser.

93. What is the difference between HTTP Get and HTTP Post ?

HTTP Get:

1. User entered information is appended in a URL string.
2. It can send only a limited amount of data.
3. The browser caches the data.

HTTP Post:

1. User entered information is send as data as a part of the message body not appended to URL.
2. It can send any amount of data.
3. The data’s are not cached.

94. What are the tasks performed by web container when a request comes for a servlet ?

Tasks performed by web container are:

1)It loads the servlet class.
2)It instantiates the servlet.
3)It initializes the servlet instance.
4)It passes request to the servlet instance.
5)Finally it sends response to the client.

95. What is a web server ?

A computer program responsible for accepting HTTP requests and serving them HTTP responses along with data, which usually are web pages such as HTML pages. They are repository of web pages.

96. What are the features of web server ?

Features of web server:

Web server program works by accepting HTTP requests from the client, and providing an HTTP response to the client.

It is a host for all server side scripting like servlet,JSP,ASP,CGI etc.

97. What is an application server ?

An application server is a software engine that delivers applications to clients. Moreover, an application server handles most of the business logic and data access of the application.

98. What are the features of application server ?

Features of application server:

Application servers enable applications to intercommunicate with dependent applications, like web servers, database management systems and chart programs.

Portals are common application server mechanism by which a single point of entry is provided to multiple devices.

EJB’s are hosted in an application server.

99. How to use ServletConfig?

ServletConfig is passed as an argument to the init() method of the servlet by the web container during servlet initialization. Hence to use ServletConfig we need to override the method:

public void init(ServletConfig config) throws ServletException

100. How ServletConfig object is loaded and initialized ?

Step i: When a request to a servlet comes for the first time from client or when the application is deployed the web container will initialize the servlet.

Step ii: The web container will parse the web.xml file and read the configurations of the servlet to be initialized.

Step iii: The web container then will create a ServletConfig object and load the configuration details of the servlet in the object.

101. What is the use of HTTPServletRequest Interface ?

This interface contains methods to access request information by the HTTP servlets. It is used by servlets to access the parameters sent by client as part of HTTP request from the browser. It is used to access client information like port number, client protocol and form field values.

102. What is the use of HTTPServletResponse interface ?

This interface contains methods for managing the response send by an HTTP servlet to the client. It also contains a set of status codes for sending the request status to the client.

103. List the do-XXXX methods in HTTPServlet?

void doGet(HTTPServletRequest req, HTTPServletResponse res)

void doPost(HTTPServletRequest req, HTTPServletResponse res)

void doHead(HTTPServletRequest req, HTTPServletResponse res)

void doOptions(HTTPServletRequest req, HTTPServletResponse res)

void doPut(HTTPServletRequest req, HTTPServletResponse res)

void doTrace(HTTPServletRequest req, HTTPServletResponse res)

void doDelete(HTTPServletRequest req, HTTPServletResponse res)

104. List different types of HTTP requests?

get, post, head, options, put, trace, delete.

105. What are the two packages that deal with servlets ?

Servlet API exist in two packages:

Javax.servlet: The classes and interfaces in javax.servlet are not protocol dependent. e.g. It can support different protocols like HTTP, FTP.

Javax.servlet.http: The classes and interface in this package are specific for requests using HTTP protocol. Some of the classes and interfaces in this package extend those of javax.servlet package.

106. What arre the features of servlets ?

Security: A Web container provides a runtime environment for executing a servlet. Servlets inherit the security feature provided by the web container. This allows developers to focus on the servlet functionality and leave the security issues to the Web container to handle.

Session management: It is the mechanism of tracking the state of a user across multiple requests. A session maintains the client identity and state across multiple requests.

Instance persistence: Servlets help to enhance the performance of the server by preventing frequent disk access. For example, if a customer logs on to an online banking site, the customer can perform activities, such as checking for the balance or applying for a loan. The account number of the customer will be validated at every stage from the database. Instead of every time checking the account number against the database, servlets retain the account number in the memory till the user logs out of the Web site.

It is platform and server independent.

107. Explain the web application directory structure ?

web application’s directory structure has document root which contains JSP files, HTML files, JavaScript files and static files such as image files. There is a directory WEB-INF under the document root which contains configuration files related to application. This configuration files can’t be served directly to the client. The WEB-INF directory contains:

/WEB-INF/classes/* : It contains compiled class files

/WEB-INF/lib/*.jar : It contains different library jar files

/WEB-INF/web.xml : It is a deployment descriptor that specify the web application configuration.

108. How Send Redirect works ?

User requests a URL to the server.
Server sends the browser a status to redirect to a new URL.
Browser requests a new URL and sends a new request.

109. What are session management techniques ?

The following are the session management techniques. These are used for managing the data’s between pages of the user in a session.

Hidden Form fields
URL Rewriting
Cookies
Session object

110. What is a Hidden Field ?

Hidden Fields are nothing but normal HTML form element with type Hidden to store the user data across HTTP request.

111.How Hidden Form field is used for session tracking ?

The user state to be preserved across HTTP request can be stored as a hidden elements in the HTML pages which can be read from other pages.

112. How to access Hidden form field values ?

Hidden form field values can be read using request.getParameter(“key”) method.

113. What are the advantages of Hidden form field ?

It does not consume any memory space in web server as it is stored in the HTML pages.

It works even if users disable cookies.

114. What are the disadvantages of Hidden form field ?

It can be used only with HTML forms.

This is not secured.

Very complex to develop and maintain as all the pages which needs state information needs to be implemented for the hidden fields.

115. What is URL rewriting ?

The mechanism by which the user state or information’s are appended to the URL for tracking the state/session of the user. Example: The userName is appended to the URL.

https://www.kodnest.com/SuccessServlet?userName=”Tim”&location=”India”

where, userName and location are user information set as parameter in the URL.

116. What are the advantages of URL rewritting ?

Every data is appended to the URL. So it is easy to debug.

It works even if users disable cookies.

117. What are the disadvantages of URL rewriting ?

URL length is a limitation, so we cannot store information beyond a limit.

The URL contains data so it is not secured.

Difficult to maintain in large application since in each page the URL should be rewritten to carry the data.

118. What is a servlet filter ?

Servlet filter are programs that runs on the server which intercepts HTTP request/response for transformations/processing/filtering.

119. How does filter work ?

Steps of operation of a servlet filter:

Step 1: Intercepts the HTTP request and preprocess the request.
Step 2: Invokes the requested resource with the preprocessed HTTP request.
Step 3: Intercepts the HTTP response and transforms it.
Step 4: The transformed HTTP response will be sent back to the client.

120. What are the usage of filters ?

Used for authenticating all HTTP request coming to the server. Example: All requests to the application will be authenticated and authorized against stored user credentials.

All the HTTP requests can be logged and audited in a flat file or database for tracking users of a web application. Example: The user credentials can be logged as “Ron logged in at 8:00 PM and he transferred 10,000 dollars from the account.

To perform some formatting of HTTP response, say display a message in the header (or) bread crumbs for all the pages of the application. Example: All the HTML pages displayed in the client should have the navigation breadcrumb like “Home Page> Savings Account> Account Summary”

121. What are the steps to create a filter ?

Step 1: Create a class that implements the filter interface.
Step 2: Implement the doFilter method with the pre/post processing logic.
Step 3: Invoke the doFilter method of the FilterChain object.
Step 4: Register the filter with the appropriate servlet.

122. What is doFilter method ?

public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws ServletException, IOException

This method is executed every time when a servlet (or) JSP associated with this filter is invoked. This contains the filtering or pre and post processing logic.

123. Why do we override doFilter method?

 

It is overridden to perform one or more of the following tasks:

Transform the incoming request.

Transform the response before being sent to the client.

It invokes the doFilter method of the FilterChain interface.

124. What is filter chaining ?

Filter chaining is the process of applying more than one filter to a servlet.

125. How servlet filter chain works ?

Multiple filters can be chained.the  Order is dictated by the order of <filter> elements in the deployment descriptor.

The first filter of the filter chain is invoked by the container via doFilter(ServletRequest req, ServletResponse res, FilterChain chain) method. The filter then perform whatever filter logic and then call the next filter in the chain by calling chain.doFilter(…) method.

The last filter’s call to chain.doFilter() which ends up calling service() method of the Servlet.

126. How to send error message to client ?

Error message can be send to client by using methods:

public void sendError(int status_code)

or

public void sendError(int status_code, String message)

Status_code describes the type of error occurred, message describes the error and sends the error response to the client.

127. Explain HTTP request briefly ?

An HTTP request has three parts:

A request line.

One or more request headers.

A message.

A request line looks like: GET /WelcomeProject/Home.html HTTP/1.1

1st token is the name of the HTTP method, which is GET in this case.
2nd token is the URI, that gives information about the location of the resource to be gotten.
3rd token is the version of HTTP to be used.

128. Explain HTTP response briefly ?

An HTTP response has three parts:

A response line

One or more response headers

A message

A response line looks like: HTTP/1.1 200 OK

1st token is the HTTP version.
2nd token is one of the many predefined status codes.
3rd token is an English descriptio

129. Explain MVC design pattern?

Model-View-Controller (MVC) is a design pattern which divides a software application into three parts namely model, view and controller.

A model deals with behavior of the application. It contains the data and business logic of the application. It notifies views and controllers when there is change in its state.

A view renders the information to the user so that it looks attractive and appealing. It takes information from the model using which it generates output.

A controller takes input from user and sends command to model or view. It controls the flow of application.

130. How MVC works ?

i): The controller servlet handles the user’s request.

ii): The controller servlet then invokes the model and performs the business logic or data retrieval.

iii): The model returns back the data (response) back to the controller.

iv): The controller then transfers the data to the view.

v): The view renders the data in the appropriate format requested by the client.

131. What are the benefits of MVC ?

Clear separation of layers, modular and easy to maintain. Example: The model holds business logic or data manipulation logic and view holds the presentation logic. System is modular and easy to maintain as developer know which logic is present in which layer.

Supports parallel development so reduces development time. Example: The view and model can be developed by different teams and finally integrated. This reduces development time to market.

Flexible for future enhancements. Example: Any changes done like database up gradation or change in business logic it is enough if the model is changed without changing the view or controller.

Related Articles

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

Hackerearth-Java

     1. Challenge : Welcome to Java! Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs…

Hackerearth-Algorithm

      1. Challenge: Quicksort 1 – Partition The previous challenges covered Insertion Sort, which is a simple and intuitive sorting algorithm with a running…

Responses

Your email address will not be published. Required fields are marked *

KodNest Training New Batch is starting on 5th October 2020. Attend one week free demo classes.Register Now

New Report

Close