Tuesday, August 17, 2010

EJB interview questions



EJB Questions

Q: What is the J2EE?
The J2EE is a set of coordinated specifications and practices that together enable solutions for developing, deploying and managing multi-tier server-centric applications.

Q) What is enterprise java bean? Why ejb?
A) It’s a collection of java classes and xml descriptor files bundled together as a unit. The java classes must provide certain rules and call back methods as per ejb specifications.
When the application is so complex and requires certain enterprise level services such as concurrency, scalability, transaction services, resource pooling, security, fail-over, load-balancing ejb is the right choice.

Q) New in EJB 2.1?
 Message-driven beans (MDBs): can now accept messages from sources other than JMS.
 EJB query language (EJB-QL): many new functions are added to this language: ORDER BY, AVG, MIN, MAX, SUM, COUNT, and MOD.
 Support for Web services: stateless session beans can be invoked over SOAP/HTTP. Also, an EJB can easily access a Web service using the new service reference.
 EJB timer service: a new event-based mechanism for invoking EJBs at specific times.
 Many small changes: support for the latest versions of Java specifications, XML schema, and message destinations.

Q) Application server & Web server
 A.S is a generalized server for running more than one application like ejb, rmi, jsp and servlets.
 W.S 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.
 W.S understands and supports only HTTP protocol whereas an Application Server supports HTTP, TCP/IP and many more protocols.
 A.S manage transactions, security, persistence, clustering, caching, 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) What does Container contain?
A) 1. Support for Transaction Management, 2. Support for Security 3. Support for Persistence 4. Support for management of multiple instances (Instance passivation, Instance Pooling, Database connection pooling)
5. Life Cycle Management

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.

Q) Statefull Session Bean & Stateless Session Bean
Stateless Session Bean Stateful Session Bean
Stateless session bean these are single request business process is one that does not require state to be maintained across method invocation. Stateless session bean cannot hold the state. 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.
There should be one and only one create method that to without any argument in the home interface. There can be one or more create methods with or without arguments in the Home Interface.
Stateless session bean instance can be pooled. Therefore “n” number of beans can cater to n+1 number of clients. Statefull session bean do not have pooling concept. Stateful bean will be given individual copy for every user.
Stateless bean will not be destroyed after client has gone. Stateful bean will be destroyed once the client has gone (or after session time out)
If the business last only for a single method call, S.S.B are suitable If the business process spans multiple invocations there by requiring a conversational then S.S.B will be ideal choice.
Stateless session bean cannot have instance variable Stateful session bean will have instance variable and state is maintained in these instance variables
EjbRemove() method does not destroy the bean , it remains in the pooled state. Stateful bean can be destroyed by calling the ejbRemove() method



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 database. In entity bean deployment descriptor you specify which fields that the container should manage. The transactions 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) 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) Diff MDB & Stateless Session beans?
- MDB’s process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
- MDB have no H.I / R.I, and therefore cannot be directly accessed by internal or external clients. Clients interact with MDB’s only indirectly, by sending a message to a JMS Queue or Topic.
- Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary
-The Container maintains the entire lifecycle of a MDB; instances cannot be created or removed as a result of client requests or other API calls.

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) When to choose 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 database.
 S.B for application logic.

Q) When to choose CMP & BMP?
CMP is used when the persistent 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 persistence is used when there is no “one to one” mapping of the table and a complex query retrieving 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) How do Stateful Session beans maintain consistency across transaction updates?
A) S.S.B maintain data consistency by updating their fields each time a transaction is committed. To keep informed of changes in transation status, a S.S.B implements the SessionSynchronization interface. Container then calls methods of this interface as it initiates and completes transactions involving the bean.

Q) Can't stateful session beans persistent? Is it possible to maintain persistence temporarily in stateful sessionbeans?
A) Session beans are not designed to be persistent, whether stateful or stateless. A stateful session bean instance typically can't survive system failures and other destructive events.
Yes, it is possible using Handle.

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) 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?
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 develop an Entity Bean without implementing the create() method in the home interface?
As per the specifications, there can be 'ZERO' or 'MORE' create() methods defined in an Entity Bean. In cases where create() method is not provided, the only way to access the bean is by knowing its primary key, and by acquiring a handle to it by using its corresponding finder method. In those cases, you can create an instance of a bean based on the data present in the table. All one needs to know is the primary key of that table. i.e. a set a columns that uniquely identify a single row in that table. Once this is known, one can use the 'getPrimaryKey()' to get a remote reference to that bean, which can further be used to invoke business methods.

Q) How do you determine whether two entity beans are the same?
A) By invoking the EntityBean.isIdentical method. This method should be implemented by the entity bean developer to determine when two references are to the same object.

Q) How can you capture if findBy method returns more than one row?
A) If finder method returns more than one row, create or instantiate an object (which has instance variable equal to number of columns to be stored) each time and add the object to vector that stores. Vector stores only the memory address not object reference. So every time when you instantiate and store object into vector a separate memory address will be allocated and the same is stored in the vector.

Q) Diff Context, InitialContext & SessionContext & EntityContext
javax.naming.Context is an interface that provides methods for binding a name to an object. It's much like the RMI Naming.bind() method.

javax.naming.InitialContext is a Context and provides implementation for methods available in the Context interface.

Where as SessionContext is an EJBContext object that is provided by the EJB container to a SessionBean in order for the SessionBean to access the information and/or services or the container.

There is EntityContext too which is also and EJBContext object that'll be provided to an EntityBean for the purpose of the EntityBean accessing the container details. In general, the EJBContext (SessionContext and EntityContext), AppletContext and ServletContext help the corresponding Java objects in knowing about its 'context' [environment in which they run], and to access particular information and/or service. Where as, the javax.naming.Context is for the purpose of 'NAMING' [by the way of referring to] an object.

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 you use Bean-Managed Persistence(BMP), map the bean to tables manually. Consider applying the DAO design pattern to accomplish this.
If you 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(SessionContext 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, i.e. 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, and 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 requests.

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) 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) 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) What is the need of Remote and Home interface. Why cant it be in one?
The home interface is your way to communicate with the container, that is who is responsible of creating, locating even removing one or more beans. The remote interface is your link to the bean, that will allow you to remotely access to all its methods and members. As you can see there are two distinct elements (the container and beans) and you need two different interfaces for accessing to both of them.

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




Q) Session Bean Example

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) Entity Bean Example

Home.java (Home Interface)
package test;

public interface Home extends javax.ejb.EJBHome {
public String hello() throws RemoteException;
public int add(int a, int b) throws RemoteException;
public HomeObj findByPrimaryKey(String a) throws RemoteException, FinderException;
}

HelloObj.java (Remote Interface)
package test;

public interface HelloObj extends javax.ejb.EJBObject {
}

HelloBean.java (Bean class)
package test;
import javax.ejb.*;

public class HelloBean extends com.caucho.ejb.AbstractEntityBean {
public String ejbHomeHello()
{
return "Hello, world";
}

public int ejbHomeAdd(int a, int b)
{
return a + b;
}

public String ejbFindByPrimaryKey(String key) throws FinderException
{
throw new FinderException("no children");
}
}

Client
package test.entity.home;
import javax.naming.*;

public class HomeServlet extends GenericServlet {
Home home;

public void init() throws ServletException
{
try {
Context env = (Context) new InitialContext().lookup("java:comp/env");
home = (Home) env.lookup("ejb/home");
} catch (Exception e) {
throw new ServletException(e);
}
}

public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException
{
PrintWriter pw = res.getWriter();
try {
pw.println("message: " + home.hello() + "");
pw.println("1 + 3 = " + home.add(1, 3) + "");
pw.println("7 + 1 = " + home.add(7, 1) + "");
} catch (Exception e) {
throw new ServletException(e);
}
}
}



Q) How do you configure a session bean for bean-managed transactions?
A) By set transaction-attribute in the xml file or in the deployment descriptor.

JSP INTERVIEW QUESTIONS

JSP Tutorial

1.What are the advantages of JSP over Servlet?
JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.

2.What is the life-cycle of JSP?
When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
Translation
Compilation
Loading the class
Instantiating the class
jspInit() invocation
_jspService() invocation
jspDestroy() invocation


3.What is the jspInit() method?
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.

4.What is the _jspService() method?
SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.

5.What is the jspDestroy() method?
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.

6.What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().

7.How can I override the jspInit() and jspDestroy() methods within a JSP page?
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
. . .
}
%>
<%!
public void jspDestroy() {
. . .
}
%>

8.What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:
request
response
pageContext
session
application
out
config
page
exception
The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.
Check more about implicit objects
9.What are the different types of JSP tags?
The different types of JSP tags are as follows:


10.What are JSP directives?
JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
They are used to set global values such as a class declaration, method implementation, output content type, etc.
They do not produce any output to the client.
Directives are always enclosed within <%@ ….. %> tag.
Ex: page directive, include directive, etc.








11.What is page directive?
A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
Typically, the page directive is found at the top of almost all of our JSP pages.
There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
The syntax of the include directive is: <%@ page attribute="value">
Example:<%@ include file="header.jsp" %>

12.What are the attributes of page directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
import: It specifies the packages that are to be imported.
session: It specifies whether a session data is available to the JSP page.
contentType: It allows a user to set the content-type for a page.
isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.

13.What is the include directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
The include directive is used to statically insert the contents of a resource into the current JSP.
This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
The syntax of the include directive is as follows:
<%@ include file = "FileName" %>
This directive has only one attribute called file that specifies the name of the file to be included.

14.What are the JSP standard actions?
The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
Ex: include, forward, useBean,etc. object

15.What are the standard actions available in JSP?
The standard actions available in JSP are as follows:
: It includes a response from a servlet or a JSP page into the current page. It differs from an include directive in that it includes a resource at request processing time, whereas the include directive includes a resource at translation time.
: It forwards a response from a servlet or a JSP page to another page.
: It makes a JavaBean available to a page and instantiates the bean.
: It sets the properties for a JavaBean.
: It gets the value of a property from a JavaBean component and adds it to the response.
: It is used in conjunction with ;, ; to add a parameter to a request. These parameters are provided using the name-value pairs.
: It is used to include a Java applet or a JavaBean in the current JSP page.

16.What is the standard action?
The standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.

17.What are the scopes available in ?
The scopes available in are as follows:
page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
session scope: It specifies that the object will be available throughout the session with a particular client.

18.What is the standard action?
The standard action forwards a response from a servlet or a JSP page to another page.
The execution of the current page is stopped and control is transferred to the forwarded page.
The syntax of the standard action is :

Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.
If anything is written to the output stream that is not buffered before , an IllegalStateException will be thrown.
Note : Whenever we intend to use or in a page, buffering should be enabled. By default buffer is enabled.

19.What is the standard action?
The standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the standard action is as follows:

Here, targetPage is the page to be included in the current JSP.

20.What is the difference between include directive and include action?
Include directive Include action
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user.
The include directive is used to statically insert the contents of a resource into the current JSP. The include standard action enables the current JSP page to include a static or a dynamic resource at runtime.
Use the include directive if the file changes rarely. It’s the fastest mechanism. Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested.






21.Differentiate between pageContext.include and jsp:include?
The standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include() method always flushes the output of the current page before including the other components, whereas flushes the output of the current page only if the value of flush is explicitly set to true as follows:


22.What is the jsp:setProperty action?
You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:

...

In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.

A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:

...
property="someProperty" ... />

Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.


23.What is the jsp:getProperty action?
The action is used to access the properties of a bean that was set using the action. The container converts the property to a String as follows:
If it is an object, it uses the toString() method to convert it to a String.
If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
The syntax of the method is:
Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the action before using the action.


24.What is the standard action?
The standard action is used with or to pass parameter names and values to the target resource. The syntax of the standard action is as follows:


25.What is the jsp:plugin action ?
This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.

26.What are scripting elements?
JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
1. Expressions of the form <%= expression %> that are evaluated and inserted into the output,
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method,
3. Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.

27.What is a scriptlet?
A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time.

28.What are JSP declarations?
As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.

29.What is a JSP expression?
A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.

30.How is scripting disabled?
Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:

*.jsp
true

jdbc quick review

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


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


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


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


5.What are the main components of JDBC ?
The life cycle of a servlet consists of the following phases:
DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.
Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.
Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.
Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to query execution.


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





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



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



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



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



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



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

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

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

15.What are types of JDBC drivers?
There are four types of drivers defined by JDBC as follows:
Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.
Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.
Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.
Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.
Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.






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

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


18.Which is the right type of driver to use and when?
Type I driver is handy for prototyping
Type III driver adds security, caching, and connection control
Type III and Type IV drivers need no pre-installation
Note: Preferred by 9 out of 10 Java developers: Type IV. Click here to learn more about JDBC drivers.

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

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

21.What are the types of resultsets?
The values are defined in the class java.sql.Connection and are:

TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can be advanced only in the forward direction.

TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.

TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

Note: A TYPE_FORWARD_ONLY resultset is always insensitive.

22.What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?
TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE

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

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


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

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

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


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

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

Saturday, March 27, 2010

OBC -creamylayer Some mandotary Explanation

For more details visit--
www.obcguru.com



Candidate‟s creamy layer status is always determined by parent‟s (father, mother) status and never by status of self, husband, spouse or brother/sister.

(1) For whole life of a candidate, creamy layer status is determined by parent‟s (father, mother) status and never by status of self, husband, spouse or brother/ sister.


Status or income of a “candidate” availing or applying for OBC reservation is never counted for creamy layer purpose
.

(2) Out of the six rules, each rule of creamy layer criteria dated 08.09.1993 issued by Ministry of Personnel Govt of India New Delhi starts from: -
“SONS & DAUGHTERS OF SO & SO...will be treated as creamy layer”.
Means candidate‟s creamy layer status is always determined by parent‟s (father, mother) status.



(3) Para No. 08 of creamy clarifications dated 14.10.2004 issued by Ministry of Personnel Govt of India New Delhi clearly speaks that: -
8. “Creamy layer status of a candidate is determined on the basis of the status of his parents and not on the basis of his own status or income or on the basis of status or income or on the basis or status or income of his/her spouse. Therefore, while determining the creamy layer status of a person the status or the income of the candidate himself or of his/her spouse shall not be taken into account.”

(4) The Explanation (b) of Rule II A of creamy layer criteria dated 08.09.1993 issued by Ministry of Personnel Govt of India New Delhi clearly speaks that: -
Provided that the rule of exclusion shall not apply in the following cases:-
(b) A lady belonging to OBC category has got married to a Class I officer, and may herself like to apply for job.
(5) OBC candidate has to submit the details (status/income) of “father” and “mother” only and not of the “self” in “Application form prescribed to get OBC certificate”.
Kindly see the correct „application form‟ prescribed by Ministry of Personnel Govt of India New Delhi vide Govt order dated 15.11.1993, available at www.obcguru.com.
(6) EVEN THERE IS NO NEED TO LEAVE THE EXISTING JOB FOR A CANDIDATE, TO BECOME A NON-CREAMY LAYER CANDIDATE FOR ANY OBC RESERVATION.
(7) This reservation facility is actually based on that “what status a father-mother has given to a child”.
(8) If you are selected for, the post of IPS trough UPSC civil services examination and want to apply again to become an IAS, even though you are eligible for OBC reservation on the basis of parent‟s (father, mother) status.