Saturday, December 6, 2008

jdbc interview question and answer

JDBC
1) What are the steps in the JDBC connection? While making a JDBC connection we go through the following steps : Step 1 : Register the database driver by using : Class.forName(\" driver classs for that specific database\" ); Step 2 : Now create a database connection using : Connection con = DriverManager.getConnection(url,username,password); Step 3: Now Create a query using : Statement stmt = Connection.Statement(\"select * from TABLE NAME\"); Step 4 : Exceute the query : stmt.exceuteUpdate();
2) What is JDBC?

JDBC is a set of Java API for executing SQL statements. This API consists of a set of classes and interfaces to enable programs to write pure Java Database applications.



3) What are drivers available?

a) JDBC-ODBC Bridge driver
b) Native API Partly-Java driver
c) JDBC-Net Pure Java driver
d) Native-Protocol Pure Java driver

4) What is the difference between JDBC and ODBC?

a) OBDC is for Microsoft and JDBC is for Java applications.
b) ODBC can't be directly used with Java because it uses a C interface.
c) ODBC makes use of pointers which have been removed totally from Java.
d) ODBC mixes simple and advanced features together and has complex options for simple queries. But JDBC is designed to keep things simple while allowing advanced capabilities when required.
e) ODBC requires manual installation of the ODBC driver manager and driver on all client machines. JDBC drivers are written in Java and JDBC code is automatically installable, secure, and portable on all platforms.
f) JDBC API is a natural Java interface and is built on ODBC. JDBC retains some of the basic features of ODBC.


5) What are the types of JDBC Driver Models and explain them?

There are two types of JDBC Driver Models and they are:

a) Two tier model

b) Three tier model

Two tier model: In this model, Java applications interact directly with the database. A JDBC driver is required to communicate with the particular database management system that is being accessed. SQL statements are sent to the database and the results are given to user. This model is referred to as client/server configuration where user is the client and the machine that has the database is called as the server.

Three tier model: A middle tier is introduced in this model. The functions of this model are:
a) Collection of SQL statements from the client and handing it over to the database,
b) Receiving results from database to the client and
c) Maintaining control over accessing and updating of the above.


6) What are the steps involved for making a connection with a database or how do you connect to a database?

a) Loading the driver : To load the driver, Class.forName( ) method is used.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

When the driver is loaded, it registers itself with the java.sql.DriverManager class as an available database driver.

b) Making a connection with database : To open a connection to a given database,
DriverManager.getConnection( ) method is used.
Connection con = DriverManager.getConnection ("jdbc:odbc:somedb", "user", "password");
c) Executing SQL statements : To execute a SQL query, java.sql.statements class is used.
createStatement( ) method of Connection to obtain a new Statement object.
Statement stmt = con.createStatement( );
A query that returns data can be executed using the executeQuery( ) method of Statement. This method
executes the statement and returns a java.sql.ResultSet that encapsulates the retrieved data:
ResultSet rs = stmt.executeQuery("SELECT * FROM some table");
d) Process the results : ResultSet returns one row at a time. Next( ) method of ResultSet object can be called to move to the next row. The getString( ) and getObject( ) methods are used for retrieving column values:
while(rs.next( ) ) {
String event = rs.getString("event");
Object count = (Integer) rs.getObject("count");


7) What type of driver did you use in project?

JDBC-ODBC Bridge driver (is a driver that uses native(C language) libraries and makes calls to an existing ODBC driver to access a database engine).


8) What are the types of statements in JDBC?

Statement -- To be used createStatement() method for executing single SQL statement
PreparedStatement -- To be used preparedStatement() method for executing same SQL statement over and over .

CallableStatement -- To be used prepareCall( ) method for multiple SQL statements over and over.


9) What is stored procedure?

Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task.
Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.


10) How to create and call stored procedures?

To create stored procedures:
Create procedure procedurename (specify in, out and in out parameters)
BEGIN
Any multiple SQL statement;
END;

To call stored procedures:
CallableStatement csmt = con.prepareCall("{call procedure name(?,?)}");
csmt.registerOutParameter(column no., data type);
csmt.setInt(column no., column name)
csmt.execute( );





11)Why do we have index table in the database?

Because the index table contain the information of the other tables. It will be faster if we access the index table to find out what the other contain.


12) Give an example of using JDBC access the database.

Answer:
try
{
Class.forName("register the driver");
Connection con = DriverManager.getConnection("url of db", "username","password");
Statement state = con.createStatement();
state.executeUpdate("create table testing(firstname varchar(20), lastname varchar(20))");
state.executeQuery("insert into testing values('phu','huynh')");
state.close();
con.close();
}
catch(Exception e)
{
System.out.println(e);
}


13)What are the two major components of JDBC?

One implementation interface for database manufacturers, the other implementation interface for application and applet writers.



14)What is JDBC Driver interface?

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.


15)What are the common tasks of JDBC?

1.Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers; 2. Register a driver; 3. Specify a database; 4. Open a database connection; 5. Submit a query; 6. Receive results.


16)What packages are used by JDBC?

There are 8 packages: java.sql.Driver, Connection,Statement, PreparedStatement, CallableStatement, ResultSet, ResultSetMetaData, DatabaseMetaData.


17)What are the flow statements of JDBC?

A URL string -->getConnection-->DriverManager-->Driver-->Connection-->Statement-->executeQuery-->ResultSet.


18)What are the steps involved in establishing a connection?

This involves two steps: (1) loading the driver and (2) making the connection.


19)How can you load the drivers?

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

Eg.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code:
E.g.
Class.forName("jdbc.DriverXYZ");


20)What Class.forName will do while loading drivers?

It is used to create an instance of a driver and register it with the DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS.


21)How can you make the connection?

In establishing a connection is to have the appropriate driver connect to the DBMS. The following line of code illustrates the general idea:

E.g.
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, "Fernanda", "J8");


22)How can you create JDBC statements?

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

Statement stmt = con.createStatement();


23)How can you retrieve data from the ResultSet?

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


24)What are the different types of Statements?

1.Statement (use createStatement method) 2. Prepared Statement (Use prepareStatement method) and 3. Callable Statement (Use prepareCall)


25)How can you use PreparedStatement?

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 ?");


26)How to call a Stored Procedure from JDBC?

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

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


27)How to Retrieve Warnings?

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

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();
}
}


28)How to Make Updates to Updatable Result Sets?

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

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");



29). What is JDBC ? what are its advantages ?

It is an API .The latest version of jdbc api is (3.0).
The JDBC 3.0 API is divided into two packages:
(1) java.sql and (2) javax.sql.
Both packages are included in the J2SE and J2EE platforms.

Advantages:

The JDBC API can be used to interact with multiple data sources in a distributed, heterogenous environment.
It can connect to any of the database from java language.
It can switch over to any backend database without changing java code or by minute changes.


30). How many JDBC Drivers are there ? what are they?

There are 4 types of JDBC drivers.
a. JDBC-ODBC Bridge Driver(Type-1 driver)
b. Native API Partly Java Driver(Type-2 driver)
c. Net protocol pure Java Driver(Type-3 driver)
d. Native protocol Pure Java Driver(Type-4 driver)


31. Explain about JDBC-ODBC driver(Type-1) ? When this type of driver is used ?

In this mechanism the flow of execution will be

Java code(JDBC API)<------>JDBC-ODBC bridge driver<------->ODBC API<------->ODBC Layer<-------->DataBase

This type of JDBC Drivers provides a bridge between JDBC API and ODBC API.
This Bridge(JDBC-ODBC bridge) translates standard JDBC calls to Corresponding ODBC Calls, and
send them to ODBC database via ODBC Libraries.


The JDBC API is based on ODBC API.
ODBC(Open Database Connectivity)is Microsoft's API for Database drivers.
ODBC is based on X/Open Call Level Interface(CLI)specification for database access.

The URL and class to be loaded for this type of driver are

Class :- sun.jdbc.odbc.JdbcOdbcDriver
URL :- jdbc:odbc:dsnname


32. Explain about Type-2 driver ? When this type of driver is used ?

The Drivers which are written in Native code will come into this category
In this mechanism the flow of Execution will be

java code(JDBC API)<------>Type-2 driver(jdbc driver)<------->Native API(vendor specific)<------->DataBase


When database call is made using JDBC,the driver translates the request into vendor-specific API calls.
The database will process the requet and sends the results back through the Native API ,which will
forward them back to the JDBC dirver. The JDBC driver will format the results to conform to the JDBC
standard and return them to the application.



33. Explain about Type-3 driver ? When this type of driver is used ?

In this mechanism the flow of Execution will be
java code(JDBC API)<------>JDBC driver<------->JDBC driver server<-------->Native driver<------->DataBase

The Java Client Application sends the calls to the Intermediate data access server(jdbc driver server)
The middle tier then handles the requet using other driver(Type-II or Type-IV drivers) to complete the request.


34. Explain about Type-4 driver ? When this type of driver is used ?

This is a pure java driver(alternative to Type-II drivers).
In this mechanism the flow of Execution will be

java code(JDBC API)<------>Type-4 driver(jdbc driver)<------->DataBase
These type of drivers convert the JDBC API calls to direct network calls using
vendor specific networking protocal by making direct socket connection with
database.
examples of this type of drivers are
1.Tabular Data Stream for Sybase
2.Oracle Thin jdbc driver for Oracle



35. Which Driver is preferable for using JDBC API in Applets?

Type-4 Drivers.



36.Write the Syntax of URL to get connection ? Explain?

Syntax:- jdbc::
jdbc -----> is a protocal .This is only allowed protocal in JDBC.
----> The subprotocal is used to identify a database driver,or the
name of the database connectivity mechanism, choosen by the database driver providers.

-------> The syntax of the subname is driver specific. The driver may choose any
syntax appropriate for its implementation

ex: jdbc:odbc:dsn
jdbc:oracle:oci8:@ database name.
jdbc:orale:thin:@ database name:port number:SID


37.How do u Load a driver ?

Using Driver Class.forName(java.lang.String driverclass) or registerDriver(Driver driver)


38.what are the types of resultsets in JDBC3.0 ?How you can retrieve information of resultset?

ScrollableResultSet and ResultSet.We can retrieve information of resultset by using java.sql.ResultSetMetaData interface.You can get the instance by calling the method getMetaData() on ResulSet object.


39.write the steps to Connect database?

Class.forName(The class name of a spasific driver);
Connection c=DriverManager.getConnection(url of a spasific driver,user name,password);

Statement s=c.createStatement();
(or)
PreparedStatement p=c.prepareStatement();
(or)
CallableStatement cal=c.prpareCall();

Depending upon the requirement.


40.Can java objects be stored in database? how?

Yes.We can store java objects, BY using setObject(),setBlob() and setClob() methods in PreparedStatement


41.what do u mean by isolation level?

Isolation means that the business logic can proceed without
consideration for the other activities of the system.


42.How do u set the isolation level?

By using setTransactionIsolation(int level) in java.sql.Connection interface.

level MEANS:-

static final int TRANSACTION_READ_UNCOMMITTED //cannot prevent any reads.
static final int TRANSACTION_READ_COMMITTED //prevents dirty reads
static final int TRANSACTION_REPEATABLE_READ //prevents dirty reads & non-repeatable read.
static final int TRANSACTION_SERIALIZABLE //prevents dirty reads , non- repeatable read & phantom read.

These are the static final fields in java.sql.Connection interface.


43. What is a dirty read?

A Dirty read allows a row changed by one transaction to be
read by another transaction before any change in the row
have been committed.

This problem can be solved by setting the transaction isolation
level to TRANSACTION_READ_COMMITTED


44. what is a non-repeatable read ?

A non-repeatable read is where one transaction reads a row, a second
transaction alters or deletes the row, and the first transaction
re-reads the row,getting different values the second time.

This problem can be solved by setting the transaction isolation
level to TRANSACTION_REPEATABLE_READ


45. what is phantom read?

A phantom read is where one transaction reads all rows that satisfy
a WHERE condition,a second transaction inserts a row that satisfies
that WHERE condition,and the first transaction re-reads for the same
condition,retrieving the additional 'phantom' row in the second read

This problem can be solved by setting the transaction isolation
level to TRANSACTION_SERIALIZABLE


47.How to retrieve the information about the database ?

We can retrieve the info about the database by using inerface
java.sql.DatabaseMetaData

We can get this object by using getMetaData() method in
Connection interface.


48.what are the Different types of exceptions in jdbc?

BatchUpdateException
DataTruncation
SQLException
SQLWarning


49.How to execute no of queries at one go?

By using a batchUpdate's (ie throw addBatch() and executeBatch())
in java.sql.Statement interface,or by using procedures.


50. What are the advantages of connection pool.?

Performance


51.In which interface the methods commit() & rollback() are defined ?

A.java.sql.Connection interface


52.How to store images in database?

Using binary streams (i.e. getBinaryStream (), setBinaryStream ()). But it is not visible in database, it is stored in form of bytes, to make it visible we have to use any one front-end tool.


53.How to check null value in JDBC?

By using the method wasNull() in ResultSet ,it returns boolean value.
Returns whether the last column read had a value of SQL NULL.
Note that you must first call one of the getXXX methods on a column to try to read its value and then call the method wasNull to see if the value read was SQL NULL.


54.Give one Example of static Synchronized method in JDBC API?

getConnection() method in DriverManager class.Which is used to get object of Connection interface.


55.What is a Connection?

Connection is an interface which is used to make a connection between client and Database (ie opening a session with a particular database).


56.what is the difference between execute() ,executeUpdate() and executeQuery() ? where we will use them?

execute() method returns a boolean value (ie if the given query
returns a resutset then it returns true else false),so depending upon
the return value we can get the ResultSet object (getResultset())or
we can know how many rows have bean affected by our query
(getUpdateCount()).That is we can use this method for Fetching
queries and Non-Fetching queries.

Fetching queries are the queries which are used to fetch the records from database (ie which returns resutset)
ex: Select * from emp.

Non-Fetching queries are the queries which are used to update,insert,create or delete the records from database
ex: update emp set sal=10000 where empno=7809.

executeUpdate() method is used for nonfetching queries.which returns int value.

executeQuery() method is used for fetching queries which returns ResulSet object ,Which contains methods to fetch the values.



58). Using a Prepared Statement

A prepared statement should be used in cases where a particular SQL statement is used frequently. The prepared statement is more expensive to set up but executes faster than a statement. This example demonstrates a prepared statement for getting all rows from a table called ''mytable'' whose column COL_A equals ''Patrick Chan''. This example also demonstrates a prepared statement for updating data in the table. In particular, for all rows whose column COL_B equals 123, column COL_A is set to ''John Doe''.

try {

// Retrieving rows from the database.

PreparedStatement stmt = connection.prepareStatement(

"SELECT * FROM mytable WHERE COL_A = ?");

int colunm = 1;

stmt.setString(colunm, "Patrick Chan");

ResultSet rs = stmt.executeQuery();



// Updating the database.

stmt = connection.prepareStatement(

"UPDATE mytable SET COL_A = ? WHERE COL_B = ?");

colunm = 1;

stmt.setString(colunm, "John Doe");

colunm = 2;

stmt.setInt(colunm, 123);

int numUpdated = stmt.executeUpdate();

} catch (SQLException e) {

}



59.What are the types of JDBC drivers ?

Type 1- JDBC-ODBC Bridge
Type 2- Native API Driver
Type 3 - JDBC-Net,Java Pure Driver
Type 4- Native Protocol, Pure Java Driver

60.Which among the four driver is pure Java driver ?
Type 3 and Type 4

61.How do you connect without the Class.forName (" ") ?
It is not possible not connect

62.What does Class.forName return ?
Class Name

63.Why is preparedStatement,CallableStatement used for?

Preapred Stmt -SQL in the database is a precompiled, by the database for faster execution

CallableStmt-JDBC allows use of stored procedures by the CallableStatement class.

A CallableStatement object is created by the preaprecall()method in the connection object


64) Explain the role of Driver in JDBC? The JDBC Driver 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. 65) Is java.sql.Driver a class or an Interface ? It's an interface. 66) Is java.sql.DriverManager a class or an Interface ? It's a class. This class provides the static getConnection method, through which the database connection is obtained. 67) Is java.sql.Connection a class or an Interface ? java.sql.Connection is an interface. The implmentation is provided by the vendor specific Driver. 68) Is java.sql.Statement a class or an Interface ? java.sql.Statement,java.sql.PreparedStatement and java.sql.CallableStatement are interfaces. 69) Which interface do PreparedStatement extend? java.sql.Statement 70) Which interface do CallableStatement extend? CallableStatement extends PreparedStatement. 71) What is the purpose Class.forName("") method? The Class.forName("") method is used to load the driver.
72) Do you mean that Class.forName("") method can only be used to load a driver? The Class.forName("") method can be used to load any class, not just the database vendor driver class. 73) Which statement throws ClassNotFoundException in SQL code block? and why? Class.forName("") method throws ClassNotFoundException. This exception is thrown when the JVM is not able to find the class in the classpath. 74) What exception does Class.forName() throw? ClassNotFoundException. 75) What is the return type of Class.forName() method ? java.lang.Class 76) Can an Interface be instantiated? If not, justify and explain the following line of code: Connection con = DriverManager.getConnection("dsd","sds","adsd"); An interface cannot be instantiated. But reference can be made to a interface. When a reference is made to interface, the refered object should have implemented all the abstract methods of the interface. In the above mentioned line, DriverManager.getConnection method returns Connection Object with implementation for all abstract methods. 77) What type of a method is getConnection()? static method. 78) What is the return type for getConnection() method?Connection object. 79) What is the return type for executeQuery() method? ResultSet 80) What is the return type for executeUpdate() method and what does the return type indicate? int. It indicates the no of records affected by the query. 81) What is the return type for execute() method and what does the return type indicate? boolean. It indicates whether the query executed sucessfully or not.
82) Is Resultset a Classor an interface? Resultset is an interface.
83) What is the advantage of PrepareStatement over Statement? PreparedStatements are precompiled and so performance is better. PreparedStatement objects can be reused with passing different values to the queries. 84) What is the use of CallableStatement? CallableStatement is used to execute Stored Procedures. 85) Name the method, which is used to prepare CallableStatement? CallableStament.prepareCall(). 86) What do mean by Connection pooling?
Opening and closing of database connections is a costly excercise. So a pool of database connections is obtained at start up by the application server and maintained in a pool. When there is a request for a connection from the application, the application server gives the connection from the pool and when closed by the application is returned back to the pool. Min and max size of the connection pool is configurable. This technique provides better handling of database connectivity.


87. Which methods and classes are used for connection pooling?

88). How will you perform transactions using JDBC?

89). What is difference between PreparedStatement and Statement?

90). What is the difference between ExecuteUpdate and ExecuteQuery?

91). How do you know which driver is connected to a database?

92). What is DSN and System DSN and differentiate these two?

93). How you can know about drivers and database information?
94). If you are truncated using JDBC, How can you know? That how much
data is truncated?
95). What are the Normalization Rules? Define the Normalization?

Create Struts Project

How To Develop Struts


Struts framework


Introduction:

The Jakarta Struts project, an open−source project sponsored by the Apache Software Foundation, is a server−side Java implementation of the Model−View−Controller (MVC) design pattern. The Struts project was originally created by Craig McClanahan in May 2000.

Requirements:

1. Eclipse3.2

2. MyEclipse5.1


Note: Eclipse without MyEclipse - Used for running only java application.


To run struts web application, we extract the MyEclipse into the Eclipse Folder.

Componenets


There are some components that are needed to develop the struts application.

1. Actionform

2. Action

3. Struts-config.xml



STEPS


Step 1:

Open Eclipse3.2 and go to File----Project----MyEclipse----web Project and click Next. Give project Name(BlogPro) and click Finish. Here Your Project(example BlogPro) is created.


Step 2:

Add Struts capabilities. Right click on ProjectName(BlogPro). Select MyEclicpse---Add struts capabilities and click Finish.

Step 3:

Create ActionForm. Right click on Project Name(BlogPro). New---Other----web-struts---struts1.1---struts 1.1 form.----New Form window open---give form name in usecase(must start lower letter). Select org.apache.struts.action.ActionForm in super class. If you want to give form fields ,we specify the field (Optional Detail) Form properties Add and create property window opened. There give name and select type. Add more fields like this if desire. And click finish.

Step 4:

Create Action. Right click on Project Name(BlogPro). New---Other----web-struts---struts1.1---struts1.1 action. New Action window Opened. There Give action name and select org.apache.struts.action.Action in superclass. And click finish.

Step 5:

Open Action Servlet like (src—com.yourcompany.struts.action).

public ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)
{
//create object for actionform

Loginform sform=(Loginform)form;

//check validation

If((sform.getUsername.equals(“super”))
{
Request.setAttribute(“Login”,sform);

return mapping.findForward("success");
}
else
{
request.setAttribute(“Login”,sform);
return mapping.findForward(“Failure”);
}
}

Note:

we get form field values through actionform. so create object for actionform and use this object to retrieve form filed.

Step 6:

deploy deployment descriptor file.( struts-config.xml)


webroot---WEB-INF—struts-config.xml

we give name (form bean name displayed above form-bean tag) in action tag

step 7:

finally create two jsp file have to create.

success.jsp




success





failure.jsp




failure




How To Run


Enter url of the Jsp loginform.jsp. the control goes to web.xml.




action
*.do



check servlet-name in servlet-mapping with servlet-name in servlet(above)

true control goes to action servlet.

check username=”super” true control forward into struts-config.xml--

it invokes success.jsp file.

otherwise it Is false control forward into struts-config.xml--


it invokes failure.jsp file.



Note:

It is very easy to learn struts. Here after I am going to write struts framework continuously.

You have any doubt please send post your question to me. Through post.


Next Post Is Form Validation

by yours

S.Sureshkumar,M.Sc,M.Phil

Servlet Interview Question And Answer

SERVLET

1.) What is the difference between GenericServlet and HttpServlet?

A GenericServlet has a service ( ) method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet (), doPost (), doHead () methods plus doPut (), doOptions (), doDelete (), doTrace () methods. Both these classes are abstract. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality like doGet and doPost methods.

2.) How you can destroy the session in Servlet?

It can call invalidate() method on the session object to destroy the session. e.g. session.invalidate();

3.) What are different types of Session Tracking?

Mechanism for Session Tracking are:

a) Cookies

b) URL rewriting

c) Hidden form fields

d) SSL Sessions

4.)What are the uses of Servlets?

* Servlets are used to process the client request.

* A Servlet can handle multiple request concurrently and be used to develop high performance system

A Servlet can be used to load balance among serveral servers, as Servlet can easily forward request.

5.) What must be implemented by all Servlets?

The Servlet Interface must be implemented by all servlets.

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

Servlet Container uses Cookies, URL rewriting, and HTTPS protocol information to maintain the session.

7.) What are the advantages of Servlets over CGI programs?

Java Servlets have a number of advantages over CGI and other API’s. They are:

Platform Independence

Performance

Extensibility

Safety

Secure

8.) What are methods of HttpServlet?

The methods of HttpServlet class are :

* doGet() is used to handle the GET, conditional GET, and HEAD requests

* doPost() is used to handle POST requests

* doPut() is used to handle PUT requests

* doDelete() is used to handle DELETE requests

* doOptions() is used to handle the OPTIONS requests and

· doTrace() is used to handle the TRACE requests

9.) What are the types of Servlet?

There are two types of servlets, GenericServlet and HttpServlet. GenericServlet defines the generic or protocol independent servlet. HttpServlet is subclass of GenericServlet and provides some http specific functionality like doGet and doPost methods.

10.) When doGET() method will execute?

When we specified method=’GET’ in HTML Example : < name="'SSS'" method="'GET'">

11.) What is the use of ServletContext?

Using ServletContext, We can access data from its environment. Servlet context is common to all Servlets so all Servlets share the information through ServeltContext.

12.) Which protocol will be used by browser and servlet to communicate?

HTTP is the protocol that will be used by browser and servlet to communicate.

14.) which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set.

15.) What is the servlet life cycle?

When first request came in for the servlet , Server will invoke init() method of the servlet. There after if any user request the servlet program, Server will directly executes the service() method. When Server want to remove the servlet from pool, then it will execute the destroy() method.

16.) What are the uses of Servlets?

A servlet can handle multiple requests concurrently, and can synchronize requests. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers.

17.) What’s the difference between servlets and applets?

Servlets executes on Servers. Applets executes on browser. Unlike applets, however, servlets have no graphical user interface.

18.) What is the servlet?

Servlet is a script, which resides and executes on server side, to create dynamic HTML. In servlet programming, we will use java language. A servlet can handle multiple requests concurrently.

19) What are the classes and interfaces for servlets?

There are two packages in servlets and they are javax.servlet and javax.servlet.http.

Javax.servlet contains:

Interfaces Classes

Servlet Generic Servlet

ServletRequest ServletInputStream

ServletResponse ServletOutputStream

ServletConfig ServletException

ServletContext UnavailableException

SingleThreadModel

Javax.servlet.http contains:

Interfaces Classes

HttpServletRequest Cookie

HttpServletResponse HttpServlet

HttpSession HttpSessionBindingEvent

HttpSessionCintext HttpUtils

HttpSeesionBindingListener

20) What is the difference between doPost and doGet methods?

a) doGet() method is used to get information, while doPost( ) method is used for posting information.

b) doGet() requests can't send large amount of information and is limited to 240-255 characters. However, doPost( )requests passes all of its data, of unlimited length.

c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part of its HTTP request body and the exchange are invisible to the client.

21) What is the life cycle of a servlet?

Each Servlet has the same life cycle:

a) A server loads and initializes the servlet by init () method.

b) The servlet handles zero or more client's requests through service( ) method.

c) The server removes the servlet through destroy() method.

22) Who is loading the init() method of servlet?

Web server

23)What are the different servers available for developing and deploying Servlets?

a) Java Web Server

b) JRun

g) Apache Server

h) Netscape Information Server

Web Logic

24) How many ways can we track client and what are they?

The servlet API provides two ways to track client state and they are:

Using Session tracking and Using Cookies.

25) What is session tracking and how do you track a user session in servlets?

Session tracking is a mechanism that servlets use to maintain state about a series requests from the same user across some period of time. The methods used for session tracking are:

a) User Authentication - occurs when a web server restricts access to some of its resources to only those clients that log in using a recognized username and password

b) Hidden form fields - fields are added to an HTML form that are not displayed in the client's browser. When the form containing the fields is submitted, the fields are sent back to the server

c) URL rewriting - every URL that the user clicks on is dynamically modified or rewritten to include extra information. The extra information can be in the form of extra path information, added parameters or some custom, server-specific URL change.

d) Cookies - a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

e) HttpSession- places a limit on the number of sessions that can exist in memory. This limit is set in the session.maxresidents property

26) What are cookies and how will you use them?

Cookies are a mechanism that a servlet uses to have a client hold a small amount of state-information associated with the user.

Create a cookie with the Cookie constructor:

public Cookie(String name, String value)

A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse:

public void HttpServletResponse.addCookie(Cookie cookie)

A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:

public Cookie[ ] HttpServletRequest.getCookie( ).

26) Is it possible to communicate from an applet to servlet and how many ways and how?

Yes, there are three ways to communicate from an applet to servlet and they are:

a) HTTP Communication(Text-based and object-based)

b) Socket Communication

c) RMI Communication

(You can say, by using URL object open the connection to server and get the InputStream from URLConnection object).

Steps involved for applet-servlet communication:

1) Get the server URL.

URL url = new URL();

2) Connect to the host

URLConnection Con = url.openConnection();

3) Initialize the connection

Con.setUseCatches(false):

Con.setDoOutput(true);

Con.setDoInput(true);

4) Data will be written to a byte array buffer so that we can tell the server the length of the data.

ByteArrayOutputStream byteout = new ByteArrayOutputStream();

5) Create the OutputStream to be used to write the data to the buffer.

DataOutputStream out = new DataOutputStream(byteout);

27) Why should we go for interservlet communication?

Servlets running together in the same server communicate with each other in several ways.

The three major reasons to use interservlet communication are:

a) Direct servlet manipulation - allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)

b) Servlet reuse - allows the servlet to reuse the public methods of another servlet.

c) Servlet collaboration - requires to communicate with each other by sharing specific information (through method invocation)

28) Is it possible to call servlet with parameters in the URL?

Yes. You can call a servlet with parameters in the syntax as (?Param1 = xxx || m2 = yyy).

29) What is Servlet chaining?

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

In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.

30) How do servlets handle multiple simultaneous requests?

The server has multiple threads that are available to handle requests. When a request comes in, it is assigned to a thread, which calls a service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

31) Are servlets platform independent? If so Why? Also what is the most common application of servlets?

Yes, Because they are written in Java. The most common application of servlet is to access database and dynamically construct HTTP response

32). What is the three tier model?

It is the presentation, logic, backend

33) Describe 3-Tier Architecture in enterprise application development.?

In 3-tier architecture, an application is broken up into 3 separate logical layers, each with a well-defined set of interfaces. The presentation layer typically consists of a graphical user interfaces. The business layer consists of the application or business logic, and the data layer contains the data that is needed for the application.

34) What's the advantages using servlets than using CGI?

In CGI,create separate process for every request.where as in servlet,not create separate process.

35) What's the Servlet Interface?

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 such as HttpServlet. Servlets-->Generic Servlet-->HttpServlet-->MyServlet. The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet.

37) When a servlet accepts a call from a client, it receives two objects. What are they?

ServeltRequest: which encapsulates the communication from the client to the server.

ServletResponse: which encapsulates the communication from the servlet back to the client.

ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

38) What information that the ServletRequest interface allows the servlet access to?

Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.

39) What information that the ServletResponse interface gives the servlet methods for replying to the client?

It allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.

40) If you want a servlet to take the same action for both GET and POST request, what you should do?

Simply have doGet call doPost, or vice versa.

41) What is the servlet life cycle?

Each servlet has the same life cycle:

* A server loads and initializes the servlet (init())

* The servlet handles zero or more client requests (service())

* The server removes the servlet (destroy()) (some servers do this step only when they shut down)

42) Which code line must be set before any of the lines that use the PrintWriter?

setContentType() method must be set before transmitting the actual document.

43) How HTTP Servlet handles client requests?

An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.

44) When using servlets to build the HTML, you build a DOCTYPE line, why do you do that?

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 validators 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.(http://validator.w3.org and http://www.htmlhelp.com/tools/validator/ are two major online validators)

45) What are the types of ServletEngines?

Standalone ServletEngine:A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine:Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.

46) What is a Session Id?

It is a unique id assigned by the server to the user when a user first accesses a site or an application ie. when a request is made.

47). List out Differences between CGI Perl and Servlet?

Servlet CGI

Platform independent Platform dependent.

Language dependent Language independent.

48) What is servlet tunnelling?.

Used in applet to servlet communications, a layer over http is built so as to enable object serialization.

49). What is a cookie?.

Cookies are a way for a server to send some information to a client to store and for the server to later retrieve its data from that client.Web browser supports 20 cookies/host of 4kb each.

50). What is the frontend in Java?.Also what is Backend?.

Frontend: Applet

Backend : Oracle, Ms-Access(Using JDBC).

51) What is the default HttpRequest method?.

doGet().

52) Why do u use Session Tracking in HttpServlet ?

HTTP is a stateless protocol ;it provides no way for a server to recognize that a sequence of requests are all from the same client .

53) Can u use javaScript in Servlets ?

YES

54) What is the capacity the doGet can send to the server ?

Some servers limit the length of URL's and query strings to about 240 charcters

55).What are the type of protocols used in HttpServlet ?

HTTP,HTTPS

56)What is a Servlet?

A Servlet is a server side java program which processes client requests and generates dynamic web content.


57) Explain the architechture of a Servlet?


javax.servlet.Servlet interface is the core abstraction which has to be implemented by all servlets either directly or indirectly. Servlet run on a server side JVM ie the servlet container.Most servlets implement the interface by extending either javax.servlet.GenericServlet or javax.servlet.http.HTTPServlet.A single servlet object serves multiple requests using multithreading.


58) What is the difference between an Applet and a Servlet?


An Applet is a client side java program that runs within a Web browser on the client machine whereas a servlet is a server side component which runs on the web server. An applet can use the user interface classes like AWT or Swing while the servlet does not have a user interface. Servlet waits for client's HTTP requests from a browser and generates a response that is displayed in the browser.


59) What is the difference between GenericServlet and HttpServlet?


GenericServlet is a generalised and protocol independent servlet which defined in javax.servlet package. Servlets extending GenericServlet should override service() method. javax.servlet.http.HTTPServlet extends GenericServlet. HTTPServlet is http protocol specific ie it services only those requests thats coming through http.A subclass of HttpServlet must override at least one method of doGet(), doPost(),doPut(), doDelete(), init(), destroy() or getServletInfo().



60) Explain life cycle of a Servlet?


On client's initial request, Servlet Engine loads the servlet and invokes the init() methods to initialize the servlet. The servlet object then handles subsequent client requests by invoking the service() method. The server removes the servlet by calling destry() method.


61) What is the difference between doGet() and doPost()?


doGET Method : Using get method we can able to pass 2K data from HTML All data we are passing to Server will be displayed in URL (request string).

doPOST Method : In this method we does not have any size limitation. All data passed to server will be hidden, User cannot able to see this info on the browser.

62) What is the difference between ServletConfig and ServletContext?


ServletConfig is a servlet configuration object used by a servlet container to pass information to a servlet during initialization. All of its initialization parameters can only be set in deployment descriptor. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized. ServletContext is an interface which defines a set of methods which the servlet uses to interact with its servlet container. ServletContext is common to all servlets within the same web application. Hence, servlets use ServletContext to share context information.


63) What is the difference between using getSession(true) and getSession(false) methods?


getSession(true) method will check whether already a session is existing for the user. If a session is existing, it will return the same session object, Otherwise it will create a new session object and return taht object.

getSession(false) method will check for the existence of a session. If a session exists, then it will return the reference of that session object, if not, it will return null.

64) What is meant by a Web Application?


A Web Application is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.


65) What is a Server Side Include ?


Server Side Include is a Web page with an embedded servlet tag. When the Web page is accessed by a browser, the web server pre-processes the Web page by replacing the servlet tag in the web page with the hyper text generated by that servlet.


66) What is Servlet Chaining?


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.


67) How do you find out what client machine is making a request to your servlet?


The ServletRequest class has functions for finding out the IP address or host name of the client machine. getRemoteAddr() gets the IP address of the client machine and getRemoteHost()gets the host name of the client machine.

68) What is the structure of the HTTP response?


The response can have 3 parts:


1) Status Code - describes the status of the response. For example, it could indicate that the request was successful, or that the request failed because the resource was not available. If your servlet does not return a status code, the success status code, HttpServletResponse.SC_OK, is returned by default.
2) HTTP Headers - contains more information about the response. For example, the header could specify the method used to compress the response body.
3) Body - contents of the response. The body could contain HTML code, an image, etc.


69) What is a cookie?


A cookie is a bit of information that the Web server sends to the browser which then saves the cookie to a file. The browser sends the cookie back to the same server in every request that it makes. Cookies are often used to keep track of sessions.


70) Which code line must be set before any of the lines that use the PrintWriter?


setContentType() method must be set.


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


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.


72) How can a servlet refresh automatically if some new data has entered the database?


You can use a client-side Refresh or Server Push


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


As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation. The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on hard disk.


74) What is HTTP Tunneling?


HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and sent as HttpRequest. The masking of other protocol requests as http requests is HTTP Tunneling.

75) What's the difference between sendRedirect( ) and forward( ) methods?


A sendRedirect method creates a new request (it's also reflected in browser's URL ) where as forward method forwards the same request to the new target(hence the change is NOT reflected in browser's URL). The previous request scope objects are no longer available after a redirect because it results in a new request, but it's available in forward. sendRedirect is slower compared to forward.


76) Is there some sort of event that happens when a session object gets bound or unbound to the session?


HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).


77) Is it true that servlet containers service each request by creating a new thread? If that is true, how does a container handle a sudden dramatic surge in incoming requests without significant performance degradation?


The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool. For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.


78) What is URL Encoding and URL Decoding?


URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters and Decoding is the reverse process converting all Hex Characters back their normal form.


For Example consider this URL,
/ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/") the output is
http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F
This can be decoded back using
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")


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


Yes, the objects need to be serializable, but only if your servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if your engine does support persistent sessions, it is usually possible to disable this feature.


80) What is the difference between session and cookie?


The difference between session and a cookie is two-fold.


1) session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. There is no way to disable sessions from the client browser.


2) session and cookies differ in type and amount of information they are capable of storing. Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. Javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects.

81) How to determine the client browser version?


Another name for "browser" is "user agent." You can read the User-Agent header using request.getUserAgent() or request.getHeader("User-Agent")

Friday, December 5, 2008

JSP Interview Question and Answer

JSP-JAVA SERVER PAGES(72 question and answer)

1) What is JSP page?

A JSP page is a text-based document that contains two types of text: static template data, which can be expressed in any text-based format such as HTML, SVG, WML, and XML, and JSP elements, which construct dynamic content.

JSP is a dynamic scripting capability for web pages that allows Java as well as a few special tags to be embedded into a web file (HTML/XML, etc). The suffix ends with .jsp to indicate to the web server that the file is a JSP files. JSP is a server side technology - you can't do any client side validation with it.

JSP (java server pages ) is an extension of java programming technology. This is to add server side programming functionalities to java

The advantages are:

a) The JSP assists in making the HTML more functional. Servlets on the other hand allow outputting of HTML but it is a tedious process.

b) It is easy to make a change and then let the JSP capability of the web server you are using deal with compiling it into a servlet and running it.

2) What are JSP scripting elements?

JSP scripting elements let’s to insert Java code into the servlet that will be generated from the current JSP page.

There are three forms:

a) Expressions of the form <%= expression %> that are evaluated and inserted into the output,

b) Scriptlets of the form <% code %> that are inserted into the servlet's service method,

c) Declarations of the form <%! Code %> that are inserted into the body of the servlet class, outside of any existing methods.

3) What are JSP Directives?

A JSP directive affects the overall structure of the servlet class. It usually has the following form:

<%@ directive attribute="value" %>

However, you can also combine multiple attribute settings for a single directive, as follows:

<%@ directive attribute1="value1"

attribute 2="value2"

...

attributeN ="valueN" %>

There are two main types of directive: page, which lets to do things like import classes, customize the servlet superclass, and the like; and include, which lets to insert a file into the servlet class at the time the JSP file is translated into a servlet

4) What are predefined variables or implicit objects?

Implicit objects are created by the web container and contain information related to a particular request, page, or application. They are request, response, pageContext, session, and application, out, config, page and exception.

5) What are JSP ACTIONS?

JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.

Available actions include:

? jsp:include - Include a file at the time the page is requested.

? jsp:useBean - Find or instantiate a JavaBean.

? jsp:setProperty - Set the property of a JavaBean.

? jsp:getProperty - Insert the property of a JavaBean into the output.

? jsp:forward - Forward the requester to a newpage.

? Jsp: plugin - Generate browser-specific code that makes an OBJECT or EMBED

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

(1) Request Lifetime: Using this technique to pass beans, a request dispatcher (using either "include" or forward") can be called. This bean will disappear after processing this request has been completed.

Servlet:

request.setAttribute("theBean", myBean);

RequestDispatcher rd = getServletContext().getRequestDispatcher("thepage.jsp");

rd.forward(request, response);

JSP PAGE:

(2) Session Lifetime: Using this technique to pass beans that are relevant to a particular session (such as in individual user login) over a number of requests. This bean will disappear when the session is invalidated or it times out, or when you remove it.

Servlet:

HttpSession session = request.getSession(true);

session.putValue("theBean", myBean);

/* You can do a request dispatcher here,

or just let the bean be visible on the

next request */

JSP Page:

(3) Application Lifetime: Using this technique to pass beans that are relevant to all servlets and JSP pages in a particular app, for all users. For example, I use this to make a JDBC connection pool object available to the various servlets and JSP pages in my apps. This bean will disappear when the servlet engine is shut down, or when you remove it.

Servlet:

GetServletContext(). setAttribute("theBean", myBean);

JSP PAGE:

7) How can I set a cookie in JSP?

response.setHeader("Set-Cookie", "cookie string");

To give the response-object to a bean, write a method setResponse

(HttpServletResponse response)

- to the bean, and in jsp-file:

<%

bean.setResponse (response);

%>

8) How can I delete a cookie with JSP?

Say that I have a cookie called "foo," that I set a while ago & I want it to go away. I simply:

<%

Cookie killCookie = new Cookie("foo", null);

KillCookie.setPath("/");

killCookie.setMaxAge(0);

response.addCookie(killCookie);

%>

9) How are Servlets and JSP Pages related?

JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.

10) How many JSP scripting elements and what are they?

There are three scripting language elements: declarations, scriptlets, and expressions.

11) Why are JSP pages the preferred API for creating a web-based client program?

Because no plug-ins or security policy files are needed on the client systems(applet does). Also, JSP pages enable cleaner and more module application design because they provide a way to separate applications programming from web page design. This means personnel involved in web page design do not need to understand Java programming language syntax to do their jobs.

12) What do you understand by JSP Actions?


JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

-------------------------------------------------------------------------------------------

13). What is the difference between and
<%@ include file = ... >
?.
Answer: Both the tag includes the information from one page in another. The differences are as follows:
: This is like a function call from one jsp to another jsp. It is executed ( the included page is executed and the generated html content is included in the content of calling jsp) each time the client page is accessed by the client. This approach is useful to for modularizing the web application. If the included file changed then the new content will be included in the output.

<%@ include file = ... >: In this case the content of the included file is textually embedded in the page that have <%@ include file=".."> directive. In this case in the included file changes, the changed content will not included in the output. This approach is used when the code from one jsp file required to include in multiple jsp files.

14). What is the difference between and
response.sendRedirect(url),?.
The element forwards the request object containing the client request information from one JSP file to another file. The target file can be an HTML file, another JSP file, or a servlet, as long as it is in the same application context as the forwarding JSP file.
sendRedirect sends HTTP temporary redirect response to the browser, and browser creates a new request to go the redirected page. The response.sendRedirect kills the session variables.

15). Identify the advantages of JSP over Servlet.

a) Embedding of Java code in HTML pages
b) Platform independence
c) Creation of database-driven Web applications
d) Server-side programming capabilities

Answer :- Embedding of Java code in HTML pages

16) What are implicit Objects available to the JSP Page?
Implicit objects are the objects available to the JSP page. These objects are created by Web container and contain information related to a particular request, page, or application.

Certain objects that are available for the use in JSP documents without being declared first. These objects are parsed by the JSP engine and inserted into the generated servlet.

The JSP implicit objects are:

Variable

Class

Description

application

javax.servlet.ServletContext

The context for the JSP page's servlet and any Web components contained in the same application.

config

javax.servlet.ServletConfig

Initialization information for the JSP page's servlet.

exception

java.lang.Throwable

Accessible only from an error page.

out

javax.servlet.jsp.JspWriter

The output stream.

page

java.lang.Object

The instance of the JSP page's servlet processing the current request. Not typically used by JSP page authors.

pageContext

javax.servlet.jsp.PageContext

The context for the JSP page. Provides a single API to manage the various scoped attributes.

request

Subtype of javax.servlet.ServletRequest

The request triggering the execution of the JSP page.

response

Subtype of javax.servlet.ServletResponse

The response to be returned to the client. Not typically used by JSP page authors.

session

javax.servlet.http.HttpSession

The session object for the client.

-------------------------------------------------------------------------------------------

17)What are all the different scope values for the tag?
tag is used to use any java object in the jsp page. Here are the scope values for tag:
a) page
b) request
c) session and
d) application

18) What is expression in JSP?
Expression tag is used to insert Java values directly into the output. Syntax for the Expression tag is:
<%= expression %>
An expression tag contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. The following expression tag displays time on the output:
<%=new java.util.Date()%>
--------------------------------------------------------------------------------------------

19) What types of comments are available in the JSP?
There are two types of comments are allowed in the JSP. These are hidden and output comments. A hidden comments does not appear in the generated output in the html, while output comments appear in the generated output.
Example of hidden comment:
<%-- This is hidden comment --%>
Example of output comment:

--------------------------------------------------------------------------------------------

20) What is JSP declaration?
JSP Decleratives are the JSP tag used to declare variables. Declaratives are enclosed in the <%! %> tag and ends in semi-colon. You declare variables and functions in the declaration tag and can use anywhere in the JSP. Here is the example of declaratives:

<%@page contentType="text/html" %>

<%!
int cnt=0;
private int getCount(){
//increment cnt and return the value
cnt++;
return cnt;
}
%>

Values of Cnt are:

<%=getCount()%>


--------------------------------------------------------------------------------------------

21) What is JSP Scriptlet?
JSP Scriptlet is jsp tag which is used to enclose java code in the JSP pages. Scriptlets begins with <% tag and ends with %> tag. Java code written inside scriptlet executes every time the JSP is invoked.
Example:
<%
//java codes
String userName=null;
userName=request.getParameter("userName");
%>
--------------------------------------------------------------------------------------------

22.) What are the life-cycle methods of JSP?

Life-cycle methods of the JSP are:
a) jspInit(): The container calls the jspInit() to initialize the servlet instance. It is called before any other method, and is called only once for a servlet instance.
b)_jspService(): The container calls the _jspservice() for each request and it passes the request and the response objects. _jspService() method cann't be overridden.
c) jspDestroy(): The container calls this when its instance is about to destroyed.
The jspInit() and jspDestroy() methods can be overridden within a JSP page.

--------------------------------------------------------------------------------------------

23) What is a JSP Custom tag?


JSP Custom tags are user defined JSP language element. JSP custom tags are user defined tags that can encapsulate common functionality. For example you can write your own tag to access the database and performing database operations. You can also write custom tag for encapsulate both simple and complex behaviors in an easy to use syntax and greatly simplify the readability of JSP pages.

24) What is the role of JSP in MVC Model?
JSP is mostly used to develop the user interface, It plays the role of View in the MVC Model.

--------------------------------------------------------------------------------------------

25) What do you understand by context initialization parameters?
The context-param element contains the declaration of a web application's servlet context initialization parameters.

name
value

The Context Parameters page lets you manage parameters that are accessed through the ServletContext.getInitParameterNames and ServletContext.getInitParameter methods.

--------------------------------------------------------------------------------------------

26) Can you extend JSP technology?
JSP technology lets the programmer to extend the jsp to make the programming more easier. JSP can be extended and custom actions and tag libraries can be developed.

--------------------------------------------------------------------------------------------

27) What do you understand by JSP translation?
JSP translators generate standard Java code for a JSP page implementation class. This class is essentially a servlet class wrapped with features for JSP functionality.

--------------------------------------------------------------------------------------------

28) What you can stop the browser to cash your page?
Instead of deleting a cache, you can force the browser not to catch the page.
<%
response.setHeader("pragma","no-cache");//HTTP 1.1
response.setHeader("Cache-Control","no-cache");
response.setHeader("Cache-Control","no-store");
response.addDateHeader("Expires", -1);
response.setDateHeader("max-age", 0);
//response.setIntHeader ("Expires", -1); //prevents caching at the proxy server
response.addHeader("cache-Control", "private");

%>
put the above code in your page
.

--------------------------------------------------------------------------------------------

29) What you will handle the runtime exception in your jsp page?
The errorPage attribute of the page directive can be used to catch run-time exceptions automatically and then forwarded to an error processing page.

For example:
<%@ page errorPage="customerror.jsp" %>
above code forwards the request to "customerror.jsp" page if an uncaught exception is encountered during request processing. Within "customerror.jsp", you must indicate that it is an error-processing page, via the directive: <%@ page isErrorPage="true" %>.

30) What are the lifecycle phases of a JSP?
JSP page looks like a HTML page but is a servlet. When presented with JSP page the JSP engine does the following 7 phases.

1. Page translation: -page is parsed, and a java file which is a servlet is created.

2. Page compilation: page is compiled into a class file

3. Page loading : This class file is loaded.

4. Create an instance :- Instance of servlet is created

5. jspInit() method is called

6. _jspService is called to handle service calls

7. _jspDestroy is called to destroy it when the servlet is not required.

31) What is a translation unit?

JSP page can include the contents of other HTML pages or other JSP files. This is done by using the include directive. When the JSP engine is presented with such a JSP page it is converted to one servlet class and this is called a translation unit, Things to remember in a translation unit is that page directives affect the whole unit, one variable declaration cannot occur in the same unit more than once, the standard action jsp:useBean cannot declare the same bean twice in one unit.

32) What are context initialization parameters?

Context initialization parameters are specified by the in the web.xml file, these are initialization parameter for the whole application and not specific to any servlet or JSP.

33) What is a output comment?

A comment that is sent to the client in the viewable page source. The JSP engine handles an output comment as un-interpreted HTML text, returning the comment in the HTML output sent to the client. You can see the comment by viewing the page source from your Web browser.

34) What is a Hidden Comment?

A comment that documents the JSP page but is not sent to the client. The JSP engine ignores a hidden comment, and does not process any code within hidden comment tags. A hidden comment is not sent to the client, either in the displayed JSP page or the HTML page source. The hidden comment is useful when you want to hide or “comment out” part of your JSP page.

35) What is a Expression?

Expressions are act as placeholders for language expression; expression is evaluated each time the page is accessed

36) What’s the difference between forward and sendRedirect?

When you invoke a forward request, the request is sent to another resource on the server, without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container And then returns to the calling method. When a sendRedirect method is invoked, it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.

37) What is difference between custom JSP tags and beans?

Custom JSP tag is a tag you defined. You define how a tag, its attributes and its body are interpreted, and then group your tags into collections called tag libraries that can be used in any number of JSP files. Custom tags and beans accomplish the same goals — encapsulating complex behavior into simple and accessible forms. There are several differences:

· Custom tags can manipulate JSP content; beans cannot.

· Complex operations can be reduced to a significantly simpler form with custom tags than with beans.

· Custom tags require quite a bit more work to set up than do beans.

· Custom tags usually define relatively self-contained behavior, whereas beans are often defined in one servlet and used in a different servlet or JSP page.

· Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.

38) What is the difference b/w variable declared inside a declaration part and variable declared in scriplet part?

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

39) Is there a way to execute a JSP from the comandline or from my own application?

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

40) What is the difference between getAttribute and getParameter()?

getParameter() is used to get form field values. it will take form field name as argument, it is totally client side and returns. String.getAttribute() is used to get object value, which is set by setAttribute(),this method will take object key as arguments,

41) What is the difference between application server and web server?

42) what are the advantage of JSP?

1) Auto compilation(translation.....)2) Not deployment descritpor specific3)Multiple deployment is avoided

43) How to perform redirect action without using response.sendRedirect (“”)?

By using the requestdispatcher.dispatch() method we can redirect to another page

44) what is the difference scriptlet and expression?

Scriptelet are used to write the code in any language but that language is mentioned in page language attribute.

45) Can we implement interface or extends class in JSP?

We cannot implement an interface in a jsp but we can extend a class in JSP by using extends attribute of the page directive.extends="package.class".

46) What is the default scope of jsp ?

Page is the default scope of jsp .

47) What is the difference between session and cookies?

Session are used as server side means for session tracking whereas cookies are used as client side means of sesion tracking. There can be only 20 cookies per server. Size of each cookie is 4k

48). Why should we use setContentType in Servlet?

To tell the browser what type of output posted from server.

49) What is the difference between static include and dynamic include?

50) How to refresh jsp page?

response.setHeader("refresh","2");

51) Which element enables JSP to integrate with JavaBeans?

A) Scriptlets.

B) Directives.

C) Declarations.

D) Actions.

Ans: D)

52) Can a interface be implemented in a jsp file?

A) Yes.

B) No.

C) Only when static pages are included.

D) Only when dynamic pages are included.

Ans: B)

53) What is a Scriplet?

Scriptlet can contain any number of language statements, variable or method declarations, or expressions that are valid in the page scripting language.

54) What is the purpose of Jsp forward method?

This method will forward the control to another resource available in the same web application on the same container.

55) Briefly explain about Java Server Pages technology?

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

56) Why do I need JSP technology if I already have servlets?


JSP pages are compiled into servlets, so theoretically you could write servlets to support your web-based applications. However, JSP technology was designed to simplify the process of creating pages by separating web presentation from web content. In many applications, the response sent to the client is a combination of template data and dynamically-generated data. In this situation, it is much easier to work with JSP pages than to do everything with servlets.

58) How are the JSP requests handled?


The following sequence of events happens on arrival of jsp request:
a. Browser requests a page with .jsp file extension in webserver.
b. Webserver reads the request.
c. Using jsp compiler,webserver converts the jsp into a servlet class that implement the javax.servletjsp.jsp page interface. the jsp file compiles only when the page is first requested or when the jsp file has been changed.
d. The generated jsp page servlet class is invoked to handle the browser request.
e. The response is sent to the client by the generated servlet.
-----------------------------------------------------------------------------------

59) What are the advantages of JSP?


The following are the advantages of using JSP:


a. JSP pages easily combine static templates, including HTML or XML fragments, with code that generates dynamic content.
b. JSP pages are compiled dynamically into servlets when requested, so page authors can easily make updates to presentation code. JSP pages can also be precompiled if desired.
c. JSP tags for invoking JavaBeans components manage these components completely, shielding the page author from the complexity of application logic.
d. Developers can offer customized JSP tag libraries that page authors access using an XML-like syntax.
e. Web authors can change and edit the fixed template portions of pages without affecting the application logic. Similarly, developers can make logic changes at the component level without editing the individual pages that use the logic.

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

61) What are Directives?

Directives are instructions that are processed by the JSP engine when the page is compiled to a servlet. Directives are used to set page-level instructions, insert data from external files, and specify custom tag libraries. Directives are defined between < %@ and % >.
< %@ page language=="java" imports=="java.util.*" % >
< %@ include file=="banner.html" % >

62) What are the different types of directives available in JSP?

The following are the different types of directives:
a. include directive : used to include a file and merges the content of the file with the current page
b. page directive : used to define page specific attributes like scripting language, error page, buffer, thread safety, etc
c. taglib : used to declare a custom tag library which is used in the page.

63) What are JSP actions?

JSP actions are executed when a JSP page is requested. Action are inserted in the jsp page using XML syntax to control the behavior of the servlet engine. Using action, we can dynamically insert a file, reuse bean components, forward the user to another page, or generate HTML for the Java plugin. Some of the available actions are as follows:
- include a file at the time the page is requested.
- find or instantiate a JavaBean.
- set the property of a JavaBean.
- insert the property of a JavaBean into the output.
- forward the requester to a new page.
- generate browser-specific code that makes an OBJECT or EMBED tag for the Java plugin.

-----------------------------------------------------------------------------------

64) What are Scriptlets?

Scriptlets are blocks of programming language code (usually java) embedded within a JSP page. Scriptlet code is inserted into the servlet generated from the page. Scriptlet code is defined between <% and %>

65) What are Decalarations?

Declarations are similar to variable declarations in Java.Variables are defined for subsequent use in expressions or scriptlets. Declarations are defined between <%! and %>.
< %! int i=0; %>

66) How to declare instance or global variables in jsp?

Instance variables should be declared inside the declaration part. The variables declared with JSP declaration element will be shared by all requests to the jsp page.
< %@ page language=="java" contentType="text/html"% >
< %! int i=0; %>

67) What are Expressions?

Expressions are variables or constants that are inserted into the data returned by the web server. Expressions are defined between <% = and % >
< %= scorer.getScore() %>


14) What is meant by implicit objects? And what are they?


Ans : Implicit objects are those objects which are avaiable by default. These objects are instances of classesdefined by the JSP specification. These objects could be used within the jsp page without being declared.

The following are the implicit jsp objects:
1. application
2. page
3. request
4. response
5. session
6. exception
7. out
8. config
9. pageContext

68) How do I use JavaBeans components (beans) from a JSP page?
The JSP specification includes standard tags for bean use and manipulation. The tag creates an instance of a specific JavaBean class. If the instance already exists, it is retrieved. Otherwise, a new instance of the bean is created. The and tags let you manipulate properties of a specific bean.

69) What is the difference between and %@include:?

Both are used to insert files into a JSP page.
<%@include:> is a directive which statically inserts the file at the time the JSP page is translated into a servlet.
is an action which dynamically inserts the file at the time the page is requested.
-----------------------------------------------------------------------------------

70) What is the difference between forward and sendRedirect?
Both requestDispatcher.forward() and response.sendRedirect() is used to redirect to new url.

forward is an internal redirection of user request within the web container to a new URL without the knowledge of the user(browser). The request object and the http headers remain intact.

sendRedirect is normally an external redirection of user request outside the web container. sendRedirect sends response header back to the browser with the new URL. The browser send the request to the new URL with fresh http headers. sendRedirect is slower than forward because it involves extra server call.
-----------------------------------------------------------------------------------

71) Can I create XML pages using JSP technology?

Yes, the JSP specification does support creation of XML documents. For simple XML generation, the XML tags may be included as static template portions of the JSP page. Dynamic generation of XML tags occurs through bean components or custom tags that generate XML output.

72) How is Java Server Pages different from Active Server Pages?

JSP is a community driven specification whereas ASP is a similar proprietary technology from Microsoft. In JSP, the dynamic part is written in Java, not Visual Basic or other MS-specific language. JSP is portable to other operating systems and non-Microsoft Web servers whereas it is not possible with ASP