EJB instance Tutorial Notes (2)

EJB instance Tutorial Notes (2)

EJB3 tutorial e-book example of byLiHuoming.pdf Notes

2.4 Stateful Session Bean (Stateful Bean) development needs of each user has their own instance, this instance of the influence by other users. Stateful Bean in the Bean for each instance of the service life of only one user, Stateful Session Bean maintains the user's information.

For stateful Session Bean, the user once each call lookup () will create a new Bean instance, if you want to use a Bean instance, must be in the client cache stub.

Custom Interface Cart.java as follows:
package com.sillycat.ejb;

import java.io.Serializable;
import java.util.List;

public interface Cart extends Serializable (
public void AddBuyItem (String productName);
public List <String> getBuyItem ();
)
Bean file CartBean.java defined as follows:
package com.sillycat.ejb.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Remote;
import javax.ejb.Stateful;

import com.sillycat.ejb.Cart;

@ Stateful
@ Remote (Cart.class)
public class CartBean implements Cart (

private static final long serialVersionUID = 4371026853912745479L;

private List <String> buyitems = new ArrayList <String> ();

public void AddBuyItem (String productName) (
buyitems.add (productName);
)

public List <String> getBuyItem () (
return buyitems;
)

)

Unit Testing CartTest.java
package com.sillycat.ejb;

import static org.junit.Assert.assertEquals;

import java.util.List;

import javax.naming.InitialContext;

import org.junit.BeforeClass;
import org.junit.Test;

public class CartTest (
protected static Cart cart;

@ BeforeClass
public static void setUpBeforeClass () throws Exception (
InitialContext ctx = new InitialContext ();
cart = (Cart) ctx.lookup ("CartBean / remote");
)

@ Test
public void testBuyItems () (
cart.AddBuyItem ("boring ah");
cart.AddBuyItem ("Actually, I like the writing process");
List <String> items = cart.getBuyItem ();
assertEquals (2, items.size ());
)
)

Examples of the original book, is to ask, if you want to use the same instance, stub, Ye Jiu Shi lookup get to Cunfang In session in the cart, Oh, Then I Xiang other ways it, put a cart into the session not what I want to see of.

2.5-activation mechanism (Activation mechanism)
Stateful Bean each in its life cycle only serve one user, on a state Bean instance pooling mechanism used is meaningless.

2.6 Stateful Session Bean Life Cycle
stateful Session Bean life cycle consists of three states: does not exist, method-ready and passivated. method-ready state and the method-ready pool significantly different between.

2.7 EJB call mechanism called remote or local interface method, interface, use the stub (stub) object, the stub implementation of the session bean's remote or local interface. It is responsible for calls through the network to a remote EJB container, or to route requests to the local JVM in the EJB container. Stub is used during the deployment of java.lang.reflect.Proxy JDK dynamically generated.

2.8 How to change the JNDI name of the Session Bean
JBOSS provide @ LocalBinding and @ RemoteBinding, examples are as follows OperationBean.java:
package com.sillycat.ejb.impl;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;

import org.jboss.ejb3.annotation.LocalBinding;
import org.jboss.ejb3.annotation.RemoteBinding;

import com.sillycat.ejb.Operation;
import com.sillycat.ejb.OperationLocal;

@ Stateless
@ Remote (Operation.class)
@ RemoteBinding (jndiBinding = "easyejb / OperationRemote")
@ Local (OperationLocal.class)
@ LocalBinding (jndiBinding = "easyejb / OperationLocal")
public class OperationBean implements Operation, OperationLocal (

private int total = 0;

public int Addup () (
total + +;
return total;
)

)

If you are using weblogic / Sun Application Server / Glassfish, etc., using the @ Stateless.mappedName ().
Because the JNDI name and manufacturer, use the JNDI name defined comment will be transplanted, it is suggested to use ejb-jar.xml deployment descriptor file to define. Documents placed in the jar's META-INF directory.

2.9 Session Bean life cycle events
@ PostConstruct
When Bean instance of an object to complete, the labeling method of this note will be called immediately. (Stateful and stateless)
@ PreDestroy
Container destroyed a useless or before the expiration of the bean instance of the call. (Stateful and stateless)
@ PrePassivate
Bean instance of a state too long idle event occurs passivation (passivate). Note marked this way will be called before passivation. Bean instance to be passivated after a period of time, without user action on the bean instance, the container will remove it from the hard disk. After the call for the bean method, the container will throw an exception. (With state)
@ PostActivate
When the client re-used stateful bean has been passivated when, EJB container will re-instantiate a Bean instance, and from the hard drive will resume the state before, marked the approach of this note will be called when the activation to complete. (With state)
@ Init
It is different from @ PostConstruct more @ Init annotation method can simultaneously exist in a stateful session bean, but only one instance of each bean annotated @ Init method is called. @ PostConstruct after the @ Init is called. (With state)
@ Remote
When the client calls the mark of the @ Remote annotation method, the container will be the end of the method of implementation, the bean instance to delete.

Note the callback method must return void, with no arguments, and can not throw any checked exception.

Sample interface file LifeCycle.java:
package com.sillycat.ejb;

public interface LifeCycle (

public String say ();

public void stopSession ();
)

EJB class LifeCycleBean.java as follows:
package com.sillycat.ejb.impl;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Init;
import javax.ejb.PostActivate;
import javax.ejb.PrePassivate;
import javax.ejb.Remote;
import javax.ejb.Remove;
import javax.ejb.Stateful;

import com.sillycat.ejb.LifeCycle;

@ Stateful
@ Remote (LifeCycle.class)
public class LifeCycleBean implements LifeCycle (
public String say () (
try (
Thread.sleep (1000 * 10);
) Catch (InterruptedException e) (
e.printStackTrace ();
)
return "stateful Session Bean Life Cycle";
)

@ Init
public void initialize () (
System.out.println ("@ Init event");
)

@ PostConstruct
public void construct () (
System.out.println ("@ PostConstruct event");
)

@ PreDestroy
public void exit () (
System.out.println ("@ PreDestroy event");
)

@ PrePassivate
public void serialize () (
System.out.println ("@ PrePassivate event");
)

@ PostActivate
public void activate () (
System.out.println ("@ PostActivate event");
)

@ Remove
public void stopSession () (
System.out.println ("@ Remove Event");
)
)
Test page ejbTest2.jsp as follows:
<% @ Page contentType = "text / html; charset = UTF-8"%>
<% @ Page import = "com.sillycat.ejb .*, javax.naming .*"%>
<%

try (
LifeCycle lifecycle = (LifeCycle) session.getAttribute ("lifecycle");
if (lifecycle == null) (
InitialContext ctx = new InitialContext ();
lifecycle = (LifeCycle) ctx.lookup ("LifeCycleBean / remote");
session.setAttribute ("lifecycle", lifecycle);
)
out.println (lifecycle.say ());
out.println ("<BR> Please observe Jboss console output. waiting 10 minutes, the container will be passive in this session Bean, @ PrePassivate annotated method will perform <BR>");
out.println ("<font color=red> stopSession way you can call a session Bean instance to delete. When you delete a session Bean will trigger @ PreDestroy event <BR> </ font>");
/ *
lifecycle.stopSession ();
* /
) Catch (Exception e) (
out.println (e.getMessage ());
)
%>

Log situation:
Click here for the first time:
13:47:35,933 INFO [STDOUT] @ PostConstruct events
13:47:35,935 INFO [STDOUT] @ Init event
13:57:02,775 INFO [STDOUT] @ PrePassivate event to refresh the page:
14:10:56,584 INFO [STDOUT] @ PostActivate events rather strange here is the @ PostConstruct event even in front of the @ Init. Ha ha.

2.10 Interceptor (Interceptor)
Interceptor can intercept Session Bean and Message-driven bean's method call, or life-cycle events. Blocker used to encapsulate the common behavior of applications, so that these acts and business logic. Interceptor may be the same bean class method or an external class.
Interface Example HelloChina.java:
package com.sillycat.ejb;

public interface HelloChina (
public String sayHello (String name);
public String myname ();
)

EJB's Bean as HelloChinaBean.java:
package com.sillycat.ejb.impl;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.interceptor.Interceptors;

import com.sillycat.ejb.HelloChina;
import com.sillycat.ejb.HelloChinaLocal;

@ Stateless
@ Remote (HelloChina.class)
@ Local (HelloChinaLocal.class)
@ Interceptors (HelloInterceptor.class)
/ / @ Interceptors ((A.class, B.class))
public class HelloChinaBean implements HelloChina, HelloChinaLocal (

public String myname () (
return "sillycat";
)

/ / @ Interceptors (HelloInterceptor.class) interception of a method
public String sayHello (String name) (
return name + ", hello ejb.";
)

)
Here @ Interceptors ((A.class, B.class)) is the number of interceptor classes written, another label could also be written in a particular method, that only the intercept of this method.
Interceptor class HelloInterceptor.java as follows:
package com.sillycat.ejb.impl;

import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;

public class HelloInterceptor (

@ AroundInvoke
public Object log (InvocationContext ctx) throws Exception (
System.out.println ("*** HelloInterceptor intercepting ");
long start = System.currentTimeMillis ();
try (
if (ctx.getMethod (). getName (). equals ("sayHello")) (
System.out.println ("*** sayHello has been called! *** ");
String name = (String) ctx.getParameters () [0];
/ / Get the first parameters
if ("boss". equals (name)) (
throw new Exception ("the method will not go any further.");
)
)
if (ctx.getMethod (). getName (). equals ("myname")) (
System.out.println ("*** myname has been called! *** ");
)
return ctx.proceed ();
) Catch (Exception e) (
throw e;
) Finally (
long time = System.currentTimeMillis () - start;
System.out.println ("use Time:" + time + "ms");
)
)
)
If you throw an error halfway, there is no call ctx.proceed (), then the business will not call the final method.
if ("boss". equals (name)) (
throw new Exception ("the method will not go any further.");
)
javax.interceptor.InvocationContext encapsulates the client calls business methods.
getTarget () call to the bean instance to point back
getMethod () point to the business method is blocked
getParameters () business method to obtain the parameters of the intercepted
setParameters () business method to set the parameters of the intercepted
getContextData () method returns a Map object, which in the method call can be accessed during the period. Located within the same method calls between different interceptors, you can use it to deliver context-sensitive data.

Our test class HelloChinaTest.java as follows:
package com.sillycat.ejb;

import javax.naming.InitialContext;

import org.junit.BeforeClass;
import org.junit.Test;

public class HelloChinaTest (

protected static HelloChina helloChina;

@ BeforeClass
public static void setUpBeforeClass () throws Exception (
InitialContext ctx = new InitialContext ();
helloChina = (HelloChina) ctx.lookup ("HelloChinaBean / remote");
)

@ Test
public void testSayHello () (
System.out.println (helloChina.sayHello ("sillycat"));
System.out.println (helloChina.myname ());
System.out.println (helloChina.sayHello ("boss"));
)
)

Intercept method can also type directly into the business methods inside the class methods directly to the block copy in the past on the line, plus @ AroundInvoke label.

Default interceptors EJB module in a lot of EJB, EJB method if the interception of all, we must re-configure the ejb-jar.xml, are here to support wildcards.

If you disable the interceptor configuration ejb-jar.xml are added to many EJB interceptor, but some of the EJB we do not want to block, then we should use the @ ExcludeDefaultInterceptors comment.

@ Stateless
@ Remote (HelloChina.class)
@ Local (HelloChinaLocal.class)
@ ExcludeDefaultInterceptors

Here is not only the implementation of the default interceptors, the interceptors if the definition itself, or to perform.

Intercept lifecycle events
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of EJB instance Tutorial Notes (2)

  • First Hibernate Example

    Curd a simple example. Source does not contain the dependent libraries, or playing too much of the package. PO object Note: One must have the default constructor 2 non-final modified. Otherwise useless lazy loading. UserDAOImpl category code, and other co

  • Struts2 + hibernate + spring problem user log in

    dao layer services layer action jsp <tr> <td align="center"> <b> user name: </ b> </ td> <td> <s: textfield name = "czyNumber" cssClass = "textstyle" theme = "simple" size = &q

  • Hibernate secondary cache

    Hibernate cache: 2-bit cache, also known as process-level cache or SessionFactory level cache, secondary cache can be shared by all of the session Cache configuration and the use of: Will echcache.xml (the document code in hibernate package directory ...

  • Hibernate's lazy strategy

    hibernate Lazy strategy can be used in: <class> tag, it can be true / false Tags can <PROPERTY> values true / false type of necessary tools to enhance <set> <list> can tag values true / false / extra <many-to-one> <on ...

  • spring struts2.0 hibernate bug killer 1

    exception There is no Action mapped for namespace / and action name checkLogin. - [Unknown location] com.opensymphony.xwork2.DefaultActionProxy.prepare (DefaultActionProxy.java: 186) org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries