Servlet to call Session beans during runtime
Hi,
I hope anyone can help me with this.
i'm using a session bean in a servlet. anyone can advise me should i call the bean's create() in the servlet init() or in the doService()?
And can also tell me, whether it is also possible to call the session beans runtime.
Thanks a lot.
Re: Servlet to call Session beans during runtime
Session Bean interacts with the client and is non persistent in nature. If server crashes all the data stored in Session Bean are lost. But Entity Beans are persistent in nature and in case sever crashes Entity Bean reconstruct its data from the underlying database. Session Beans are used to handle the client request and manage the session and Entity Beans are used to do database processing.
Here you can have the following Example on it.
Code:
/*
* MyTestSession.java
*
*/
package test.session;
import java.lang.*;
import java.rmi.RemoteException;
import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
public interface MyTestSession extends javax.ejb.EJBObject{
public java.lang.String SayHello() throws java.rmi.RemoteException;
}
Re: Servlet to call Session beans during runtime
To answer your first question ... if you've ever heard of the MVC (Model-view-controller) pattern or n-tier pattern of development, then the JSP/Servlets are the 'View' part of it - or the 'Presentation' layer in the n-tier system. Meaning, they are primarily responsible just for displaying the data & accepting input. To some extent JSP/Servlets can be 'Controllers', i.e. they can control/define the flow of an application.
However, it is bad design to put your 'Model' part (i.e. the 'business logic' part) in JSP/Servlets. That is what you use the EJBs for.
My advice ? Try to put display logic in JSP/Servlets & put your business logic in EJBs - easy as pie.
Re: Servlet to call Session beans during runtime
Here i will provide some guidelines, there are many way to access your EJB3 session/entity bean. Also You can use Singlton ServiceLocator(J2EE design pattern) to look up the EJB session bean from the JNDI Naming Server.
So your application flow would be something like this:
JSP (View) -> Servlet (Controller) -> Business Delegate (J2EE Design Pattern) -> Service Locator (J2EE Design Pattern) -> Session Bean (Business Tier)
Example:
EJB3 session bean
Code:
//session interface
package com.myapp;
import javax.ejb.Stateless;
public interface HelloEJB3 {
public String sayHello();
}
//session implementation
package com.myapp;
import java.ejb.Stateless;
@Stateless
@local
public class HelloEJB3Bean implements HelloEJB3 {
private String greeting = “Hello, EJB3!”;
public String sayHello() { return greeting; }
}