Pages

Subscribe Twitter Twitter

Monday, August 2, 2010

DATABASE QUESTIONS

Database Questions

Q) DML  insert, update, delete

DDL  create, alter, drop, truncate, rename.

DQL  select

DCL  grant, revoke.

TCL  commit, rollback, savepoint.

Q) Normalization
Normalization is the process of simplifying the relationship between data elements in a record.


Q) Normal forms

(i) 1st normal form : - 1st N.F is achieved when all repeating groups are removed, and P.K should be defined.

(ii) 2nd normal form : - Eliminate any non full dependence of data item on record keys.

(iii) 3rd normal form : - Eliminate any transitive dependence of data items on P.K’s.


Q) Diff Primary key and a Unique key? What is foreign key?
A) Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only.

Foreign key constraint prevents any actions that would destroy link between tables with the corresponding data values. A foreign key in one table points to a primary key in another table. Foreign keys prevent actions that would leave rows with foreign key values when there are no primary keys with that value. The foreign key constraints are used to enforce referential integrity.
CHECK constraint is used to limit the values that can be placed in a column. The check constraints are used to enforce domain integrity.
NOT NULL constraint enforces that the column will not accept null values. The not null constraints are used to enforce domain integrity, as the check constraints.

Q) Diff Delete & Truncate?
A) Rollback is possible after DELETE but TRUNCATE remove the table permanently and can’t rollback. Truncate will remove the data permanently we cannot rollback the deleted data.

Dropping : (Table structure + Data are deleted), Invalidates the dependent objects, Drops the indexes
Truncating : (Data alone deleted), Performs an automatic commit, Faster than delete
Delete : (Data alone deleted), Doesn’t perform automatic commit

Q) Diff Varchar and Varchar2?
A) The difference between Varchar and Varchar2 is both are variable length but only 2000 bytes of character of data can be store in varchar where as 4000 bytes of character of data can be store in varchar2.

Q) Diff LONG & LONG RAW?
A) You use the LONG datatype to store variable-length character strings. The LONG datatype is like the VARCHAR2 datatype, except that the maximum length of a LONG value is 32760 bytes.
You use the LONG RAW datatype to store binary data (or) byte strings. LONG RAW data is like LONG data, except that LONG RAW data is not interpreted by PL/SQL. The maximum length of a LONG RAW value is 32760 bytes.

Q) Diff Function & Procedure
Function is a self contained program segment, function will return a value but procedure not.
Procedure is sub program will perform some specific actions.

Q) How to find out duplicate rows & delete duplicate rows in a table?
A)
MPID EMPNAME EMPSSN
------- --------------- ----------------
1 Jack 555-55-5555
2 Mike 555-58-5555
3 Jack 555-55-5555
4 Mike 555-58-5555
SQL> select count (empssn), empssn from employee group by empssn having count (empssn) > 1;

COUNT (EMPSSN) EMPSSN
------------- -----------
2 555-55-5555
2 555-58-5555

SQL> delete from employee where (empid, empssn)
not in (select min (empid), empssn from employee group by empssn);
Good approach
SQL> delete ename from emp a where rowid < (select min(rowid) from emp b where a.ename = b.ename);

Matrix Report
Select * from (select job,sum(decode (deptno,10,sal)) DEPT10,
sum(decode (deptno,20,sal)) DEPT20,
sum(decode (deptno,30,sal)) DEPT30 from
emp group by job);

Q) Select the nth highest rank from the table?
A) Select * from tab t1 where 2=(select count (distinct (t2.sal)) from tab t2 where t1.sal<=t2.sal)

Q) a) Emp table where fields empName, empId, address
b) Salary table where fields EmpId, month, Amount
these 2 tables he wants EmpId, empName and salary for month November?
A) Select emp.empId, empName, Amount from emp, salary where emp.empId=salary.empId and month=November;

Q) Oracle/PLSQL: Synonyms?
A) A synonym is an alternative name for objects such as tables, views, sequences, stored procedures, and other database objects

Syntax: -
Create [or replace] [public] synonym [schema.] synonym_name for [schema.] object_name;

or replace -- allows you to recreate the synonym (if it already exists) without having to issue a DROP synonym command.
Public -- means that the synonym is a public synonym and is accessible to all users.
Schema -- is the appropriate schema. If this phrase is omitted, Oracle assumes that you are referring to your own schema.
object_name -- is the name of the object for which you are creating the synonym. It can be one of the following:
Table Package
View materialized view
sequence java class schema object
stored procedure user-defined object
Function Synonym

Example:
Create public synonym suppliers for app. suppliers;
Example demonstrates how to create a synonym called suppliers. Now, users of other schemas can reference the table called suppliers without having to prefix the table name with the schema named app. For example:
Select * from suppliers;

If this synonym already existed and you wanted to redefine it, you could always use the or replace phrase as follows:
Create or replace public synonym suppliers for app. suppliers;
Dropping a synonym
It is also possible to drop a synonym.
drop [public] synonym [schema .] synonym_name [force];
public -- phrase allows you to drop a public synonym. If you have specified public, then you don't specify a schema.
Force -- phrase will force Oracle to drop the synonym even if it has dependencies. It is probably not a good idea to use the force phrase as it can cause invalidation of Oracle objects.

example:
Drop public synonym suppliers;
This drop statement would drop the synonym called suppliers that we defined earlier.

Q) What is an alias and how does it differ from a synonym?
A) An alias is an alternative to a synonym, designed for a distributed environment to avoid having to use the location qualifier of a table or view. The alias is not dropped when the table is dropped.

Q) What are joins? Inner join & outer join?
A) By using joins, you can retrieve data from two or more tables based on logical relationships between the tables

Inner Join: - returns all rows from both tables where there is a match
Outer Join: - outer join includes rows from tables when there are no matching values in the tables.

• LEFT JOIN or LEFT OUTER JOIN
The result set of a left outer join includes all the rows from the left table specified in the LEFT OUTER clause, not just the ones in which the joined columns match. When a row in the left table has no matching rows in the right table, the associated result set row contains null values for all select list columns coming from the right table.

• RIGHT JOIN or RIGHT OUTER JOIN.
A right outer join is the reverse of a left outer join. All rows from the right table are returned. Null values are returned for the left table any time a right table row has no matching row in the left table.

• FULL JOIN or FULL OUTER JOIN.
A full outer join returns all rows in both the left and right tables. Any time a row has no match in the other table, the select list columns from the other table contain null values. When there is a match between the tables, the entire result set row contains data values from the base tables.

Q. Diff join and a Union?
A) A join selects columns from 2 or more tables. A union selects rows.
when using the UNION command all selected columns need to be of the same data type. The UNION command eliminate duplicate values.

Q. Union & Union All?
A) The UNION ALL command is equal to the UNION command, except that UNION ALL selects all values. It cannot eliminate duplicate values.
> SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA

Q) Is the foreign key is unique in the primary table?
A) Not necessary

Q) Table mentioned below named employee
ID NAME MID
1 CEO Null
2 VP CEO
3 Director VP

Asked to write a query to obtain the following output
CEO Null
VP CEO
Director VP

A) SQL> Select a.name, b.name from employee a, employee b where a.mid=b.id(+).

Q) Explain a scenario when you don’t go for normalization?
A) If we r sure that there wont be much data redundancy then don’t go for normalization.

Q) What is Referential integrity?
A) R.I refers to the consistency that must be maintained between primary and foreign keys, i.e. every foreign key value must have a corresponding primary key value.

Q) What is Normalization? Explain in details?
A)  Normalization is the process of simplifying the relation ship between data elements in a record.

1st N.F -- the big table is broken into many small tables, such that each table has a primary key.
2nd N.F – Removes partial dependency. Ie The columns in a table which is not completely dependant on the primary key are taken to a separate table
3rd N.F – Removes Transitive dependency. Ie If X is the primary key in a table. Y & Z are columns in the same table. Suppose Z depends only on Y and Y depends on X. Then Z does not depend directly on primary key. So remove Z from the table to a look up table.

Q) What techniques are used to retrieve data from more than one table in a single SQL statement?
A) Joins, unions and nested selects are used to retrieve data.

Q) What is a view? Why use it?
A) A view is a virtual table made up of data from base tables and other views, but not stored separately.

Q) SELECT statement syntax?
A) SELECT [ DISTINCT | ALL ] column_expression1, column_expression2, ....
[ FROM from_clause ]
[ WHERE where_expression ]
[ GROUP BY expression1, expression2, .... ]
[ HAVING having_expression ]
[ ORDER BY order_column_expr1, order_column_expr2, .... ]

column_expression ::= expression [ AS ] [ column_alias ]
from_clause ::= select_table1, select_table2, ...
from_clause ::= select_table1 LEFT [OUTER] JOIN select_table2 ON expr ...
from_clause ::= select_table1 RIGHT [OUTER] JOIN select_table2 ON expr ...
from_clause ::= select_table1 [INNER] JOIN select_table2 ...
select_table ::= table_name [ AS ] [ table_alias ]
select_table ::= ( sub_select_statement ) [ AS ] [ table_alias ]
order_column_expr ::= expression [ ASC | DESC ]

Q) DISTINCT clause?
A) The DISTINCT clause allows you to remove duplicates from the result set.
> SELECT DISTINCT city FROM supplier;

Q) COUNT function?
A) The COUNT function returns the number of rows in a query
> SELECT COUNT (*) as "No of emps” FROM employees WHERE salary > 25000;

Q) Diff HAVING CLAUSE & WHERE CLAUSE?
A) Having Clause is basically used only with the GROUP BY function in a query.
WHERE Clause is applied to each row before they are part of the GROUP BY function in a query.

Q) Diff GROUP BY & ORDER BY?
A) Group by controls the presentation of the rows; order by controls the presentation of the columns for the results of the SELECT statement.

> SELECT "col_nam1", SUM ("col_nam2") FROM "tab_name" GROUP BY "col_nam1"
> SELECT "col_nam" FROM "tab_nam" [WHERE "condition"] ORDER BY "col_nam" [ASC, DESC]

Q) What keyword does an SQL SELECT statement use for a string search?
A) The LIKE keyword allows for string searches. The % sign is used as a wildcard.

Q) What is a NULL value? What are the pros and cons of using NULLS?
A) NULL value takes up one byte of storage and indicates that a value is not present as opposed to a space or zero value. A NULL in a column means no entry has been made in that column. A data value for the column is "unknown" or "not available."

Q) Index? Types of indexes?
A) Locate rows more quickly and efficiently. It is possible to create an index on one (or) more columns of a table, and each index is given a name. The users cannot see the indexes, they are just used to speed up queries.

Unique Index: -
A unique index means that two rows cannot have the same index value.
>CREATE UNIQUE INDEX index_name ON table_name (column_name)

When the UNIQUE keyword is omitted, duplicate values are allowed. If you want to index the values in a column in descending order, you can add the reserved word DESC after the column name:
>CREATE INDEX PersonIndex ON Person (LastName DESC)

If you want to index more than one column you can list the column names within the parentheses.
>CREATE INDEX PersonIndex ON Person (LastName, FirstName)

Q) Diff subqueries & Correlated subqueries?
A) subqueries are self-contained. None of them have used a reference from outside the subquery.
Correlated subquery cannot be evaluated as an independent query, but can reference columns in a table listed in the from list of the outer query.

Q) Predicates IN, ANY, ALL, EXISTS?
A) Sbquery can return a subset of zero to n values. According to the conditions which one wants to express, one can use the predicates IN, ANY, ALL or EXISTS.

IN The comparison operator is the equality and the logical operation between values is OR.
ANY Allows to check if at least a value of the list satisfies condition.
ALL Allows to check if condition is realized for all the values of the list.
EXISTS If the subquery returns a result, the value returned is True otherwise the value returned is False.

Q) What are some sql Aggregates and other Built-in functions?
A) AVG, SUM, MIN, MAX, COUNT and DISTINCT.

STRUTS

Struts Questions

Q) Diff Struts1.0 & 1.1?
A) 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
Change to the ORO package, 10.Change to Commons logging, 11. Removal of Admin actions, 12.Deprecation of the GenericDataSource

Q) Struts Validator Framework?
A) 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

Q) ActionServlet:-
The class org.apache.struts.action.ActionServlet is the called the ActionServlet. In the Jakarta Struts Framework this class plays the role of controller. All the requests to the server goes through the controller. Controller is responsible for handling all the requests.

Q) Action Class:-
The Action Class is part of the Model and is a wrapper around the business logic. 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. In the Action Class all the database/business processing are done. It is advisable to perform all the database related stuffs in the Action Class. The ActionServlet (commad) passes the parameterized class to Action Form using the execute() method. 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.

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class TestAction extends Action
{
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception{
return mapping.findForward("testAction");
}
}

Q) Action Form:-
An ActionForm is a JavaBean that extends org.apache.struts.action.ActionForm. ActionForm maintains the session state for web application and the ActionForm object is automatically populated on the server side with data entered from a form on the client side

Q) Message Resource Definition file:-
M.D.R file are simple .properties file these files contains the messages that can be used in struts project. The M.D.R can be added in struts-config.xml file through tag ex:

Q) Reset:-
This is called by the struts framework with each request, purpose of this method is to reset all of the forms data members and allow the object to be pooled for rescue.

public class TestAction extends ActionForm{
public void reset(ActionMapping mapping, HttpServletRequest request request)
}

Q) execute:-
is called by the controller when a request is received from a client. The controller creates an instance of the Action class if one do not already exist. The frame work will create only a single instance of each Action class.

public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response)

Q) Validate:-
This method is called by the controller after the values from the request has been inserted into the ActionForm. The ActionForm should perform any input validation that can be done and return any detected errors to the controller.

public ActionErrors validate(ActionMapping mapping, HttpServletRequest request)

Q) Struts-config.xml





















name="employeeForm" scope="request" validate="false">



name="employeeForm" scope="request" validate="true"
input="/employeeForm.jsp">














Q) web.xml :-
Is a configuration file describing the deployment elements.



Struts rr lesson 2


action
org.apache.struts.action.ActionServlet

debug
3

1




action
/do/*




index.jsp




struts/bean-el
/WEB-INF/struts-bean-el.tld



struts/html-el
/WEB-INF/struts-html-el.tld



struts/logic-el
/WEB-INF/struts-logic-el.tld





Design Patterns Questions

Service Locator
To access different resources/services, J2EE compatible server binds these resources/services to the JNDI server so that the clients can lookup those resources/services through JNDI lookup process from anywhere in the network. The resources/services can be
1. EJBHome objects
2. DataSource objects
3. JMS ConnectionFactory
4. JMS Topic/Queue etc.
EJB Client needs to initially get EJBHome object from JNDI to manage life cycle of EJBObjects. JMS clients need to get ConnectionFactory and Topic/Queue from JNDI for processing messages. JDBC clients need to get DataSource object in order to get database connection. All these services need to bind to the JNDI services and the clients need to lookup JNDI to get those services. Clients have to go through JNDI lookup process every time to work with these services. JNDI lookup process is expensive because clients need to get network connection to the JNDI server if the JNDI server is located on a different machine and need to go through lookup process every time, this is redundant and expensive.


The solution for the redundant and expensive JNDI lookup process problem is to cache those service objects when the client performs JNDI lookup first time and reuse that service object from the cache second time onwards for other clients. This technique maintains a cache of service objects and looks up the JNDI only first time for a service object. This technique reduces redundant and expensive JNDI lookup process thus increasing performance significantly. Service Locator Pattern implements this technique by having a class to cache service objects, methods for JNDI lookup and methods for getting service objects from the cache.
The figure below shows the ServiceLocator class intercepting the client request and accessing JNDI once and only once for a service object.

Here the clients call ServiceLocator class to get a service object rather than calling JNDI directly. ServiceLocator acts as interceptor between client and JNDI. For source code and different flavors of implementation of this Pattern, see the following links.

Session Facade
EJB clients (swing, servlets, jsps etc) can access entity beans directly. If EJB clients access entity beans directly over the network, it takes more network calls and imposes network overhead.
Here the servlet calls multiple entity beans directly to accomplish a business process, thereby increasing the number of network calls.
The solution for avoiding number of network calls due to directly accessing multiple entity beans is to wrap entity beans with session bean (Facade). The EJB client accesses session bean (Facade) instead of entity beans through coarse grained method call to accomplish a business process.


Message Facade
Session bean and entity bean methods execute synchronously that means the method caller has to wait till a value is returned. In some situations like sending hundred's of mails or firing a batch process or updating processes, the client does not have to bother about return value. If you use synchronous session and entity beans in such situations, they take a long time to process methods and clients have to wait till the method returns a value.

The client has to wait till all the eight synchronous steps complete. This synchronous execution takes a long time and has an impact on performance when the method process is huge.

To avoid blocking of a client, use asynchronous message driven beans, so that client does not have to wait for a return value. If a client uses asynchronous messaging then the client need not wait for a return value but can continue its flow of execution after sending the message.





Value Object

When a client calls a remote method there will be process of marshalling, network calls and unmarshalling involved for the remote method invocation. If you choose fine grained approach when calling methods remotely, there will be a significant network overhead involved. For example if you call fine grained method like this,
remoteObject.getName();
remoteObject.getCity();
remoteObject.getState();
remoteObject.getZipCode();
Here, there are four network calls from client to the remote object because every method call is remote method call.

The solution for avoiding many network calls due to fine grained method calls is to use coarse grained approach. For example :
// create an Value Object and fill that object locally
PersonInfo person = new PersonInfo();
person.setName("Ravi");
person.setCity("Austin");
person.setState("TX");
person.zipCode("78749");
// send Value Object through network
remoteObject.getPersonInfo(person);
Here, there is only one network call instead of three network calls and PersonInfo object is a Value Object. The following figure illustrates the coarse grained approach that is passing a Value Object through network.


Value Object is an object that is passed over the network rather than passing each attributes separately thus increasing performance by reducing network calls.

ValueObjectFactory
For a single request, a client might need to access multiple server side components such as different session beans and entity beans. In such situations the client accesses multiple components over the network, this increases the network traffic and has an impact on the performance.


To reduce the network traffic due to accessing multiple components by a client for a single request, let ValueObjectFactory hold different ValueObjects as place holders and respond with a single ValueObject for a client request. Here ValueObjectFactory holds creation and delegation logic of ValueObjects for different client requests.


Value List Handler
J2EE applications generally have the search facility and have to search huge data and retrieve results. If an application returns huge queried data to the client, the client takes long time to retrieve that large data and If that application uses entity bean to search data, it has an impact on.



1. Use Data Access Objects (DAO) rather than Entity beans
2. Return small quantity of data multiple times iteratively rather than returning large amount of data at once to the client.
Data Access Object encapsulates JDBC access logic. ValueListHandler caches list of Value objects that are retrieved through DAO. When client wants to search data, It calls ValueListHandler that is in turn responsible for caching data and returning data to the client iteratively.


Singleton
There will be only one instance for the entire JVM. You can achieve this by having the private constructor in the class.
Singleton is probably the most widely used design pattern. Its intent is to ensure that a class has only one instance, and to provide a global point of access to it. There are many situations in which a singleton object is necessary: a GUI application must have a single mouse, an active modem needs one and only one telephone line, an operating system can only have one window manager, and a PC is connected to a single keyboard

Public class Singleton{
Private static final Singleton s = new Singleton();
Private Singleton(){}
Public static Singleton getInstance(){ return s;}
}

Business Delegate
The Business Delegate hides the underlying implementation details of the business service, such as lookup & access details of the EJB architecture. The business delegates acts as a client-side business abstraction and hides the implementation of the business services.
The delegate may cache results and references to remote business services. Caching can significantly improve performance, because it limits unnecessary and potentially costly round trips over the network.
A Business Delegate uses a component called the Lookup Service. The Lookup Service is responsible for hiding the underlying implementation details of the business service lookup code. The Lookup Service may be written as part of the Delegate, but we recommend that it be implemented as a separate component, as outlined in the Service Locator pattern
Figure shows the class diagram representing the Business Delegate pattern. The client requests the BusinessDelegate to provide access to the underlying business service. The BusinessDelegate uses a LookupService to locate the required BusinessService component.

EJB FAQS

EJB Questions


Q) Application server & Web server
 Application server is a generalized server for running more than one application like ejb, rmi, jsp, servlets.
 webserver is for request, response paradigm. It takes the client request and send response back to the client and the connection is closed.
 A.S cannot process Http request, but takes the forwarded request from W.S and process the business logic and send the output to the W.S which it turns send to the client.
 A.S manage transactions, security, persistence and lot more, but W.S cannot help in this regards. W.S takes only the Http request.
 A.S provides runtime environment for server side components, they provide middleware services such as resource pooling and network.

Q) Diff Bean & Ejb

Q) SessionBeans
Session beans are not persistence there are short lived beans. S.B can perform database operations but S.B it self is not a persistence objects. S.B are business process objects they implements business logic, business rules and workflow.

Statefull Session Bean & Stateless Session Bean

 Statefull session bean is a bean that is designed to service business process that span multiple methods request/transaction, S.S.B can retain their state on the behalf of individual client. All S.S.B can exposes only a single ejbCreate() method it does not take any parameters.
 Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. S.S.B cannot hold the state.
 Statefull session bean do not have pooling concept
 Stateless session bean instance can be pooled.
 If the business process span multiple invocations there by requiring a conversational then S.S.B will be ideal choice.
 If the business last only for a single method call, S.S.B are suitable.

Q) Entity Bean
Entity beans are permanent business entities because their state is saved in permanent data storage. E.B are persistence objects, E.B contain data related logic. E.B are permanent so if any machine crashes, the E.B can be reconstructed in memory again by simple reading the data back in from the database.

Bean managed Persistence & Container managed Persistence
 B.P is an entity bean that must be persisted by hand, other words component developer must write the code to translate your in-memory fields into an underlying data store. You handle these persist operations your self, you place your data base calls in ejbLoad() and ejbStore(). Finder methods only for B.M.P for C.M.P your ejb container will implement the finder methods. In this commit, rollback, begin are transactions In B.M.P findByPK() return a reference to the actual bean object.
 You do not have to do anything to synchronize with data base. In entity bean deployment descriptor you specify which fields that the container should manage. The transaction in C.M.P are TX-Support, TX-NotSupport, TX-require. He findByPK() in C.M.P return void because the method is internally implemented.

Q) Message Driven Bean
 M.D.B process messages asynchronously are deliver via JMS. M.D.B’s are stateless, server side, transaction aware components used for asynchronous JMS messages. It acts as a JMS message listener which JMS messages, the messages may be sent by any J2ee component, an application client, another enterprise bean, or by a JMS application.
When Ejb application server starts it parse the D.D and then loads and initializes declared beans. In case of M.D.B container establish a connection with the message provide(MOM server), client access message beans through the beans JMS interface (java.JMS.messageListerner) which exposes a single method.
Public void onmessage(javax.JMS.message message)




Q) When to use container managed and bean managed persistence?
Container managed persistance is used when the persistant data store is a relational database and there is one to one mapping between a data represented in a table in the relational database and the ejb object.
Bean managed persistance in used when there is no one to one mapping of the table and a complex query reteriving data from several tables needs to be performed to construct an ejb object. Bean managed is also used when the persistence data storage is not a relational database.

Q) When to choose Statefull & Stateless Session bean?
A) Does the business process span multiple method invocations, requiring a conversational state if so the state full model fits very nicely. If your business process last for a single method call the stateless paradigm will better suite needed.

Q) Diff Statefull Session & Entity Bean
Both S.S.B & E.B undergo passivation and activation. The E.B have a separate ejbStore() callback for saving state during passivation & a separate ejbLoad() callback for loading state during activation. We do not need these callbacks for S.S.B because the container is simply uses object serialization to persist S.S.B fields.

Q) Object-Relational Mapping
Mapping of objects to relational database is a technology called O.R.M. O.R.M is a persistence mechanism of persistence objects than simple object serialization.

Q) When to use which bean Session Bean & Entity Bean?
 E.B are effective when application want to access one row at a time, if many rows needed to be fetched using session bean can be better alternative.
 E.B are effective when working with one row at a time cause of lot of N.W traffic. S.B are efficient when client wants to access database directly, fetching, updating multiple rows from data base.
 S.B for application logic.

Q) Deployment Descriptor
D.D contains information for all the beans in the “ejb.jar” file. D.D enables ejb container to provide implicit services to enterprise bean components, these services can gain your bean with out coding. D.D is a XML file.

Q) ejbCreate()
In stateless session bean can have only one ejbCreate() method it must take no arguments. Remember that ejbCreate() is essentially analogous to a constructor for ejb; it initializes an instance internal state variable. Because the stateless session bean has no client specific variables.

Q) Can a Session Bean be defined without ejbCreate() method?
A) The ejbCreate() methods is part of the bean's lifecycle, so, the compiler will not return an error because there is no ejbCreate() method.

- The home interface of a Stateless Session Bean must have a single create() method with no arguments, while the session bean class must contain exactly one ejbCreate() method, also without arguments.
- Stateful Session Beans can have arguments (more than one create method)
- Stateful beans can contain multiple ejbCreate() as long as they match with the home interface definition

Q) Can i call remove() on a Stateless Session bean?
A) Yes, The life of a Stateless Session bean for a client is just till the execution of the method that the client would have called on the bean…after the execution of that method if the client calls another method, then a different bean is taken from the pool. so the container very well knows that a bean has finished its life for a client and can put it back in the pool.

Q) Can a Stateless Session Bean maintain state?
A) Yes, A Stateless Session bean can contain no-client specific state across client invoked methods. For ex states such as socket connection, dbase connection, references to an EJBObject and so on can be maintained.

Q) How can I map a single Entity Bean to multiple tables?
A) If u use Bean-Managed Persistence(BMP), map the bean to tables manually. Consider applying the DAO design pattern to accomplish this,.
If u choose Container-Managed persistence(CMP), use the vendors object/relational mapping tool to specify the mapping between your object state and the persistence schema.

Q) Can EJB handle transaction across multiple databases?
A) The transaction manager in EJB handling transaction across multiple databases. This is accomplished with multiple Entity beans handling to each database and a single session bean to manage a transaction with the Entity bean.

Q) Session Bean CallBack methods?
public interface javax.ejb.SessionBean extends javax.ejb.EnterpriseBean
{
public abstract void ejbActivate();
public abstract void ejbCreate();
public abstract void ejbPassivate();
public abstract void ejbRemove();
public abstract void setSessionContext(SessionyContext ctx);
}

SessionContext  S.C is your beans gateway to interact with the container, S.C query the container about your current transactional state, your security state.

ejbCreate()

ejbPassivate( )  If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here, ie,close socket connections..etc.

ejbActivate( )  When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection

ejbRemove() container wants to remove your bean instance it will call this method.

Q) Entity Bean CallBack methods?
public interface javax.ejb.EntityBean extends javax.ejb.EnterpriseBean
{
public abstract void ejbActivate();
public abstract void ejbLoad();
public abstract void ejbPassivate();
public abstract void ejbRemove();
public abstract void ejbStore();
public abstract void setEntityContext(EntityContext ctx);
public abstract void unsetEntityContext();
}

Q) EJBContext Rollback Methods

EJBContext interface provides the methods setRollbackOnly() & getRollbackOnly().
setRollbackOnly( )Once a bean invokes the setRollbackOnly() method, the current transaction is marked for rollback and cannot be committed by any other participant in the transaction--including the container.
getRollbackOnly( )  method returns true if the current transaction has been marked for rollback. This can be used to avoid executing work that wouldn't be committed anyway.

Q) How can I call one EJB from inside of another EJB?
A) EJB can be clients of another EJB’s. it just works. Use JNDI to locate the Home Interface of the other bean, then acquire an instance.




Q) Conversational & Non-conversational
Conversational is an interaction between the bean and client, stateless session bean is a bean that do not hold multi method conversation with clients. Stateless.S.B cannot hold state, Statefull.S.B can hold conversational with client that may span multiple method request.

Q) JNDI to locate Home Objects
H.O are physically located some where on the N.W, perhaps in the address space of the Ejb Container. For client to locate H.O, you must provide nick name for your beans H.O. Client will use this nick name to identify the H.O it wants, we will specify the nice name in the Deployment descriptor. Container will use this nick name, JNDI goes over the N.W to some directory service to look for the H.O.

Properties props = System.getProperties();
Context ctx = new InitialContext(props);
MyHome home = (MyHome)ctx.lookup(“MyHome”);
MyRemoteInterface remote = home.create();

Q) Diff servlet/jsp session & EJB session
 logical point of view a servlet/jsp session is similar to an ejb session. A session in servlet is maintained by the servlet container through Http session object.. That is acquiring through the request object. You cannot instantiate Http session object.
 A session in Ejb is maintained using S.B, you design bean that can maintain business logic. You can have 2 types of beans 1. Stateless 2. Stateful.

Q) ejbCretae( ) & ejbPostCreate( )
 ejbCreate() is called just before the state of the bean is written to the persistence storage. After this method is completed a new record is created and written.
 ejbPostCreate() is called after the bean has been written to the database and the bean data has been assigned to an Ejb object.

Q) Can map Entity bean to more than one table?
A)

Q) EAR, WAR, JAR
 All EJB classes should package in a JAR file, All web components pages, servlets, gif, html, applets, beans, ejb modules, classes should be packaged into WAR file. EAR file contain all the JAR & WAR files. Note that each JAR, WAR, EAR file will contain D.D

Q) Life cycle

Life cycle of a Stateful Session Bean

- Stateful session bean has 3 states Does Not Exist, Method Ready Pool and Passivated states.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- Once a container creates one are more instance of a Stateful Session bean it sets them in a Method Ready State. In this state it can serve requests from its clients. Like Stateless beans, a new instance is created(Class.newInstance()), the context is passed (setSessionContext()) and finally the bean is created with the ejbCreate().
- ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here,ie,close socket connections..etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection




Life cycle of a Stateless Session Bean : -

- A S.S.B has only two states: Does Not Exist and Method Ready Pool.
- A bean has not yet instantiated when it is in the Does Not Exist Sate.
- When the EJB container needs one are more beans, it creates and set then in the Method Ready Pool Sate. This happens through the creation of a new instance(Class.newInstance()), then it is set its context (setSessionContext()) and finally calls the ejbCreate() method.
- The ejbRemove() method is called to move a bean from the Method Ready Pool back to Does Not Exist State.



Life cycle of Entity bean
- Bean instance “Dose not exist” state represent entity bean instance that has not been instantiated yet.
- To create a new instance container calls the newInstance() on entity bean class.
- After step 2 E.B is in a pool of other E.Bs. At this point your E>b does not have any E.B data base data loaded into it and it does not hold any bean specific resources (socket & database connections) .If the container wants to reduce it’s pool size it can destroy your bean by calling unsetEntityContext() on your bean.
- When the client wants to create some new data base data it calls a create() method on entity beans HomeObject. The container grabs the beans instance from the pool and the instance ejbCreate() method is called.
- E.B to be kicked back to pool, if a client call ejbremove() method.
- ejbPassivate( ) If too many beans are instantiated, the container can passivate some of them .ie write the bean to some temp storage. The container should release all resources held by the bean. Just before passivating, the container calls the ejbPassivate() method. So release all resources here, ie,close socket connections..etc.
- ejbActivate( ) When a passiavted bean is called, its said to be activated. The container then calls the ejbActivate() method. Acquire all the required resources for the bean in this method. ie get socket connection
-



Life cycle of M.D.B


Does Not Exist
When an MDB instance is in the Does Not Exist state, it is not an instance in the memory of the system. In other words, it has not been instantiated yet.

The Method-Ready Pool
MDB instances enter the Method-Ready Pool as the container needs them. When the EJB server is first started, it may create a number of MDB instances and enter them into the Method-Ready Pool. (The actual behavior of the server depends on the implementation.) When the number of MDB instances handling incoming messages is insufficient, more can be created and added to the pool.

Transitioning to the Method-Ready Pool
When an instance transitions from the Does Not Exist state to the Method-Ready Pool, three operations are performed on it. First, the bean instance is instantiated when the container invokes the Class.newInstance() method on the MDB class. Second, the setMessageDrivenContext() method is invoked by the container providing the MDB instance with a reference to its EJBContext. The MessageDrivenContext reference may be stored in an instance field of the MDB.
Finally, the no-argument ejbCreate() method is invoked by the container on the bean instance. The MDB has only one ejbCreate() method, which takes no arguments. The ejbCreate() method is invoked only once in the life cycle of the MDB.

Q) EJB Resources?

text
name
Java type
mycom.ejb.AccountHome
mycom.ejb.Account
ejb.name
security role


Q How to deploy in J2EE (i.e Jar, War file) ?

Each web application should be contained in a war (web archive) file. War files are nothing but a jar file containing atleast one descriptor called web.xml. The file structure of war file is:

/--
|
| WEB-INF
| |
| |-- WEB.XML (Deployment descriptor)
| |-- classes (Folder containing servlets and JSPs
|
| META-INF
| |
| |-- MANIFEST.MF
|
| all utility files and resources like error pages etc.

Each enterprise bean is stored in a jar file. The jar file contains all standard files like manifest and atleast one additional file called ejb-jar.xml. The structure of a jar file is:

/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- ejb-jar.xml
|
| all classes as in a normal jar file.

Both jar and war files are placed inside a ear (enterprise archive) file. The structure of an ear file is

/--
|
| META-INF
| |
| |-- MANIFEST.MF
| |-- application.xml
|
| jar and war files.



Q) Deployment descriptor of EJB


JavaBeans 1.1//EN" "http://java.sun.com/j2ee/dtds/ejb-jar_1_1.dtd">



This Deployment includes all the beans needed to make a reservation:
TravelAgent, ProcessPayment, Reservation, Customer, Cruise, and Cabin.



TravelAgentBean
com.titan.travelagent.TravelAgent
...


CustomerBean
com.titan.customer.Customer
...


ProcessPaymentBean
com.titan.processpayment.ProcessPayment
...

...


...

...


Q)
Remote Interface

public interface Hello extends javax.ejb.EJBObject
{
public String hello() throws java.rmi.RemoteException;
}

Home Interface

public interface HelloHome extends javax.ejb.EJBHome
{
Hello create() throws java.rmi.RemoteException; javax.ejb.CreateException;
}

Bean Class

public class HelloBean implements javax.ejb.SessionBean
{
private SessionContex ctx;
public void ejbCreate();
public abstract void ejbRemove();
public abstract void ejbActivate();
public abstract void ejbPassivate();
public abstract void setSessionContext(SessionyContext ctx);

public String hello(){
System.out.println(“hello());
Return “hello world”;
}

Client

public class HelloClient
{
public static void main(String args[ ])
properties props = system.getProperties();
Context ctx = new InitialContext(props);
Object obj = ctx.lookup(“HelloHome”);
HelloHome home = (HelloHome)
javax.rmi.protableRemoteObject.narrow(obj, HelloHome.class);
Hello hello = home.create();
System.out.println(hello.hello());
Hello.remove();
}

Q) Transaction Isolation levels

TRANSACTION_READ_UNCOMMITTED
The transaction can read uncommitted data. Dirty reads, nonrepeatable reads, and phantom reads can occur. Bean methods with this isolation level can read uncommitted change.

TRANSACTION_READ_COMMITTED
The transaction cannot read uncommitted data; data that is being changed by a different transaction cannot be read. Dirty-reads are prevented; nonrepeatable reads and phantom reads can occur. Bean methods with this isolation level cannot read uncommitted data.

TRANSACTION_REPEATABLE_READ
The transaction cannot change data that is being read by a different transaction.
Dirty reads and nonrepeatable reads are prevented; phantom reads can occur. Bean methods with this isolation level have the same restrictions as Read Committed and can only execute repeatable reads.

TRANSACTION_SERIALIZABLE
The transaction has exclusive read and update privileges to data; different transactions can neither read nor write the same data. Dirty reads, nonrepeatable reads, and phantom reads are prevented. This isolation level is the most restrictive.

Dirty-read  When your application reads data from a database that has not been committed to permanent storage yet.

Un-repeatable read  When a component reads some data from a database, but upon reading the data, the data has been changed. This can arise when another concurrently executing transaction modifies the data being read.

Phantom-read  A phantom is a new set of data that magically appears in a database between two database read operations.

Q) Diff Phantom & Un-repeatable
Un-repeatable occurs when existing data is changed, where as phantom read occurs when new data is inserted that does not exist before.

Q) Transaction Attributes

TX_BEAN_MANAGED  Then your bean programmatically controls its own transaction boundaries. When you using programmatically transaction, you issue the begin, commit & abort statements.

TX_NOT_SUPPORTED  If you set this your bean cannot be involved in a transaction at all.

TX_REQUIRED  If you want your bean to always run in a transaction. If there is a transaction already running your bean joins in on that transaction. If there is no transaction running, the container starts one for you.

TX_REQUIRES_NEW  If you always want a new transaction to begin when your bean is called we should use this. If there is a transaction already underway when your bean called, that transaction is suspended during the bean invocation. The container then launches a new transaction and delegate the call to the bean.

TX_SUPPORTS  When a client call this it runs only in a transaction if the client had one running already; it then joins that transaction. If no transaction =, the bean runs with no transaction at all.

TX_MANDATORY  Is a safe transaction attribute to use. It guarantees that your bean should run in a transaction. There is no way your bean can be called if there is not a transaction already running.

Q) ACID Properties
When you properly use transaction your operations will execute ACID properties.

(i) Atomicity  Guarantees that many operations are bundled together and appears as one contiguous unit of work.
Ex:- When you transfer money from one bank account to another you want to add funds to one account and remove funds from the other transaction and you want both operations to occur or neither to occur.

(ii) Consistency  Guarantees that a transaction will leave the system state to be consistent after a transaction completes.
Ex:- A bank system state could be consist if the rule “bank account balance must always be +ve”.

(iii) Isolation  Protect concurrently executing transaction from seeing each other incomplete results.
Ex:- If you write a bank account data to a database, the transaction may obtain locks on the bank account record (or) table. The lock guarantee that no other updates can interfere.

(iv) Durability  Resources keep a transactional log for resources crashes, the permanent data can be reconstructed by reapplying the steps in the log.

Q) Diff Sax & DOM

DOM SAX
1. Tree of nodes
2. Occupies more memory preferred for small XML documents
3. Slower at runtime
4. Stored as objects
5. Programmatically easy, since objects
6. Easy of navigation
7. DOM creates a tree structure in memory 1.Sequence of events
2.Does not use any memory preferred for large documents.
3.Faster at runtime
4.Objects are to be created
5.Need to write code for creating objects are to referred
6.backward navigation is not possible

Q) Hot deployment
Hot Deployment in Web Logic is he act of deploying, re-deploying and un-deploying EJBs while the server is still running.

Q) When should I use TxDataSource instead of Datasource?
If your application (or) environment meet the following criteria you should use
- uses JTA
- uses EJB container in web logic server to manage transactions.
- Includes multiple database updates with single transaction.
- Access multiple resources, such as database & JMS during transactions.
- Use same connection pool on multiple servers.

Q) Clustering
In J2ee container can be distributed, a distributed container consist of number of JVM’s running on one are more host machines. In this setup, application components can be deployed on a number of JVM’s. Subject to the type of loading strategy and the type of the component the container can distributed the load of incoming request to one of these JVM’s.

JDBC

JDBC Questions



Q) What Class.forName will do while loading drivers?
A) It is used to create an instance of the driver and register with the DriverManager.

Q) JDBC connection

import java.sql.*;
public class JDBCSample {
public static void main(java.lang.String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
} catch (ClassNotFoundException e) {
System.out.println("Unable to load Driver Class");
return;
}
try {
Connection con = DriverManager.getConnection("jdbc:odbc:companydb","", "");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT FIRST_NAME FROM EMPLOYEES");
while(rs.next()) {
System.out.println(rs.getString("FIRST_NAME"));
}
rs.close();
stmt.close();
con.close();
}
catch (SQLException se) {
System.out.println("SQL Exception: " + se.getMessage());
}
}
}



Q) 4th type driver

class.forName(“oracle.jdbcdriver.oracledriver”);
//DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
// com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource for Initial Context
//
connection con = driverManager.getConnection(“jdbc:oracle:thin:@hostname:portno:oracleservice”,”uid”, “pwd”);

Q) Steps to connect to JDBC?
A) 1. First thing is using jdbc you have to establish a connection to the data base this is 2 steps process (i) you must load the jdbc driver (ii) then make a connection, to do this we can call the getConnection() method of driver manager class.
2. To execute any sql commands using jdbc connection you must first create a statement object to create this call statement st = con.createSteatement().
This is done by calling the createStatement () method in connection interface. Once the statement is created you can executed it by calling execute () method of the statement interface.

Q) JDBC connection pool
When you are going to create a pool of connection to the data base. This will give access to a collection of already opened data base connections, which will reduce the time it takes to service the request and you can service “n” number of request at once.

Q) Why you need JDBC if ODBC is available?
A) ODBC is purely written in “c” so we cannot directly connect with java. JDBC is a low level pure java API used to execute SQL statements. (i) ODBC is not appropriate for direct use from java because it uses “c” interfaces. A call from java to native “c” code has number of drawbacks in the security, implementation and robustness.

Q) Can we establish the connection with ODBC itself?
A) Yes, using java native classes we have to write a program.

Q) What is necessity of JDBC in JDBC-ODBC Bridge?
A) The purpose of JDBC is to link java API to the ODBC, ODBC return high level “c” API so the JDBC converts “c” level API to java API.

Q) JDBC Drivers
o JDBC-ODBC Bridge Driver
o Native API - Partly Java Driver
o Network protocol – All Java Driver
o Native Protocol - Pure Java Driver
Tier Driver mechanism Description
Two JDBC-ODBC JDBC access via most ODBC drivers, some ODBC binary code and client code must be loaded on each client machine. This driver is commonly used for prototyping. The JDBC-ODBC Bridge is JDBC driver which implements JDBC operations by translating them to JDBC operations.
Two Native API - Partly - Java driver This driver converts JDBC calls to database specific native calls. Client requires database specific libraries.
Three JDBC - Net -All Java driver This driver converts JDBC calls into DBMS independent network protocol that is sent to the middleware server. This will translate this DBMS independent network protocol into DBMS specific protocol, which is sent to a particular database. The results are again rooted back to middleware server and sent back to client.
Two Native protocol - All - Java driver They are pure java driver, they communicate directly with the vendor database. They convert JDBC commands.

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

Q) Is the JDBC-ODBC Bridge multi-threaded?
A) No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC
Q) Dynamically creating Tables
Statement st = con.cretaeStatement ();
Int n = st.executeUpdate (“create table “+ uname+ “(sno int, sentby varchar (10), subject varchar (15)”);

Q) Statements in JDBC

Statement  Does not take any arguments; in this statement it will check syntax error and execute it every time.

Prepare statement  P.S is precompiled statements once we compile the statements and send it to the server for later use. P.S are partially compiled statements placed at server side with place holders. Before execution of these statements user has to supply values for place holders, it will increase performance of application.

PreparedStatement pst = con.prepareStatement("SELECT * FROM EMP WHERE deptno=?");
DataInputStream dis = new DataInputStream(“System.in”);
Int dno = Integer.ParseInt(dis.readLine());
pst.setInt(1, dno);
ResultSet rs = pst.executeQuery();

execute () return type boolean and executeUpdate () return type is int.

Callable statement  C.S used to retrieve data by invoking stored procedures, stored procedure are program units placed at data base server side for reusability. These are used by n-number of clients. Stored procedures are precompiled in RDBMS, so they can run faster than the dynamic sql.
Callable statement will call a single stored procedure, they perform multiple queries and updates without net work traffic.

callableStatement cst = con.prepareCall(“{CALL procedure-name(??)} ”);
DataInputStream dis = new DataInputStream(“System.in”);
Int enum = Integer.ParseInt(dis.readLine());
cst.setInt(1, enum);
cst.registerOutParameter(2, types.VARCHAR)
resultset rs = cst.execute();

In  used to send information to the procedure.
Out  used to retrieve information from data base.
InOut  both.

Q) Retrieving very large values from database?
A) getASSCIISteram()  read values which are character in nature.
GetBinaryStream()  used to read images.

Q) ResultSetMetaData
It is used to find out the information of a table in a data base.
ResultSet rs = stmt.executeQuery("SELECT * FROM "+ table);
ResultSetMetaData rsmd = rs.getMetaData();

Methods in ResultSetMetaData  getColumnCount(), getColumnName(), getColumnLabel(), getColumnType(), getTableName(),

Q) Database MetaData
You need some information about the “data base” & “dictionary” we use this .To find out tables, stored procedure names, columns in a table, primary key of a table we use this, this is the largest interface in java.sql package

Connection con = DriverManager.getConnection(jdbcURL, "", "");
DatabaseMetaData dbmd = con.getMetaData();
ResultSet rs= dbmd.getxxx();

Methods in DatabaseMetaData  getColumns(), getTableTypes(), getTables(), getDriverName(), getMajorVersion(), get MinorVersion(), getProcedures(), getProcedureColumns(), getTables().

Q) Procedure
Procedure is a subprogram will perform some specific action; sub programs are naming PL/SQL blocks that can take parameters to be invoked.

create or replace procedure procedure-name (id IN INTEGER , bal IN OUT FLOAT) IS
BEGIN
select balance into bal from accounts where account_id = id;
bal := bal + bal * 0.03;
update accounts set balance = bal where account_id = id;
END;

Q) Trigger
Trigger is a stored PL/SQL block associated with a specific database table. Oracle executes triggers automatically when ever a given SQL operation effects the table, we can associate 12 data base triggers with in a given table.

Create/Replace trigger before Insert (or) Delete (or) Update on emp for each row
Begin
Insert into table-name values(:empno; :name)
end


Q) Stored Images into a table

Public class img
{
Public static void main(String args[]){
Class.forName();
Connection con = DriverManager.getConnection();
Preparestatement pst = con.prepareStatement(“insert into image value(?));
FileInputStream fis = new FileInputStream(“a.gif”);
Pst.setBinaryStream(1, fis, fis.available);
Int I = pst.executeUpadate();
}

Retrieve Image

Statement st = con.CreateStatement();
ResultSet rs = st.executeQuery(“select * from img”);
rs.next();
InputStream is = rs.getBinaryStream(1);
FileOutPutStream fos = new FileOutPutStream(“g2.gif”);
Int ch;
While((ch=is.read(1))!=!-1)
{
fos.write(ch);
}


Q) Resultset Types
rs.beforeFirst()  goto 1st record
rs.afterLast()  goto last record
res.absolute(4)  will got 4th record in result set.
rs.first(), rs.last()
rs.deleteRow()
rs.updateRow(), rs.updateRow(3,88)  value in column 3 of resultset is set to 88.

JSP QUESTIONS

JSP Questions

Directives
Page Directive <%@ Page language="java" extends="className" import="className" session="true|false" buffer="8KB" autoFlush="true/false" isThreadSafe="true/false" info="text" errorPage="jspUrl" isErrorPage="true/false" contentType="mimeType” %> Page directive defines information that will be globally available for that page
Include Directive <%@ include file="relative URL" %> Include JSP are Servlet at compile time meaning that only once parsed by the compiler, it will act as a “C” "#include" pulling in the text of the included file and compiling it as if it were part of the including file. We can also include “Static” files using this directive.
Taglib Directive <%@ taglib uri="uriToTagLibrary" prefix="prefixString" %> Taglib directive enables you to create your own custom tags.


Actions
type="" bean Name="" type=""
UseBean tag is used to associate a java bean with jsp.


Sets a property value or values in a bean.

Gets the value of a bean property so that you can display it in a result page.
It is used to provide other tags with additional information in the form of name, value pairs. This is used to conjunction with jsp:include, jsp:forward, jsp:plugin.





Jsp Include includes the JSP are Servlet at request time, it is not parsed by the compiler, and it Includes a static file or sends a request to a dynamic file.





When ever the client request will come it will take the request and process the request and the request to be forward to another page and it will also forward the http parameters of the previous page to the destination page. It will work at server side.

<%! private void processAmount () { ... } %>

XML syntax for JSP declaration is int x;

Q) Expressions
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.
Ex: <%= (new java.util.Date ()).toLocaleString() %>

XML syntax for JSP expression is Java expression

Q) Scriptlet
A scriptlet can contain variable or method declarations, or expressions that are valid in the page scripting language. Within scriptlet tags, you can
1.Declare variables or methods to use later in the file
2.Write expressions valid in the page scripting language
3.Use any of the JSP implicit objects or any object declared with a tag.
Scriptlets are executed at request time, when the JSP engine processes the client request. If the scriptlet produces output, the output is stored in the out object, from which you can display it.

XML syntax for JSP scriptlets is Java code

Q) Comments
Html comment  Creates a comment that is sent to the client in the viewable page source.
Ex: ] -->

Hidden Comment  Documents the JSP file, but is not sent to the client.
Ex: <%-- comment --%>


Q) MVC

Model: - model is java bean/entity beans that represent the data being transmitted are received.
Controller: - Controller is a servlet that performs necessary manipulations to the model.
View: - is a screen representation of the model.

 Major benefits of using the MVC design pattern is separate the view & model this make it is possible to create are change views with out having to change the model.
 1) The browser makes a request to the controller servlet 2) Servlet performs necessary actions to the java bean model and forward the result to the jsp view. 3) The jsp formats the model for display and send the html results back top the web browser.

Q) Life-cycle of JSP
jspInit ()  container calls the jspInit() to initialize to servlet instance. It is called before any other method, and is called only once for a servlet instance.
_jspservice ()  container calls _jspservice () for each request, passing it the request and the response objects.
jspDestroy ()  container calls this when it decides take the instance out of service. It is the last method called n the servlet instance.
 jspInit () & jspDestroy () called only once so we cannot override these methods.

Q) Diff RequestDispatcher.forward(req, res) & RequestDispatcher.include(req, res) & & res.sendRedirect( url)

RequestDispatcher.include(req, res) RequestDispatcher.include() and both include content. The included page is inserted into the current page or output stream at the indicated point.

RequestDispatcher.forward(req, res) in forward req, res would be passed to the destination url and the control will return back to the same method, It will execute at “server side”. (Or) RequestDispatcher.forward(), the servlet engine transfers control of this HTTP request internally from your current servlet or JSP to another servlet or JSP or static file.

Forwards a client request to an HTML file, JSP file, or servlet for processing. When ever the client request will come it will take the request and process the request and the request to be forward to another page, it will also forward the http parameters of the previous page to the destination page. It will execute at “server side” so the browser unaware of the changes. If page1.jsp redirects to page2.jsp, the browser address bar will still show page1.jsp.

res.sendRedirect(url) when ever the client request will come just it will take the request and the request to be forwarded to another page. It cannot forward the http parameters of the previous page. This will work at client side.

Q) Diff res.sendRedirect( ) & req.forward( )

sendRedirect()  sends a redirect response back to the client's browser. The browser will normally interpret this response by initiating a new request to the redirect URL given in the response.
forward()  does not involve the client's browser. It just takes browser's current request, and hands it off to another servlet/jsp to handle. The client doesn't know that they're request is being handled by a different servlet/jsp than they originally called.
For ex, if you want to hide the fact that you're handling the browser request with multiple servlets/jsp, and all of the servlets/jsp are in the same web application, use forward() or include(). If you want the browser to initiate a new request to a different servlet/jsp, or if the servlet/jsp you want to forward to is not in the same web application, use sendRedirect ().

Q) Diff <%@ include file="file" %> &

<%@include file="abc.jsp"%> directive acts like C "#include", pulling in the text of the included file and compiling it as if it were part of the including file. The included file can be any type (including HTML or text). (Or) includes a jsp/servlet at compile time meaning only once parsed by the compiler.

include a jsp/servlet at request time it is not parsed by the compiler.

Q) Diff Jsp & Servlet

Internally when jsp is executed by the server it get converted into the servlet so the way jsp & servlet work is almost similar.
 In jsp we can easily separate the P.L with B.L, but in servlet both are combined.
 One servlet object is communicated with many numbers of objects, but jsp it is not possible.

Q) Can JSP be multi-threaded? How can I implement a thread-safe JSP page?
A) By default the service() method of all the JSP execute in a multithreaded fashion. You can make a page “thread-safe” and have it serve client requests in a single-threaded fashion by setting the page tag’s is Thread Safe attribute to false:
<%@ page is ThreadSafe=”false” %>

Q) How does JSP handle runtime exceptions?
A) 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\" %>.

Q) How do I prevent the output of my JSP or Servlet pages from being cached by the Web browser? And Proxy server?

Web browser caching
<%response.setHeader("Cache-Control","no-store");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
%>

Proxy server caching
response.setHeader("Cache-Control","private");

Q) What's a better approach for enabling thread-safe servlets & JSPs? SingleThreadModel Interface or Synchronization?
A) SingleThreadModel technique is easy to use, and works well for low volume sites. If your users to increase in the future, you may be better off implementing explicit synchronization for your shared data
Also, note that SingleThreadModel is pretty resource intensive from the server's perspective. The most serious issue however is when the number of concurrent requests exhausts the servlet instance pool. In that case, all the unserviced requests are queued until something becomes free.

Q) Servlet – to- JSP communicate?
public void doPost(HttpServletRequest req,
HttpServletResponse res)
{
Try{
govi.FormBean f = new govi.formBean();
string id = req.getParameter(“id”);
f.setName(req.getParameter(“name”));
f.setName(req.getParameter(“addr”));
f.setPersonalizationInfo(info);
req.setAttribute(“fBean”,f);
getServletConfig().getServletContext().getRequestDispatcher(“/jsp/Bean1.jsp”).forward(req, res);
} catch(Exception ex);
}
}

The jsp page Bean1.jsp can then process fBean,






Q) JSP- to-EJB Session Bean communicate?
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject, foo.AccountHome, foo.Account" %>
<%!
AccountHome accHome=null;
public void jspInit() {
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
Account acct = accHome.create();
acct.doWhatever(...);
%>

Q) Servlet output - to - another Servlet?

Servlet1
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/../srevlet2”) ;
rd.forward(req, res);

Servlet2

Public void service(servletRequest req, servletResponse res)
{
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher(“/../srevlet1”) ;
rd.include(req, res);
}

Q) How do you pass an InitParameter to a JSP?
<%!
ServletConfig cfg =null;
public void jspInit(){
ServletConfig cfg=getServletConfig();
for (Enumeration e=cfg.getInitParameterNames(); e.hasMoreElements();)
{
String name=(String)e.nextElement();
String value = cfg.getInitParameter(name);
System.out.println(name+"="+value);
}
}
%>

Q) How to view an image stored on database with JSP?
<%@ page language="java" import="java.sql.*,java.util.*"%>
<%
String image_id = (String) request.getParameter("ID");
if (image_id != null){
try
{
Class.forName("interbase.interclient.Driver");
Connection con = DriverManager.getConnection("jdbc:interbase://localhost/D:/InterBase/examples/Database/employee.gdb","java","java");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM IMMAGINE WHERE IMMAGINE_ID = " + image_id);
if (rs.next())
{
String dim_image = rs.getString("IMMAGINE_DIMENSIONE");
byte [] blocco = rs.getBytes("IMMAGINE_IMMAGINE");
response.setContentType("image/jpeg");
ServletOutputStream op = response.getOutputStream();
for(int i=0;i {
op.write(blocco[i]);
}
}
rs.close();
stmt.close();
con.close();
} catch(Exception e) {
out.println("An error occurs : " + e.toString());
}
}
%>

Q) How do I pass values from a list box (with multiple selects) to a Java Bean?
Consider the following HTML, which basically allows the user to select multiple values by means of a checkbox:

What's your favorite movie?

2001: A Space Odyssey
The Waterboy
The Tin Drum
Being John Malkovich


To handle HTML elements like checkboxes and lists which can be used to select multiple values, you need to use a bean with indexed properties (arrays). The following bean can be used to store the data selected from the above check box, since it contains an indexed property movies:

package foo;
public class MovieBean {
private String[] movies;
public MovieBean() {
String movies[] = new String[0];
}
public String[] getMovies() {
return movies;
}
public void setMovies(String[] m) {
this.movies = m;
}
}

Although a good design pattern would be to have the names of the bean properties match those of the HTML input form elements, it need not always be the case, as indicated within this example. The JSP code to process the posted form data is as follows:


<%! String[] movies; %>





<% movies = movieBean.getMovies();
if (movies != null) {
out.println("You selected:
");
out.println("
    ");
    for (int i = 0; i < movies.length; i++) {
    out.println ("
  • "+movies[i]+"
  • ");
    }
    out.println("
");
} else
out.println ("Don't you watch any movies?!");
%>

SERVLETS

Q) Servlet
Servlet is server side component, a servlet is small plug gable extension to the server and servlets are used to extend the functionality of the java-enabled server. Servlets are durable objects means that they remain in memory specially instructed to be destroyed.

Q) Servlet Life cycle

Public void init (ServletConfig config) throws ServletException
public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy ()

First the servlet is constructed and then initialized with the init () method, this will call only once.
Any request from client is handled initially by the service () method before delegating to the doXxx () methods in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy () method, then garbaged collected and finalized. This will call only once. 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.

Q) ServletConfig & ServletContext
ServletConfig  ServletConfig object is used to obtain configuration data when it is loaded.
ServletContext ServletContext is used to obtain information about environment on which a servlet is running.

Q) Where the servlets will be loaded?
A) Address space of webserver.

Q) Are Servlets multithread?
A) Yes, the servlet container allocates a thread for each new request for a single servlet. Each thread of your servlet runs as if a single user were accessing using it alone, but u can use static variable to store and present information that is common to all threads, like a hit counter for instance.

Q) What happens to System.out & System.err output in a Servlet?
A) System.out goes to 'client side' and is seen in browser, while System.err goes to 'server side' and is visible in error logs and/or on console.

Q) Session Tracking
Session tracking is the capability of the server to maintain the single client sequential list.

Q) Servlet chaining
Is a technique in which two are more servlets cooperating in servicing a single client sequential request, where one servlet output is piped to the next servlet output. The are 2 ways (i) Servlet Aliasing (ii) HttpRequest

Servlet Aliasing  allows you to setup a single alias name for a comma delimited list of servlets. To make a servlet chain opens your browser and give the alias name in URL.

HttpRequest construct a URL string and append a comma delimited list of servlets to the end.

Q) HttpTunnelling
Is a method used to reading and writing serializes objects using a http connection. You are creating a sub protocol inside http protocol that is tunneling inside another protocol.

Q) Diff CGI & Servlet
 Servlet is thread based but CGI is not
 CGI allow separate process for every client request, CGI is platform dependent and servlet is platform independent.

Q) Diff GET & POST
 GET & POST are used to process request and response of a client.
 Get method is the part of URL, we send less amount of data through Get. The amount of information limited is 240-255 characters.
 Using POST we can send large amount of data through hidden fields.
 Get is to get the posted html data; POST is to post the html data.

Q) Diff Http & Generic Servlet
 HttpServlet class extends Generic servlet, so Generic servlet is parent and HttpServlet is child.
 Generic is from javax.servlet package, HttpServlet is from javax.servlet.Http package.
 Http implements all Http protocols, Generic servlet will implements all networking protocol
 Http is stateless protocol, which means each request is independent of previous one; In generic we cannot maintain the state of next page only main state of current page.
 A protocol is said to be stateless if it has n memory of prior connection.
 Http servlet extra functionality is capable of retrieving Http header information.
 Http servlet can override doGet (), doDelete (), doGet (), doPost (), doTrace (), generic servlet will override Service () method only.

Q) The Structure and Deployment of Modern Servlet Web Applications
A) /WEB-INF/web.xml
/WEB-INF/lib/ [any required jar files]
/WEB-INF/classes/ [all class files]

WAR-> WARfile can be placed in a server’s webapps directory

Q) Servlet mapping?
A)
watermelon
myservlets.watermelon


watermelon
/fruit/summer/*


Q) Timeoutcan be overridden in web.xml?
A)
e.g.60


Q) Init parameter / Define context parameters?

HelloWorld2
examples.servlets.HelloWorld2

greeting
Welcome



Q) Tag Libraries?
A)
myTaglib
WEB-INF/myTLD.tld


Q) How many ways we can instantiate a class.?
A) Class.forName().newInstance() and new keyword

Q) Client pull & Server push?
Client pull
Client pull is similar to redirection, with one major difference: the browser actually displays the content from the first page and waits some specified amount of time before retrieving and displaying the content from the next page. It's called client pull because the client is responsible for pulling the content from the next page.
Client pull information is sent to the client using the Refresh HTTP header. This header's value specifies the number of seconds to display the page before pulling the next one, and it optionally includes a URL string that specifies the URL from which to pull. If no URL is given, the same URL is used. Here's a call to setHeader() that tells the client to reload this same servlet after showing its current content for three seconds: setHeader("Refresh", "3");
And here's a call that tells the client to display Netscape's home page after the three seconds:
setHeader("Refresh", "3; URL=http://home.netscape.com");

Server push
server push because the server sends, or pushes, a sequence of response pages to the client.With server push, the socket connection between the client and the server remains open until the last page has been sent.

Q) How can a servlet refresh automatically if some new data has entered the database?
A) you can use client side refresh are server push

Q) Session Tracking techniques

(i) URL Rewriting
(ii) Hidden form Field
(iii) Persistence Cookies
(iv) Session Tracking API
(v) User Authorization

URL Rewriting
URL rewriting is a technique in which the requested URL is modified with the session id.
URL rewriting is another way to support anonymous session tracking. With URL rewriting, every local URL the user might click on is dynamically modified, or rewritten, to include extra information.
http://server:port/servlet/Rewritten?sessionid=123 added parameter

Hidden form Field
Hidden form fields are HTML input type that are not displayed when read by the browser. They are sent back to the server when the form that contains them is submitted. You include hidden form fields with HTML like this:





In a sense, hidden form fields define constant variables for a form. To a servlet receiving a submitted form, there is no difference between a hidden field and a visible field.

Persistence Cookie
A cookie is a bit of information sent by a web server to a browser that can later be read back from that browser. When a browser receives a cookie, it saves the cookie and thereafter sends the cookie back to the server each time it accesses a page on that server, subject to certain rules. Because a cookie's value can uniquely identify a client, cookies are often used for session tracking. Because cookies are sent using HTTP headers, they should be added to the response before you send any content. Browsers are only required to accept 20 cookies per site, 300 total per user, and they can limit each cookie's size to 4096 bytes.

Sending cookies from a servlet

Cookie cookie = new Cookie ("ID", "123");
res.addCookie (cookie);

A servlet retrieves cookies by calling the getCookies () method of HttpServlet- Request:
public Cookie[] HttpServletRequest.getCookies()
This method returns an array of Cookie objects that contains all the cookies sent by the browser as part of the request or null if no cookies were sent. The code to fetch cookies looks like this:

Reading browser cookies from a Servlet

Cookie [] cookies = req. getCookies();
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
String name = cookies [i]. getName ();
String value = cookies [i]. getValue();
}
}

A cookie, mycookie, can be Deleted using the following scriptlet:
<%
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>

You can set the maximum age of a cookie with the cookie.setMaxAge(int seconds) method:
 Zero means to delete the cookie
 + value is the maximum number of seconds the cookie will live, before it expires
 - value means the cookie will not be stored beyond this browser session (deleted on browser close)

Session Tracking API
In Java the javax.servlet.http.HttpSession API handles many of the details of session tracking. It allows a session object to be created for each user session, then allows for values to be stored and retrieved for each session. A session object is created through the HttpServletRequest using the getSession() method:

HttpSession session = request.getSession(true);

This will return the session for this user or create one if one does not already exist.
Values can be stored for a user session using the HttpSession method putValue():

session.putValue("valueName", valueObject);

Session objects can be retrieved using getValue(String name), while a array of all value names can be retrieved using getValueNames(). Values can also be removed using removeValue(String valueName)



User Authorization
Servers can be set up to restrict access to HTML pages (and servlets). The user is required to enter a user name and password. Once they are verified the client re-sends the authorisation with requests for documents to that site in the http header.
Servlets can use the username authorisation sent with request to keep track of user data. For example, a hashtable can be set up to contain all the data for a particular user. When a user makes another request the user name can be used to add new items to their cart using the hashtable.

Q) Session
Session is a persistence network connection between client and server that facilitate the exchange of information between client and server. A session object created for each user persists on the server side, either until user closes the browser or user remains idle for the session expiration time.

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.

HttpSession session = req.getSession(true); //Creating a Session instance
session.putValue ("MyIdentifier1", count1); // Storing Value into session Object
session.putValue ("MyIdentifier2", count2);
session.getValue(MyIdentifier1); // Prints value of Count
session.removeValue(MyIdentifier1); // Removing Valuefrom Session Object

Q) Cookie advantages & Disadvantages
Advantages Persistence offer efficient way to implement session tracking for each client request a cookie can be automatically provide a clients session id.
Disadvantage The biggest problem with cookies is that browser do not always accept cookies. Some times browser does not accept cookies. Browser only requires accepting 20 cookies per page and they can limit the cookie size to 4096 bytes. It cannot work if the security level set too high in browser. Cookies are stored in a plain text format so every one can view and modify them. We can put maximum 300 cookies for entire application.

Q) Advantages of Sessions over Cookies & URLRewriting?
 Sessions are more secure and fast because they are stored at server side. But sessions has to be used combindly with cookies (or) URLRewriting for maintaining client id that is session id at client side.
 Cookies are store at client side so some clients may disable cookies so we may not sure that the cookies which we are maintaining may work or not, if cookies are disable also we can maintain sessions using URLRewriting.
 In URLRewriting we cannot maintain large data because it leads to network traffic and access may be become slow. Where in sessions will not maintain the data which we have to maintain instead we will maintain only the session id.

Q) encodeURL & encodeRedirectURL
These are methods of HttpResponse object, “encodeURL” is for normal links inside your HTML pages, “encodeRedirectURL” is for a link your passing to response.sendRedirect().

Q) SingleThread model
SingleThreadModel is a tag interface with no methods. In this model no two threads will execute concurrently the service method of the servlet, to accomplish this each thread uses a free servlet instance from the servlet pool. So any servlet implementing this can be considered thread safe and it is not required synchronize access to its variables.
(or)
If a servlet implements this interface, the server ensures that each instance of the servlet handles only one service request at a time. Servers implement this functionality by maintaining a pool of servlet instances and dispatching incoming requests to free servlets within the pool. SingleThreadModel provides easy thread safety, but at the cost of increased resource requirements as more servlet instances are loaded at any given time.

public interface SingleThreadModel {
}



Q) Request Headers
User-agent: - Gives the information about client software, browser name, version and information about the machine on which it is running.
request.getHeader(“user-agent”);

Q) Why there is no constructor in servlet?
A) A servlet is just like an applet in the respect that it has an init() method that acts as a constructor, an initialization code you need to run should e place in the init(), since it get called when the servlet is first loaded.

Q) Why do you need both GET & POST methods in servlets?
A) A single servlet can be called from different HTML pages, so different method calls can be possible.