EJB injection in servlet fails
Asked Answered
P

1

5

I am trying to inject an EJB stateless bean in to a servlet, but the servlet throws a NullPointerExcetion. I am using JBOSS to deploy the EJB and servlet.

I am relatively new to the Java world, so I am posting the steps I followed.

Interface

package MavenEJB.Bidding`
import javax.ejb.Local;

@Local
public interface PlaceBid {
 public String AddBid();
}

Bean

package MavenEJB.Bidding;
import javax.ejb.Stateless;
@Stateless(name="PlaceBid")
public class PlaceBidBean implements PlaceBid {
 public PlaceBidBean(){}

 /**
  * Include logic to add the bid 
  */

 public String AddBid(){
  return "Placed bid using EJB"; 
 }
}

I created a jar file of the bean using maven and I copied the jar file to "deploy" directory of JBOSS. I am able to see the bean deployed in the JMX console.

Global JNDI Namespace in JMX console

+- PlaceBid (class: org.jnp.interfaces.NamingContext)
  |   +- local (proxy: $Proxy63 implements interface MavenEJB.Bidding.PlaceBid,interface org.jboss.ejb3.JBossProxy)

My servlet code

public class PlaceBidServlet extends HttpServlet {

    @EJB
    private PlaceBid placeBid;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("text/html");

  PrintWriter out = response.getWriter();
     out.println("<HTML>");
     out.println("<HEAD><TITLE>Hello</TITLE></HEAD>");
     out.println("<BODY>");
  out.println("Output from EJB" +placeBid.AddBid());

     //out.println("Output from EJB" );
     out.println("</BODY></HTML>");  
 }

....
}

When I point to the URL of my servlet, I get NullPointerException. When I comment the bean and print something else, it prints fine. So I am sure the problem is with the EJB Dependency Injection in the servlet. I tried many solutions suggested else where, nothing really worked, someone please help me.

Purgatory answered 14/12, 2010 at 0:34 Comment(0)
P
7

After a lot of hours I found the problem, I am posting it so someone else can benefit. The problem is, I was using JBOSS 4.2.3 and as this post http://community.jboss.org/message/410211 suggests jboss 4.2.x does not support EJB injection in servlets.

I used Jboss 5.1, also if both the servlet and EJB are not in a single ear package, one must use mappedName to the EJB Injection. I had the servlets in a WAR and the EJB in a separate Jar. Check this post for more details http://community.jboss.org/message/8196#8196

Purgatory answered 14/12, 2010 at 19:10 Comment(1)
You can accept your own answer, so other users will know that this question has been answered.Coonskin

© 2022 - 2024 — McMap. All rights reserved.