83. What are the differences between SAX and DOM parser.

SAX DOM
Both SAX and DOM are used to parse the XML document. Both has advantages and disadvantages and can be used in our programming depending on the situation.
Parses node by node Stores the entire XML document into memory before processing
Doesn’t store the XML in memory Occupies more memory
We cant insert or delete a node We can insert or delete nodes
Top to bottom traversing Traverse in any direction.
SAX is an event based parser DOM is a tree model parser
SAX is a Simple API for XML Document Object Model (DOM) API
import javax.xml.parsers.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
 
doesn’t preserve comments preserves comments
SAX generally runs a little faster than DOM SAX generally runs a little faster than DOM
If we need to find a node and doesn’t need to insert or delete we can go with SAX itself otherwise DOM provided we have more memory.

82. Describe the differences between XML and HTML

XML HTML

User definable tags

Defined set of tags designed for web display

Content driven

Format driven

End tags required for well formed documents

End tags not required

Quotes required around attributes values

Quotes not required

Slash required in empty tags

Slash not required

81. How you will make available any message resources definations file to the struts famework environment.

Message Resources Definitions file are simple .properties files and these files contains the messages that can be used in the struts project. Message Resources Definitions files can be added to the struts-config.xml file through <message-resources /> tag.
Example:
<message-resources parameter=”MessageResources” />

80. What is Jakarta Struts FrameWork

Jakarta Struts is open source implementation of MVC (Model-View-Controller) pattern for the development of web based applications. Jakarta Struts is robust architecture and can be used for the development of application of any size. Struts framework makes it much easier to design scalable, reliable Web applications with Java.

79. What are the core classes of the Struts Frame Work

Core classes of Struts Framework are ActionForm, Action, ActionMapping, ActionForward, ActionServlet etc.

78. What are the components of Struts

Struts is based on the MVC design pattern. Struts components can be categories into Model, View and Controller.

Model: Components like business logic / business processes and data are the part of Model.

View: JSP, HTML etc. are part of View

Controller: Action Servlet of Struts is part of Controller components which works as front controller to handle all the requests.

77. What are differences between <bean:message> and <bean:write>

<bean:message>: This tag is used to output locale-specific text (from the properties files) from a MessageResources bundle. 

<bean:message key=”label.search.name”/>

<bean:write>: This tag is used to output property values from a bean. <bean:write> is a commonly used tag which enables the programmers to easily present the data.

<bean:write name=”student” property=”age”/>

76. What is LookupDispatchAction

An abstract Action that dispatches to the subclass mapped execute method. This is useful in cases where an HTML form has multiple submit buttons with the same name. The button name is specified by the parameter property of the corresponding ActionMapping.

(Ref. http://struts.apache.org/1.2.7/api/org/apache/struts/actions/LookupDispatchAction.html).

75. What is struts flow

Struts Flow is a port of Cocoon’s Control Flow to Struts to allow complex workflow, like multi-form wizards, to be easily implemented using continuations-capable JavaScript. It provides the ability to describe the order of Web pages that have to be sent to the client, at any given point in time in an application.

The code is based on a proof-of-concept Dave Johnson put together to show how the Control Flow could be extracted from Cocoon. (Ref: http://struts.sourceforge.net/struts-flow/index.html )

74. How to handle exceptions in struts

In Struts you can handle the exceptions in two ways:
a) Declarative Exception Handling: You can either define global exception handling tags in your struts-config.xml or define the exception handling tags within <action>..</action> tag.
Example:

<exception   key=”database.error.duplicate”
                    path=”/UserExists.jsp”
                    type=”mybank.account.DuplicateUserException”/>

b) Programmatic Exception Handling: Here you can use try{}catch{} block to handle the exception.

73. What is the Action Errors and Action Message?

ActionMessage: A class that encapsulates messages. Messages can be either global or they are specific to a particular bean property.
Each individual message is described by an ActionMessage object, which contains a message key (to be looked up in an appropriate message resources database), and up to four placeholder arguments used for parametric substitution in the resulting message.

data.ok=Data saved successfully

ActionMessages messages = new ActionMessages();
ActionMessage msg = new ActionMessage(“data.ok”);
messages.add(“message1”, msg);

<html:messages id=”msgId” message=”true” property=”message1″>
       <bean:write name=”msgId”/><br>
</html:messages>

msg = new ActionMessage(“data.do”, “stop”);
messages.add(“message2”, msg);

In property file data.do configured as below
data.do=Please {0}

ActionErrors: A class that encapsulates the error messages being reported by the validate() method of an ActionForm. Validation errors are either global to the entire ActionForm bean they are associated with, or they are specific to a particular bean property (and, therefore, a particular input field on the corresponding form).

error.name.required=Please enter the name
ActionErrors errors = new ActionErrors();
errors.add(“name”,new ActionMessage(“error.name.required”));

72. How to setup struts to use multiple configuration files.

Struts can use multiple configuration files. Here is the configuration example:
<servlet>
        <servlet-name>banking</servlet-name>
        <servlet-class>org.apache.struts.action.ActionServlet
        </servlet-class>
        <init-param>
        <param-name>config</param-name>
        <param-value>/WEB-INF/struts-config.xml,
                /WEB-INF/struts-authentication.xml,
                /WEB-INF/struts-help.xml
           </param-value>
    </init-param>

71. What we will define in struts-config.xml file.

The main control file in the Struts framework is the struts-config.xml XML file, where action mappings are specified.

This file’s structure is described by the struts-config DTD file, which is defined at http://jakarta.apache.org/struts/. A copy of the DTD can be found on the /docs/dtds subdirectory of the framework’s installation root directory. The top-level element is struts-config.

Basically, it consists of the following elements:
data-sources—A set of data-source elements, describing parameters needed to instantiate JDBC 2.0 Standard Extension DataSource objects

<data-sources>
      <data-source    autoCommit=”false”
                              description=”Second Database Config”
                              driverClass=”oracle.jdbc.driver.OracleDriver”
                               key=”REFDB”
                               maxCount=”4″ 
                               minCount=”2″
                               password=”admin”
                               url=”jdbc:oracle:thin:@localhost:1521/AUTHORDB”
                               user=”admin”
        />
</data-sources>

form-beans—A set of form-bean elements that describe the form beans that this application uses

<form-beans>
         <form-bean name=”searchForm”>
                            type=”com.abc.struts.SearchForm”
        </form-bean>
</form-beans>

global-forwards—A set of forward elements describing general available forward URIs

<global-forwards>
          <forward name=”search” path=”/search.jsp” />
</global-forwards>

 
action-mappings—A set of action elements describing a request-to-action mapping

<action-mapping>
         <action path=”/search”
                     type=”com.abc.struts.SearchAction”
                     name=”searchForm”
                     scope=”request”
                     validate=”true”
                     input=”/search.jsp”>
          <forward name=”results” path=”/results.jsp” />
         </action>
</action-mapping>

70. What is the request processor in struts and how it works

The RequestProcessor Class is the actual place where the request processing takes place in a Struts controller environment.

When the request object first reaches the actionservlet class then it invokes the process method of the underlying RequestProcessor Class.

This process method then looks into the struts-config.xml file and tries to locate the name of the action that has come with the request.Once it identifies the action in the xml file it continues the rest of the steps needed for request processing.

processor has most of the following responsibilities:

  1. Determine path,
  2. Handle Locale,
  3. Process content and encoding type,
  4. Process cache headers
  5. Pre Processing hook
  6. Pre-processing hook,
  7. Determine mapping,
  8. Determine roles,
  9. Process and validate actionForm,
  10. Return a response

It is one instance per application module; it invokes proper Action instance

Of course processes all requests for a module.

69. What is struts actions and action mappings.

A Struts action is an instance of a subclass of an Action class, which implements a portion of a Web application and whose perform or execute method returns a forward.

An action can perform tasks such as validating a user name and password.

An action mapping is a configuration file entry that, in general, associates an action name with an action. An action mapping can contain a reference to a form bean that the action can use, and can additionally define a list of local forwards that is visible only to this action.

An action servlet is a servlet that is started by the servlet container of a Web server to process a request that invokes an action. The servlet receives a forward from the action and asks the servlet container to pass the request to the forward’s URL.

An action servlet must be an instance of an org.apache.struts.action.ActionServlet class or of a subclass of that class. An action servlet is the primary component of the controller.

68. What are the various struts tag libraries.

Struts is very rich framework and it provides very good and user friendly way to develop web application forms. Struts provide many tag libraries to ease the development of web applications. These tag libraries are:

  1. Bean tag library – Tags for accessing JavaBeans and their properties.
  2. HTML tag library – Tags to output standard HTML, including forms, text boxes, checkboxes, radio buttons etc..
  3. Logic tag library – Tags for generating conditional output, iteration capabilities and flow management
  4. Tiles or Template tag library – For the application using tiles
  5. Nested tag library – For using the nested beans in the application

67. What is the difference between perform() and execute()

  • Perform method is the method which was deprecated in the Struts Version 1.1. 
  • In Struts 1.x, Action.perform() is the method called by the ActionServlet. This is typically where your business logic resides, or at least the flow control to your JavaBeans and EJBs that handle your business logic.
  • As we already mentioned, to support declarative exception handling, the method signature changed in perform.
  • Now execute just throws Exception. Action.perform() is now deprecated;
  • however, the Struts v1.1 ActionServlet is smart enough to know whether or not it should call perform or execute in the Action, depending on which one is available.

66.How to enable front-end validation based on the xml in validation.xml

The <html:javascript> tag to allow front-end validation based on the xml in validation.xml.

For  example the code:

<html:javascript  formName=”logonForm”
                         dynamicJavascript=”true”
                         staticJavascript=”true”  />

 generates the client side java script for the form “logonForm” as defined in the  validation.xml file.

The <html:javascript> when added in the jsp file generates the client site validation script.

Following tag displays all the errors:
<html:errors/>

65. What is the Struts Validator Framework

Struts Framework provides the functionality to validate the form data.

It can be use to validate the data on the users browser as well as on the server side.

Struts Framework emits the java scripts and it can be used validate the form data on the client browser.

Server side validation of form can be accomplished by sub classing your From Bean with DynaValidatorForm class.

Following are the core components of this framework:

  1. Validators
  2. Configuration Files
  3. Resource Files/Bundles
  4. JSP Custom Tags
  5. Validator Form Classes

The Validator Framework uses two XML configuration files validator-rules.xml and validation.xml. The validator-rules.xml defines the standard validation routines, these are reusable and used in validation.xml. to define the form specific validations. The validation.xml defines the validations applied to a form bean.

The Validator framework was developed by David Winterfeldt as third-party add-on to Struts. Now the Validator framework is a part of Jakarta Commons project and it can be used with or without Struts. The Validator framework comes integrated with the Struts Framework and can be used without doing any extra settings.

64. What is Action Class

  • The Action is part of the controller. The purpose of Action Class is to translate the HttpServletRequest to the business logic.
  • To use the Action, we need to  Subclass and overwrite the execute()  method.
  • The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method.
  • There should be no database interactions in the action.
  • The action should receive the request, call business objects (which then handle database, or interface with J2EE, etc) and then determine where to go next.
  • Even better, the business objects could be handed to the action at runtime (IoC style) thus removing any dependencies on the model.  
  • The return type of the execute method is ActionForward which is used by the Struts
  • Framework to forward the request to the file as per the value of the returned ActionForward object.

63. Explain ActionFrom Class and its life cycle.

An ActionForm is a java bean that extends org.apache.struts.action.ActionForm, ActionForm maintain the session state of web application.

All data submitted by the user are sent corresponding ActionForm 

ActionForm class is used to capture user-input data from an HTML form and transfer it to the Action Class. ActionForm plays the role of Transport Vehicle between the presentation Tire & Business Tier.
Life Cycle :
1. Request received by Controller
2. Create or recycle ActionForm
3. Call reset()
4. store ActionForm in proper scope
5. populate ActionForm from Request
6. Validate the ActionForm
7. If errors found then forward back to input attribute page(configured in Action mapping in struts-config.xml) with ActionForm in scope. If no errors found then call execute() with the ActionForm.

62. What are new features of Struts 1.1

The new features added to Struts 1.1 are

1. RequestProcessor class
2. Method perform() replaced by execute() in Struts base Action Class
3. Changes to web.xml and struts-config.xml
4.Declarative exception handling
5.Dynamic ActionForms
6.Plug-ins
7.Multiple Application Modules
8.Nested Tags
9.The Struts Validator
10.Change to the ORO package
11.Change to Commons logging
12.Removal of Admin actions
13. Deprecation of the GenericDataSource.

61. What is a Action Servlet

public class ActionServlet

extends javax.servlet.http.HttpServlet

  1. ActionServlet provides the “controller” in the Model-View-Controller (MVC) design pattern for web applications that is commonly known as “Model 2”.
  2. The class org.apache.struts.action.ActionServlet is the called the ActionServlet.
  3. In the the Jakarta Struts Framework this class plays the role of controller.
  4. All the requests to the server goes through the controller.
  5. Controller is responsible for handling all the requests.

60. What is the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE

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

 

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

59. 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”);

58. 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();

}

}

57. How can you load the driver.

Driver can be loaded in 2 ways :

1. class.forName(“sun.jdbc.odbc.JdbcOdbc”);

2. Driver d=new Driver(“sun.jdbc.odbc.JdbcOdbc”);

   DriverManager.registerDriver(d);

vendar specific one: Driver d=new oracle.driver.oracleDriver();

56. How can you retrieve data from the ResultSet

Example:

Statement stmt = conn.createStatement(); 
ResultSet rs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES”); 
while (rs .next() ) 

//Iam assuming there are 3 columns in the table. 
System.out.println ( rs.getString(1)); 
System.out.println(rs.getString(2)); 
System.out.println(rs.getString(3)); 

//don’t forget to close the resultset, statement & connection 
rs.close(); //First  
stmt.close(); //Second 
con.close(); //Last  
System.out.println(“You are done”); 

55. How do you implement Connection Pooling

Connection Pooling can be implemented by the following way. 

  1.  A javax.sql.ConnectionPoolDataSource interface that serves as a resource manager connection factory for pooled java.sql.Connection objects. Each database vendors provide the implementation for that interface. 
    1. For example, the oracle vendors implementation is as follows: oracle.jdbc.pool.oracleConnectionPoolDataSource Class. 
  2. A javax.sql.PooledConnection interface encapsulates the physical connection for the database. Again, the vendor provides the implementation.

Code for connecting the connection pooling

InitalContext ic=new InitialContext();

Hashtable ht=new Hashtable();

ht.put(“Context.INITIAL_PROVIDER”,weblogic.jndi.InitialCla)

//u have to set weblogic properties first and the jndi name that u r defining in 

//weblogic while creating the connectionpool

ht.put(“Context.PROVIDER_URL”,t3://localhost:7001);

ht.put(“Context.SECURITY_PRINCIPAL”,username);

ht.put(“Context.SECURITY_CREDENTIALS”,passwordof weblogic);

DataSource ds=(DataSource)ic.lookup(“jndiname”);

Connection con=ds.getConnection();

Statement stmt=con.createStatement();

54. How to call a stored procedure from JDBC

Stored Procedures can be called in java by using the prepareCall() method which returns a CallableStatement object.

CallableStatement cs = con.prepareCall(“{call Procedure_name}”);

ResultSet rs = cs.executeQuery();

53. What are the three statements in JDBC & difference between them.

1.Statement which is used to run simple sql statements like select and update 
2. PrepareStatment is used to run Pre compiled sql.  
3. CallableStatement is used to execute the stored procedures.

52. What is the difference between ResultSet and RowSet

A ResultSet maintains a connection to a database and because of that it can’t be serialized and also we cant pass the Resultset object from one class to other class across the network.

RowSet is a disconnected, serializable version of a JDBC ResultSet and also the RowSet extends the ResultSet interface so it has all the methods of ResultSet. The RowSet can be serialized because it doesn’t have a connection to any database and also it can be sent from one class to another across the network.

More on RowSet:

A RowSet can be * connected * or *disconnected* 
A *disconnected* rowset gets a connection to a data source in order to fill itself with data or to propagate changes in data back to the data source, but most of the time it does not have a connection open. While it is disconnected, it does not need a JDBC driver or the full JDBC API, so its footprint is very small. Thus a rowset is an ideal format for sending data over a network to a thin client.  
A connected RowSet is like a wrapper around the ResultSet. 
Implementation: 
A CachedRowSet class—a disconnected rowset that caches its data in memory; not suitable for very large data sets, but an ideal way to provide thin Java clients, such as a Personal Digital Assistant (PDA) or Network Computer (NC), with tabular data  
A JDBCRowSet class—a connected rowset that serves mainly as a thin wrapper around a ResultSet object to make a JDBC driver look like a JavaBeans component  
A WebRowSet class—a connected rowset that uses the HTTP protocol internally to talk to a Java servlet that provides data access; used to make it possible for thin web clients to retrieve and possibly update a set of rows

51. What is a transaction.

To emulate a business transaction, a program may need to perform several steps. A financial program, for example, might transfer funds from a checking account to a savings account with the steps listed in the following pseudocode:

begin transaction 
   debit checking account 
   credit savings account
   update history log 
commit transaction
 

Either all three of these steps must complete, or none of them at all.

Otherwise, data integrity is lost. Because the steps within a transaction are a unified whole, a transaction is often defined as an indivisible unit of work.

  • A transaction can end in two ways: with a commit or a rollback.
  • When a transaction commits, the data modifications made by its statements are saved.
  • If a statement within a transaction fails, the transaction rolls back, undoing the effects of all statements in the transaction.
  • In the pseudocode, for example, if a disk drive crashed during the credit step, the transaction would roll back and undo the data modifications made by the debit statement. Although the transaction failed, data integrity would be intact because the accounts still balance.
  • In the preceding pseudocode, the begin and commit statements mark the boundaries of the transaction.

Transaction mainly consist of ACID. A-Atomicity, C- Consistency, I – Integrity, D- Durability. If a process consist of acid successfully then we can say that the transaction is successful.

50. What is the purpose of setAutoCommit()

Autocommit behavior    The JDBC specification requires that, by default, a COMMIT is performed after each data modification statement. Currently, the server-side JDBC behavior is to commit. You can control this behavior using a statement such as the following:

  • conn.setAutoCommit( false ) ;

    where conn is the current connection object.

  • Connection defaults    From server-side JDBC, only the first call to getConnection( “jdbc:default:connection” ) creates a new connection with the default values. Subsequent calls return a wrapper of the current connection with all connection properties unchanged. If you set AutoCommit to OFF in your initial connection, any subsequent getConnection calls within the same Java code return a connection with AutoCommit set to OFF.

    You may wish to ensure that closing a connection resets the connection properties to their default values, so that subsequent connections are obtained with standard JDBC values. The following type of code achieves this:

    Connection conn = DriverManager.getConnection("");
    boolean oldAutoCommit = conn.getAutoCommit();
    try {
         // do code here
    }
    finally {
        conn.setAutoCommit( oldAutoCommit );
    }
  • 49. What is the difference between statement and prepared statment?

    • Prepared Statement is Pre-compiled class , but Statement is not.
    • So in PreparedStatement the execution will be faster.

    Actually when u submit a simple statement to the databse, at first the DBMS parses it and sends it back with the result, so again when u send the same statement again the DBMS server parses it and sends back the result so here a lot of time is wasted and because the statement is again parsed though it has been sent twice or thrice it consumes a lot of time and response will be slow.Prepared Statement is used when u want to execute a statement object many times. when u submit a PreparedStatement the DBMS server parses it and creates a execution plan. This e-plan can be used when u again send the same statement to the database.That is the DBMS server zest executes the compiled statement rather that executing it from first, hence we get an precompiled statement.And also the advanatge of using this PreparedStatement is it is used to send dynamic sql statements, which u can give values later than giving the values at the time of creation.

    48. What is a savepoint.

    Save point is a feature using which we can save  status of the transaction to a perticular extent.so that if anytime we have lost a transaction we can get it back using save point.

    47. What is the difference between ResultSetMetaData and DatabaseMetaData

    ResultSetMetaData
    • You can interrogate JDBC for detailed information about a query’s result set using a ResultSetMetaData object.
    • ResultSetMetaData is a class that is used to find information about the ResultSet returned from a executeQuery call.
    • It contains information about the number of columns, the types of data they contain, the names of the columns, and so on.
    • Two of the most common methods in the ResultSetMetaData are getColumnName and getColumnTypeName. These retrieve the name of a column, and the name of its associated data type, respectively, each in the form of a String.
    DatabaseMetaData

    DatabaseMetaData is a class that can be used to fetch information about the database you are using. Use it to answer questions such as:

    • What kind of catalogs are in the database?

    • What brand of database am I working with?

    • What username am I?

    • ex: username = dbmd.getUserName();

    46. What do you mean by batch update

    1. The JDBC drivers that support JDBC 2.0 and above support batch updates.
    2. With batch updates, instead of updating rows of a  table one at a time, you can direct JDBC to execute a group of updates at the same time.
    3. Statements that can be included in the same batch of updates are known as batchable statements.

    Homogeneous batch: If a statement has input parameters or host expressions, you can include that statement only in a batch that has other instances of the same statement. This type of batch is known as a homogeneous batch.

    Heterogeneous batch: If a statement has no input parameters, you can include that statement in a batch only if the other statements in the batch have no input parameters or host expressions. This type of batch is known as a heterogeneous batch.

    Two statements that can be included in the same batch are known as batch compatible.

    Use the following Statement methods for creating, executing, and removing a batch of SQL updates:

    • addBatch
    • executeBatch
    • clearBatch

    example: the amendments to the all email ids of the employees.

    45. What is the difference between local and global transaction.

    A transaction is atomic unit of Work.The tasks which are made into the transaction act as a unit which can be executed successfully all,or if at least one task fails to its promise ,then the effect of all the tasks are to be rollbacked.Thus transaction is committed or rolled backed.

    Transactions can be divided into two categories.

    1.Local Transactions:These transactions are confined to objects which reside inside one particular JVM.Local transactions in java can be implemented using the JTA api.

    2.Global Transactions:These transactions may encapsulate objects which are distributed on various JVM’s.Global transactions are implemented throught TWO-PHASE-COMMIT design implementation.

    44. What the new features in JDBC 2.0

    The following are the JDBC 2.0 features.

    • Resultset enhancements

      • JDBC 2.0 supports scrollable resultset capability under three major headings, namely, forward-only, scroll-insensitive, and scroll-sensitive.

      • Each of these resultsets can in turn be Read_only or Updatable. Forward_only/Read_only is feature of JDBC 1.0.

    • Batch Updates

      • automatic batch update and explicit batch update.

    • Advanced Data Types

      • The advanced data types such as objects, object references, arrays, LOBS, SQL Data, and Struct are now supported by JDBC 2.0.

    • JNDI

      • The Java Naming and Directory Interface (JNDI) is an interface to obtain network resources in a vendor independent fashion. This is available as part of the JDBC2.0 Optional Package (JDBC 2.0 Standard Extension API) and implemented by means of javax.sql package.

    • Connection Pooling

      • Connection pooling is a method where multiple consumers share a limited set of connections instead of each having to create new connections. This also includes connection caching. This is implemented by means of javax.sql package.

    • Distributed Transactions

      • A distributed transaction is a combination of two or more related transactions that execute in a coordinated manner.

      • All the individual transactions might take place in the same database, but typically, the individual transactions are in different databases and often in different locations.

      • Distributed transactions are defined as a JDBC2.0 standard extensions API and are also implemented by means of javax.sql package.

    • Other Features

      • Other features include fetch size/row prefetching. Fetch size is part of JDBC2.0 and includes methods to define the number of rows retrieved by each database fetch. 

    43. Explain JDBC Driver Types

    JDBC drivers are divided into four types or levels. Each type defines a JDBC driver implementation with increasingly higher levels of platform independence, performance, and deployment administration. The four types are:

    • Type 1: JDBC-ODBC Bridge
    • Type 2: Native-API/partly Java driver
    • Type 3: Net-protocol/all-Java driver
    • Type 4: Native-protocol/all-Java driver

    Type 1: JDBC-ODBC Bridge 
    The type 1 driver, JDBC-ODBC Bridge, translates all JDBC calls into ODBC (Open DataBase Connectivity) calls and sends them to the ODBC driver. As such, the ODBC driver, as well as, in many cases, the client database code, must be present on the client machine. Figure 1 shows a typical JDBC-ODBC Bridge environment.

    Pros
    The JDBC-ODBC Bridge allows access to almost any database, since the database’s ODBC drivers are already available. Type 1 drivers may be useful for those companies that have an ODBC driver already installed on client machines.

    Cons

    • The performance is degraded since the JDBC call goes through the bridge to the ODBC driver, then to the native database connectivity interface. The result comes back through the reverse process. Considering the performance issue, type 1 drivers may not be suitable for large-scale applications.
    • The ODBC driver and native connectivity interface must already be installed on the client machine. Thus any advantage of using Java applets in an intranet environment is lost, since the deployment problems of traditional applications remain.

    Type 2: Native-API/partly Java driver
    JDBC driver type 2 — the native-API/partly Java driver — converts JDBC calls into database-specific calls for databases such as SQL Server, Informix, Oracle, or Sybase. The type 2 driver communicates directly with the database server; therefore it requires that some binary code be present on the client machine.

    Pros
    Type 2 drivers typically offer significantly better performance than the JDBC-ODBC Bridge.

     
    The vendor database library needs to be loaded on each client machine. Consequently, type 2 drivers cannot be used for the Internet. Type 2 drivers show lower performance than type 3 and type 4 drivers.

    Type 3: Net-protocol/all-Java driver 
    JDBC driver type 3 — the net-protocol/all-Java driver — follows a three-tiered approach whereby the JDBC database requests are passed through the network to the middle-tier server. The middle-tier server then translates the request (directly or indirectly) to the database-specific native-connectivity interface to further the request to the database server. If the middle-tier server is written in Java, it can use a type 1 or type 2 JDBC driver to do this.

    Pros
    The net-protocol/all-Java driver is server-based, so there is no need for any vendor database library to be present on client machines. Further, there are many opportunities to optimize portability, performance, and scalability. Moreover, the net protocol can be designed to make the client JDBC driver very small and fast to load. Additionally, a type 3 driver typically provides support for features such as caching (connections, query results, and so on), load balancing, and advanced system administration such as logging and auditing.

    Cons
    Type 3 drivers require database-specific coding to be done in the middle tier. Additionally, traversing the recordset may take longer, since the data comes through the backend server.

    Type 4: Native-protocol/all-Java driver 
    The native-protocol/all-Java driver (JDBC driver type 4) converts JDBC calls into the vendor-specific database management system (DBMS) protocol so that client applications can communicate directly with the database server. Level 4 drivers are completely implemented in Java to achieve platform independence and eliminate deployment administration issues.

    Pros
    Since type 4 JDBC drivers don’t have to translate database requests to ODBC or a native connectivity interface or to pass the request on to another server, performance is typically quite good. Moreover, the native-protocol/all-Java driver boasts better performance than types 1 and 2. Also, there’s no need to install special software on the client or server. Further, these drivers can be downloaded dynamically.

    Cons
    With type 4 drivers, the user needs a different driver for each database.

    42. What is JDBC

    • JDBC (Java Database Connectivity) provides a standard interface for accessing a relational database from a Java application regardless of where the application is running and where the database is.
    • It provides a way for Java applications to call SQL and PL/SQL.
    • In other words it is a way to execute SQL statements and also call stored database procedures.
    • One important feature of JDBC is location independence. Java programs with database access can be written and deployed as an application or as a Web-based applet.
    • The ease of development, robustness, and security of Java programs makes it a good choice for writing database applications in Java.
    • JDBC consists of a high-level “thin” API and multiple low-level drivers for connecting to different databases.

    41. Explain Basic Steps in writing a Java program using JDBC

    Basically a Java program implementing JDBC performs the following functions:

    • Load a JDBC driver.

    • Establish a database connection.

    • Optionally interrogate the database for capability subset.

    • Optionally retrieve schema metadata information.

    • Construct a SQL or callable statement object and send queries or database tasks.

    • Execute the database tasks or process resultsets.

    • Close the statement object and resultset.

    • Close the connection.

    40. What is the difference between <jsp:include> and <c:import>

    1. The <c:import> tag imports a resource specified by a URL and exposes it to the page, variable, or reader.
    2. The <jsp:include> standard action is a request-time action that will include the output of another JSP at the location of the tag within the calling JSP.
    3. <c:import> is similar to the <jsp:include> directive, but with more features.
    4. The body of the import tag can have param tags for adding parameters to the URL.
    5. we can overcome jsp:include limitations with the JSTL import tag.
    6. The import tag adds functionality to the jsp:include tag and eliminates the need to code these functions yourself.
    7. The first additional function allows you to include content directly from other Web sites. So the following is now legal:
      <c:import url=”
      http://www.example.com/somecontent.html”/>
    8. You can even use ftp:
      <c:import url=”
      ftp://ftp.example.com/somecontent.txt”/>
    9. Rather than dump an imported URL straight to the page, you can store it in a variable. This is a common strategy in all the JSTL tags and increases the power of a JSP page:
      <c:import url=”http://www.example.com/example.inc” var=”example”/> Once this included page is stored in the example variable, you can use another taglib, such as the Jakarta String taglib, to replace all references to example.com with done.com.
    10. Since you can store <c:import> in a variable I’m wondering if <c:import> might do some type of full read before printing to output, whereas I imagine <jsp:include> uses buffering. This could show a performance difference for very large files, with <c:import> requiring longer and taking more memory to get all the data in the import whereas <jsp:include> did things with buffers.
    11. Include Syntax:

    <jsp:include page=”…url..” flush=”true or false“/>

    The tag can optionally contain a body:

    <jsp:include page="...url..." flush="true or false">
      <jsp:param  ..../>
    </jsp:include>
    

              Import Syntax:

    <c:import url=”resource URL”
              [var=”variable name”]
              [scope=”page|request|session|application”]
              [varReader=”variable name”]
              [context=”context name”]
              [charEncoding=”character encoding”]>
         JSP body content
    </c:import>

    39. What is the differences between Http Servlet and generic Servlet

    HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. A subclass of HttpServlet must override at least one method, usually one of these:

    • doGet, if the servlet supports HTTP GET requests
    • doPost, for HTTP POST requests
    • doPut, for HTTP PUT requests
    • doDelete, for HTTP DELETE requests
    • init and destroy, to manage resources that are held for the life of the servlet
    • getServletInfo, which the servlet uses to provide information about itself

    There’s almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above). Likewise, there’s almost no reason to override the doOptions and doTrace methods.

    GenericServlet defines a generic, protocol-independent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead.

    GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it’s more common to extend a protocol-specific subclass such as HttpServlet.

    GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface.

    To write a generic servlet, you need only override the abstract service method.

    38. Servlets 20 mins drill and Quiz.

    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

    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.

    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.

    When doGET() method will going to execute?

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

    When doPOST() method will going to execute?

    When we specified method=’POST’ in HTML
    < form name=’SSS’ method=’POST’ >

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

    setContentType() method must be set.

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

    HTTP

    How Can You invoke other web resources (or other servelt / jsp ) ?

    Servelt can invoke other Web resources in two ways: indirect and direct.
    Indirect Way : Servlet will return the resultant HTML to the browser which will point to another Servlet (Web resource)
    Direct Way : We can call another Web resource (Servelt / Jsp) from Servelt program itself, by using RequestDispatcher object.
    You can get this object using getRequestDispatcher(“URL”) method. You can get this object from either a request or a Context.
    Example :
    RequestDispatcher dispatcher = request.getRequestDispatcher(“/jspsample.jsp”);
    if (dispatcher != null)
    dispatcher.forward(request, response);
    }

    How Can you include other Resources in the Response?

    Using include method of a RequestDispatcher object.
    Included WebComponent (Servlet / Jsp) cannot set headers or call any method (for example, setCookie) that affects the headers of the response.
    Example : RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(“/banner”);
                if (dispatcher != null)
                dispatcher.include(request, response);
    }

    Is there any way to generate PDF’S dynamically in servlets?

    We need to use iText. A open source library for java. Please refer sourceforge site for sample servlet examples.

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

    getSession(true) – This method will check whether already a session is existing for the user. If a session is existing, it will return that session object, Otherwise it will create new session object and return taht object.
    getSession(false) – This method will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.

    Can I invoke a JSP error page from a servlet?

    Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets.

    If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:

    java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained

    The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:

    protected void sendErrorRedirect(HttpServletRequest request,
    HttpServletResponse response, String errorPageURL, Throwable e) throws
    ServletException, IOException {
    request.setAttribute (“javax.servlet.jsp.jspException”, e);
    getServletConfig().getServletContext().
    getRequestDispatcher(errorPageURL).forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
    {
    try {
    // do something
    } catch (Exception ex) {
    try {
    sendErrorRedirect(request,response,”/jsp/MyErrorPage.jsp”,ex);
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

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

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

    Simply have doGet call doPost, or vice versa.

    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.

    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.

    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.

    What do you understand by servlet mapping?
    Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.

    What must be implemented by all Servlets?
    The Servlet Interface must be implemented by all servlets.

    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.

    What is Session ID?
    A session ID is an unique identification string usually a long, random and alpha-numeric string, that is transmitted between the client and the server. Session IDs are usually stored in the cookies, URLs (in case url rewriting) and hidden fields of Web pages. 

    What are the advantage of Cookies over URL rewriting?
    Sessions tracking using Cookies are more secure and fast. Session tracking using Cookies can also be used with other mechanism of Session Tracking like url rewriting.

    Cookies are stored at client side so some clients may disable cookies so we may not sure that the cookies may work or not. 
    In url  rewriting requites large data transfer from and to the server. So, it leads to network traffic and access may be become slow.

    What is session hijacking?
    If you application is not very secure then it is possible to get the access of system after acquiring or generating the authentication information. Session hijacking refers to the act of taking control of a user session after successfully obtaining or generating an authentication session ID. It involves an attacker using captured, brute forced or reverse-engineered session IDs to get a control of a legitimate user’s Web application session while that session is still in progress.

    What is Session Migration?
    Session Migration is a mechanism of moving the session from one server to another in case of server failure. Session Migration can be implemented by:
    a) Persisting the session into database
    b) Storing the session in-memory on multiple servers.

    How to track a user session in Servlets?
    The interface HttpSession can be used to track the session in the Servlet. Following code can be used to create session object in the Servlet:

    HttpSession session = req.getSession(true);

    How you can destroy the session in Servlet?
    You can call invalidate() method on the session object to destroy the session.

    e.g. session.invalidate();

    37. What is servlet lazy loading.

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

    36. Sir, do you know about jsp application object

    • This implicit object represents the application to which the JSP belongs.
    •  JSPs are grouped into applications according to their URLs where the first directory name in a URL defines the application.
    • The application object contains methods that provide information about the JSP Container, support for logging plus utility methods for example translating a relative URL to an absolute path.
    Servlet Class

    javax.servlet.ServletContext

    The following table summarises the most useful methods available to the application object.

    Method Description
    getAttribute(String objName) Returns the object named objName or returns null if the objName does not exist.
    getAttributeNames() Returns an Enumeration containing the attribute names available within the application.
    setAttribute(String objName, Object object) Stores the object with the given object name in this application.
    removeAttribute(String objName) Removes the objName object from the application.
    getMajorVersion() Returns the major version of the Servlet API for the JSP COntainer.
    getServerInfo() Returns information about the JSP Container, typically, name and product version.
    getResourceAsStream(Path) Translates the resource URL into an input stream for reading.
    log(Message) Writes a text string to the JSP Containers default log file.

    35. Tell me something about jsp session object

    • The session implicit object is used to provide an association between the client and the server.
    • This association, or session, persists over multiple connections and/or requests during a given time period.
    • Sessions are used to maintain state and user identity across multiple page requests.
    • A session can be maintained either by using cookies or by URL rewriting. To expose whether the client supports cookies, session defines an isCookieSupportDetermined() method and an isUsingCookies() method.
    Servlet Class

    HttpSession

    The following table summarises the most useful methods available to the session object.

    Method Description
    isNew() A session is considered to be “new” if it has been created by the server, but the client has not yet acknowledged joining the session.
    invalidate() Discards the session, releasing any objects stored as attributes.
    getAttribute(String) Retrives the object associated with the named attribute.
    getAttributeNames() Retrives the names of all attributes currently associated with the session.
    setAttribute(String, object) Sets the object to the named attribute. attribute created if it doesn’t exist.
    removeAttribute(String) Removes the object bound with the specified name from this session.

    34. What do you know about jsp response object

    • The response object handles the output to the client.
    • This object can be used for creating HTTP Headers, creating cookies, setting content type and redirecting workflow.
    Servlet Class

    javax.servlet.http.HttpServletResponse

    The following table summarises the most useful methods available to the response object.

    Method Description
    setContentType() Sets the MIME type and character encoding for the page.
    addCookie(Cookie) Adds the specified cookie to the response. It can be called multiple times to set more than one cookie.
    containsHeader(name) Checks whether the response already includes this header.

     

    setHeader(name, value) Creates an HTTP Header.
    sendRedirect(String) Sends a temporary redirect response to the client using the specified redirect location URL.

    33. Explain request implicit object

    1. The request object retrieves the values that the client browser passed to the server during an HTTP request such as headers, cookies or parameters associated with the request.
    2. Among the most common use of the request object is to obtain parammeter or query string values.

    Servlet Class

    javax.servlet.HttpServletRequest

    The following table summarises the most useful methods available to the request object.

    Method Description
    getParameter(String name) Returns the value of a request parameter as a String, or null if the parameter does not exist.
    getParameterNames() Returns an Enumeration of String objects containing the names of the parameters contained in this request.
    getParameterValues(String name) Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
    getCookies() Gets the array of cookies found in this request. See below for more details on working with cookies.
    getQueryString() Gets any query string that is part of the HTTP request URI.
    getRequestURI() Gets the URI to the current JSP page.
    getHeaderNames() Returns an enumerator of all HTTP header names.
    getHeader(String hdr) Returns the value of an HTTP header such as “QUERY_STRING” or “URL”. The method getHeaderNames() can be used to determine what headers are available. See example below.
    getAttribute(String) Retrives the object associated with the named attribute.
    getAttributeNames() Retrives the names of all attributes currently associated with the session.
    setAttribute(String, object) Sets the object to the named attribute. attribute created if it doesn’t exist.
    removeAttribute(String) Removes the object bound with the specified name from this session.

    32. What is the difference between ServletContext and ServletConfig

    public interface ServletContext

    • Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
    • There is one context per “web application” per Java Virtual Machine.
    • The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.

    public interface ServletConfig

    • A servlet configuration object used by a servlet container used to pass information to a servlet during initialization.
    • This object defines how a servlet is to be configured is passed to a servlet in its init method.
    • Most servlet containers provide a way to configure a servlet at run-time (usually through flat file) and set up its initial parameters.
    • The container, in turn, passes these parameters to the servlet via the ServetConfig.

    31. Explain Servlet Life Cycle.

    1. Servlets are normal Java classes which are created when needed and destroyed when not needed. Since Servlets run within a Servlet Container, creation and destruction of Servlets is the duty of Servlet Container and not yours.
    2. Implementing the init() and destory() methods of Servlet interface allows you to be told by the Servlet Container that when it has created an instance of your Servlet and when it has destroyed that instance.
    3. An important point to remember is that your Servlet is not created and destroyed for every request it receives, rather it is created and kept in memory where requests are forwarded to it and your Servlet then generates response.

      

    Servlet Initialization (init())
    So you have created your Servlet class by extending the HttpServlet class and have placed it in /WEB-INF/classes/ directory of your application.

    Now when will Servlet Container create an instance of your Servlet? there are two situations :

    • When you have specifically told the Servlet Container to preload your Servlet when the Servlet Container starts by setting the load-on-startup tag to a non-zero value e.g.
      <web-app>
      
        <servlet>
          <servlet-name>test</servlet-name>
          <servlet-class>com.wordpress.sharat.servlets.TestServlet</servlet-class>
          <load-on-startup>1</load-on-startup>
        </servlet>
      
      </web-app>

      So when the Servlet Container starts it will preload your Servlet in the memory.

    • If your Servlet is not already loaded, it’s instance will be created as soon as a request is received for it by the Servlet Container.
    • During the loading of the Servlet into the memory, Servlet Container will call your Servlet’s init() method.
    • Since init() is going to be called only once you can put Servlet initialization code in it like getting hold of a database connection or whatever.

    Responding to Requests(service())

    1. Once your Servlet is initialized and it’s init() method called, any request that the Servlet Container receives will be forwarded to your Servlet’s service() method.
    2. HttpServlet class breakes this service() method into more useful doGet(), doPost(), doDelete(), doOptions(), doPut() and doTrace() methods depending on the type of HTTP request it receives.
    3. So in order to generate respose you should override the doGet() or doPost() method as required.
    4. At this moment all the requests will be forwarded to the appropriate doGet() or doPost() or whatever method as required. No new instance will be created for your Servlet.

    Servlet Destruction(destory())

    When your application is stopped or Servlet Container shuts down, your Servlet’s destroy() method will be called. This allows you to free any resources you may have got hold of in your Servlet’s init() method.

    Always Remember

    • init() and destroy() methods will be called only once during the life time of your Servlet
    •  while service() and it’s broken down methods ( doGet(), doPost() etc ) will be called as many times as requests are received for them by the Servlet Container.

    30. Explain the advantages of JSTL

    1. The Java Standard Tag Library (JSTL) is a standardized collection of custom tags.
    2. It has a number of tags for common tasks such as iterating through lists, interacting with databases, handling XML data, formatting data, and much more.
    3. The latest version of JSTL is 1.1. An implementation of JSTL can be downloaded from the Apache Jakarta Web site (http://jakarta.apache.org/).
    4. JSTL consist of four sets of tags and a library of functions, grouped according to their functionality:
    • The JSTL core tag library contains tags that deal with flow control in JSP pages, iterating over collections, evaluating expressions, and importing resources.
    • Before using the core tag library, the following directive needs to be added to the JSP page:
    • <%@ taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; %>
    • The equivalent XML syntax for this directive is as follows:
    • <jsp:directive.taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core&#8221; />

    The following table summarizes the JSTL core tags.

    Tag Name

    Description

    catch

    Catches any Throwable exception that occurs in the body of the tag

    choose

    Provides conditional operation and allows for choosing between mutually exclusive options

    if

    Provides conditional operation

    import

    Imports a resource specified by a URL and exposes it to the page, variable, or reader

    forEach

    Iterates over collections

    forTokens

    Iterates over tokens

    out

    Outputs expressions to the Web page

    otherwise

    A conditional operation tag for choosing between mutually exclusive options. This tag is a subtag of the choose tag.

    param

    Used along with the import, redirect, or url tags to add a parameter to a URL

    redirect

    Redirects to a new URL

    remove

    Removes a variable from a scope

    set

    Sets the value of an attribute

    url

    Creates a URL

    when

    A conditional operation tag that includes its body when an expression evaluates to true. This tag is a subtag of the choose tag.

    29. What are the advantages of JSP

    • Separation of static from dynamic content.
    • Write Once Run Anywhere.
    • Dynamic content can be served in a variety of formats.

                example: browsers using HTML/DHTML, to handheld wireless devices like mobile phones and PDAs using WML, to other B2B applications using XML

    • Recommended Web access layer for n-tier architecture.
    • Completely leverages the Servlet API.

    28. Explain JSP Basic Structure Items.

    JSP Expression

    • <%= expression %>
    • Expression is evaluated and placed in output.
    • XML equivalent is
      <jsp:expression>
      expression
      </jsp:expression>
      .
    • Predefined variables are request,response,out,session,application,config, andpageContext (available in scriptlets also).

    JSP Scriptlet

    • <% code %>
    • Code is inserted in service method.
    • XML equivalent is
      <jsp:scriptlet>
      code
      </jsp:scriptlet>
      .

    JSP Declaration

    • <%! code %>
    • Code is inserted in body of servlet class, outside of service method.
    • XML equivalent is
      <jsp:declaration>
      code
      </jsp:declaration>
      .

    JSP page Directive

    • <%@ page att=”val” %>
    • Directions to the servlet engine about general setup.
    • XML equivalent is
      <jsp:directive.page att="val"\>.
    • Legal attributes, with default values in bold, are:
      • import=”package.class
      • contentType=”MIME-Type
      • isThreadSafe=”true|false”
      • session=”true|false”
      • buffer=”sizekb|none”
      • autoflush=”true|false”
      • extends=”package.class
      • info=”message
      • errorPage=”url
      • isErrorPage=”true|false
      • language=”java”

    JSP include Directive

    • <%@ include file=”url” %>
    • A file on the local system to be included when the JSP page is translated into a servlet.
    • XML equivalent is
      <jsp:directive.include
        file="url"\>
      .
    • The URL must be a relative one. Use the jsp:include action to include a file at request time instead of translation time.

    JSP Comment

    • <%– comment –%>
    • Comment; ignored when JSP page is translated into servlet.
    • If you want a comment in the resultant HTML, use regular HTML comment syntax of <-- comment -->.

    The jsp:include Action

    • <jsp:include page=”relative URL” flush=”true”/>
    • Includes a file at the time the page is requested.
    • If you want to include the file at the time the page is translated, use the page directive with theinclude attribute instead. Warning: on some servers, the included file must be an HTML file or JSP file, as determined by the server (usually based on the file extension).

    The jsp:forward Action

    • <jsp:forward page=”relative URL“/>
    • Forwards request to another page.

    The jsp:plugin Action

    • <jsp:plugin attribute=”value“*> … </jsp:plugin>
    • Generates OBJECT orEMBED tags, as appropriate to the browser type, asking that an applet be run using the Java Plugin.

    27. How to handle cookies in JSP

    • The getCookies() method of the request object returns an array of Cookie objects.
    • Cookies are used to allow web browsers to hold small amounts of information or state data associated with a user’s web browsing.
    • Cookies are named and have a single value. They may have optional attributes, including a comment presented to the user, path and domain qualifiers for which hosts see the cookie, a maximum age, and a version.
     
    Cookie(java.lang.String name, java.lang.String value)
    

    Cookie objects have the following methods.

    getComment()
    Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

    getMaxAge()
    Returns the maximum specified age of the cookie.

    getName()
    Returns the name of the cookie.

    getPath()
    Returns the prefix of all URLs for which this cookie is targetted.

    getValue()
    Returns the value of the cookie.

    setComment(String)
    If a web browser presents this cookie to a user, the cookie’s purpose will be described using this comment.

    setMaxAge(int)
    Sets the maximum age of the cookie. The cookie will expire after that many seconds have passed. Negative values indicate the default behaviour: the cookie is not stored persistently, and will be deleted when the user web browser exits. A zero value causes the cookie to be deleted

    setPath(String)
    This cookie should be presented only with requests beginning with this URL.

    setValue(String)
    Sets the value of the cookie. Values with various special characters (white space, brackets and parentheses, the equals sign, comma, double quote, slashes, question marks, the “at” sign, colon, and semicolon) should be avoided. Empty values may not behave the same way on all browsers.

    26. Explain JSP Session implicit Object.

    1. The session implicit object is used to provide an association between the client and the server. This association, or session, persists over multiple connections and/or requests during a given time period. Sessions are used to maintain state and user identity across multiple page requests.
    2. A session can be maintained either by using cookies or by URL rewriting. To expose whether the client supports cookies, session defines an isCookieSupportDetermined() method and an isUsingCookies() method.

    Servlet Class

    HttpSession

    The following table summarises the most useful methods available to the session object.

    isNew()
    A session is considered to be “new” if it has been created by the server, but the client has not yet acknowledged joining the session.

    invalidate()
    Discards the session, releasing any objects stored as attributes.

    getAttribute(String)
    Retrives the object associated with the named attribute.

    getAttributeNames()
    Retrives the names of all attributes currently associated with the session.

    setAttribute(String, object)
    Sets the object to the named attribute. attribute created if it doesn’t exist.

    removeAttribute(String)
    Removes the object bound with the specified name from this session.

    25. What is Session Tracking.

    There are a number of problems that arise from the fact that HTTP is a “stateless” protocol. In particular, when you are doing on-line shopping, it is a real annoyance that the Web server can’t easily remember previous transactions. This makes applications like shopping carts very problematic: when you add an entry to your cart, how does the server know what’s already in your cart? Even if servers did retain contextual information, you’d still have problems with e-commerce. When you move from the page where you specify what you want to buy (hosted on the regular Web server) to the page that takes your credit card number and shipping address (hosted on the secure server that uses SSL), how does the server remember what you were buying?

    There are three typical solutions to this problem.

    1. Cookies. You can use HTTP cookies to store information about a shopping session, and each subsequent connection can look up the current session and then extract information about that session from some location on the server machine. This is an excellent alternative, and is the most widely used approach. However, even though servlets have a high-level and easy-to-use interface to cookies, there are still a number of relatively tedious details that need to be handled:
      • Extracting the cookie that stores the session identifier from the other cookies (there may be many, after all),
      • Setting an appropriate expiration time for the cookie (sessions interrupted by 24 hours probably should be reset), and
      • Associating information on the server with the session identifier (there may be far too much information to actually store it in the cookie, plus sensitive data like credit card numbers should never go in cookies).
    2. URL Rewriting. You can append some extra data on the end of each URL that identifies the session, and the server can associate that session identifier with data it has stored about that session. This is also an excellent solution, and even has the advantage that it works with browsers that don’t support cookies or where the user has disabled cookies. However, it has most of the same problems as cookies, namely that the server-side program has a lot of straightforward but tedious processing to do. In addition, you have to be very careful that every URL returned to the user (even via indirect means like Location fields in server redirects) has the extra information appended. And, if the user leaves the session and comes back via a bookmark or link, the session information can be lost.
    3. Hidden form fields. HTML forms have an entry that looks like the following: <INPUT TYPE="HIDDEN" NAME="session" VALUE="...">. This means that, when the form is submitted, the specified name and value are included in the GET or POST data. This can be used to store information about the session. However, it has the major disadvantage that it only works if every page is dynamically generated, since the whole point is that each session has a unique identifier.

    24. How can JSP inheritance be achieved

    The JSP super class and sub-class need to satisfy certain requirements as defined in the sections below. First let us assume we are using the HTTP protocol. Then mapping of other protocols is an easy task.

    Requirements for the Super Class

    • It must implement the HttpJspPage interface.
    • It will obviously extend the HttpServlet class. It needs to implement the three main lifecycle methods of the servlet:
      • init
      • destroy
      • service

    These implementations are ‘final’. In addition, the method getServletConfig must be implemented to return the ServletConfig object, passed onto the servlet during initialization.

    This super class now necessitates the base class to actually implement the JSP version of these three function calls: jspInit, jspDestroy, and _jspService, by providing abstract declarations for the same

      • public abstract void jspInit()
      • public abstract void jspDestroy()
      • The signature for the _jspService method depends on the kind of JSP Engine that has been deployed. For eg: if Weblogic is the JSP Engine, the signature is:
    public abstract void _jspService(HttpServletRequest request, HttpServletResponse response);

    The init method is called jspInit, the destroy method – jspDestroy, and the service method as _jspService.

    Requirements for the sub class

    The sub class may or may not provide the jspInit and jspDestroy method, based on whether the parent class provides it.

    Code snippet for the JSP sub class

    <%@ page extends=”JSPPageSuper”%>

    <%

    //Any server processing

    %>

    <HTML>

    </HTML>

    Note the first line where the page extends the JSPPageSuper servlet.

    23. Explain about JSP Standard Action

    * The use of JavaBeans within JSP pages is a system for accessing Java components through the standard interface of methods with set and get prefixes.
    * The general syntax for the useBean tag is as follows.
    <jsp:useBean id=”myBean” type=”classtype” class=”com.domain.ClassName” scope=”session” />

       #  The it attribute id mandatory and can be an arbitrary string, but each can only appear once within a page (i.e. You cannot have two beans with the same id within a page).
       #  The actual class must be stored under the WEB-INF\classes directory
       #  The scope attribute can be page,request,session, or application.
       #  The scope attribute is optional and if it is omitted the default is page scope.

    Example:

    # Java Bean Code

    package com.wordpress.sharat;
    public class TestJSPUseBean {
       private String firstName=”sharat”;
       private String lastName=”abcd”;
       public void setFirstName(String firstName) {
          this.firstName = firstName;
       }
       public void setLastName(String lastName) {
          this.lastName = lastName;
       }
       public String getFirstName() {
          return firstName;
       }
       
       public String getLastName() {
          return lastName;
       }
    }

    # Usage:

    That JavaBean can be used within a JSP as follows
    <jsp:useBean id=”testbean” type=”com.wordpress.sharat.TestJSPUseBean” class=”com.wordpress.sharat.TestJSPUseBean” scope=”session” />
    <html>
    <%
       out.print(testbean.getFirstName());
    %>
    </html>
    # getProperty

    <jsp:getProperty name=”testbean” property=”firstName”/>

    name and property attributes are mandatory.
    # setProperty

    <jsp:setProperty name=”testbean” property=”firstName” value=”Donkey”/>

    # This allows values of a JavaBean to be set at runtime.
    # Param Attribute:
      It is a very common requirement to want to set a property according to a runtime query parameter.
      for example with the URL query string
               ?firstname=marcus&lastname=green

      <jsp:setProperty name=”testbean” property=”firstName” param=”firstname” />
      <jsp:setProperty name=”testbean” property=”lastName”  param=”lastname” />

    # Default Params:
      <jsp:setProperty name=”person” property=”*”   />
      then It will correctly map the firstName and lastName parameters to the “testbean” bean.

    # type attribute in bean defication is optional. We can have a bean defication with type attribute and with out a “class” attribute.

    22. Discuss the scope of a variable declared in Declaration part and in scriptlet 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.
    • the scope is available to complete jsp and to complete in the converted servlet class.

    Variable declared inside a scriplet that variable will be declared inside a service method and the scope is with in the service method.

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

    Session tracking uses cookies by default to associate a session identifier with a unique user. If the browser does not support cookies, or if cookies are disabled, you can still enable session tracking using URL rewriting. URL rewriting essentially includes the session ID within the link itself as a name/value pair. However, for this to be effective, you need to append the session ID for each and every link that is part of your servlet response.

    Adding the session ID to a link is greatly simplified by means of of a couple of methods: response.encodeURL() associates a session ID with a given URL, and if you are using redirection, response.encodeRedirectURL() can be used by giving the redirected URL as input.

    Both encodeURL() and encodeRedirectedURL() first determine whether cookies are supported by the browser; if so, the input URL is returned unchanged since the session ID will be persisted as a cookie.

    Consider the following example, in which two JSP files, say hello1.jsp and hello2.jsp, interact with each other. Basically, we create a new session within hello1.jsp and place an object within this session. The user can then traverse to hello2.jsp by clicking on the link present within the page.Within hello2.jsp, we simply extract the object that was earlier placed in the session and display its contents. Notice that we invoke the encodeURL() within hello1.jsp on the link used to invoke hello2.jsp; if cookies are disabled, the session ID is automatically appended to the URL, allowing hello2.jsp to still retrieve the session object.

    Try this example first with cookies enabled. Then disable cookie support, restart the brower, and try again. Each time you should see the maintenance of the session across pages.

    Do note that to get this example to work with cookies disabled at the browser, your JSP engine has to support URL rewriting.

    hello1.jsp

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

    hello2.jsp

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

    20. How does JSP handle run-time exceptions

    You can use the errorPage attribute of the page directive to have uncaught run-time exceptions automatically forwarded to an error processing page. For example:

    <%@ page errorPage="error.jsp" %>

    redirects the browser to the JSP page error.jsp if an uncaught exception is encountered during request processing.

    Within error.jsp, if you indicate that it is an error-processing page, via the directive:

    <%@ page isErrorPage="true" %>

    the Throwable object describing the exception may be accessed within the error page via the exception implicit object.

    Note: You must always use a relative URL as the value for the errorPage attribute.

    19. Explain the life cycle of a JSP.

    A JSP page services requests as a servlet. Thus, the life cycle and many of the capabilities of JSP pages (in particular the dynamic aspects) are determined by Java Servlet technology.

    1. JSP page translation
    2. JSP page compilation
    3. load class
    4. create instance
    5. call the jspInit method
    6. call the _jspService method
    7. call the jspDestroy method

                 When a request is mapped to a JSP page, the web container first checks whether the JSP page’s servlet is older than the JSP page. If the servlet is older, the web container translates the JSP page into a servlet class and compiles the class. During development, one of the advantages of JSP pages over servlets is that the build process is performed automatically.

                The translation involves bringing in any included files, skipping any jsp comments and leaving in any of the HTML comments. The source is then compiled using the same javac compiler that you would use to compile any other Java program. Of course the result of many of the attempts at compilation will be compilation errors that require modifications to the JSP source. If a JSP is configured with <load-on-startup> in the deployment descriptor, the container will attempt to compile when it starts rather than waiting for the first request.

                 After the page has been translated and compiled, the JSP page’s servlet (for the most part) follows the servlet life cycle.

    • If an instance of the JSP page’s servlet does not exist, the container
      Loads the JSP page’s servlet class
    • Instantiates an instance of the servlet class
    • Initializes the servlet instance by calling the jspInit method
    • The container invokes the _jspService method, passing request and response objects.
    • If the container needs to remove the JSP page’s servlet, it calls the jspDestroy method.

    Initialization: The jspInit method is called by the container once and only once for a servlet instance. As you might guess from its name it is used to do initial once only setup such as getting resources and initialising variables that are used in the JSP page. The jspInit method can be overridden within a JSP page with code like the following.

    <%!
    public void jspInit(){
    /*getServletConfig is inherited */
    ServletConfig config= getServletConfig();
    }
    %>

    Execution: The _jspService method is the equivalent of the service() method for a servlet. The _jspService method is called for each request, taking the request and response objects as parameters. The scriptlets, html elements and expressions are put into this method as part of translation. The _jspService method makes the implicit objects available to the JSP page.The _jspService method cannot be overridden within a JSP page. 
    Cleanup: The jspDestroy method is guaranteed to to be the last method called by the container before an instance of a JSP page goes out of service. The jspDestroy method is typically used to clean up or release resources acquired by the jspInit method. The jspDestory method is a little like the finalize method in a plain old Java class, in that you cannot be certain exactly when it will run. Because of this be aware that it may not be the most efficient way of cleaning up precious resources.