Accessing an EJB from Struts Action class

Hi All,

Sorry if this a repetitive question.

When I am trying to access a stateless Session bean from a struts Action class, I am getting NullPointerException. It is a very simple application as I am a newbie in EJB. Please see my code below.

My Local Interface:

@Local

publicinterface UserValidatorLocal{

publicboolean validateUser(String username, String password);

}

My Bean:

@Stateless(name="validator")

publicclass UserValidatorimplements UserValidatorLocal{

publicboolean validateUser(String username, String password){

if (username.equalsIgnoreCase("jegan") && password.equalsIgnoreCase("jegan")){

returntrue;

}else{

returnfalse;

}

}

}

My Action class Method:

public ActionForward perform(ActionMapping mappings,

ActionForm form, HttpServletRequest req,

HttpServletResponse res)throws IOException, ServletException{

String username = ((LoginForm) form).getUsername();

String password = ((LoginForm) form).getPassword();

boolean loginStatus = validator.validateUser(username, password);

ActionForward forward;

if (loginStatus){

forward = mappings.findForward("success");

}else{

forward = mappings.findForward("failure");

}

return forward;

}

The exception comes at the line

boolean loginStatus = validator.validateUser(username, password);

Do I have to add anything in the DD file? Please help me.

Thanks in Advance.

[2843 byte] By [jeganspa] at [2007-11-27 10:12:13]
# 1

Since this kind of class can not directly use Java EE 5 environment annotations, you'll need to retrieve

the ejb reference via a component environment lookup.You first need to define the ejb dependency. That can be done either by using @EJB on some other managed class (e.g. a servlet) within the same web app or by defining an ejb-local-ref in web.xml.

Then, you lookup the local ejb reference via java:comp/env. Assuming the name of the reference is "validator_ref", it would be :

UserValidatorLocal ref = (UserValidatorLocal)

new InitialContext().lookup("java:comp/env/validator_ref")

We have an EJB FAQ entry with more details here :

https://glassfish.dev.java.net/javaee5/ejb/EJB_FAQ.html#POJOLocalEJB

--ken

ksaksa at 2007-7-28 15:18:55 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...
# 2

Thanks for your reply Ken,

I will try this.

- Jegan

jeganspa at 2007-7-28 15:18:55 > top of Java-index,Enterprise & Remote Computing,Enterprise Technologies...