A Simple EJB 3.0 Example With JSP and Servlet

Yesterday I was trying to begin with EJB. There are lots of resources in web, but I found very less for EJB 3.0 in Netbeans. Among all tutorials, a video in Utube was easy to follow and very effective for understanding. Just few changes was required for me, because that tutorial is in Netbeans 6.1 and I am using Netbeans 6.9.

Here are those steps that I followed for a Stateless Session Bean program to combine with JSP and Servlet.

File -> New Project -> Java EE -> EJB Module

Next, provide the Project Name

Select Webserver and J2EE version, Finish.

Right click on the Project -> New -> Session Bean..

Provide a Bean Name
Assign a Package Name
Select Session Type as Stateless
And set the Interface as Remote, Finish

Open SessionBean.java
Press <alt + insert>, From the list select Add Business Method


Provide Menthod Name
Define a Return Type
Add Parameter by clicking on Add Button

Change the given method body to following code.

@Stateless
public class SessionBean implements SessionBeanRemote {

    public String businessMethod(String name) {
        return "Welcome " + name;
    }
}

Right Click on project and click on Build

Now the componenct is created and we have to use that component in Web Container. Here in this example we are going to use the EJB component via Servlet.

File -> New Project -> Java Web -> Web Application

Next, Provide Project Name

Next, Select  Web Server and J2EE version, Finish.

Right Click on Web Pages -> New -> Servlet..

Provide Servlet Name and Package location

Next, Provide a URL pattern for the Servlet, Finish.

In Servlet Page, remove comment from processRequest method body.
Press <alt + insert>, From the list Select Call Interprise Bean


Select SessionBean, Ok.

Go to index.jsp and create a form with a textbox and button and action to be use_ejb.do (servlet url pattern)

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>EJB Example</title>
    </head>
    <body>
        <form action="use_ejb.do" method="post">
            <input type="text" name="nm">
            <input type="submit" value="OK">
        </form>
    </body>
</html>

Then go to Servlet and send the received value from textbox to the RemoteBean method to get result from the RemoteBean.

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String str1=request.getParameter("nm");
        String str2=sessionBean.businessMethod(str1);
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet UseBean</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>" + str2 + "</h1>");
            out.println("</body>");
            out.println("</html>");

        } finally {
            out.close();
        }
    }

Output :

@Stateless
public class SessionBean implements SessionBeanRemote { 

public String businessMethod(String name) {
return “Welcome ” + name;
}

}

Advertisements

23 Responses to A Simple EJB 3.0 Example With JSP and Servlet

  1. krishna says:

    Its very useful for Beginners…it toooo good…

  2. Prat says:

    It would be useful if there is such a demo program using stateful,msg driven etc..etc..

  3. sp says:

    good 🙂

  4. anusha says:

    Its very useful.thanx a lot ….. need more examples

  5. Gitika says:

    Its really a good example for beginner .. to knw the BIG term EJB

  6. sna says:

    it is good guide.
    but i have problem at picture #5, I cannot choose drop down list of Remote option
    why?

  7. Hema says:

    I worked the same example with netbeans 6,9.1 ,i got this error after MyEJB has been successfully deployed….
    In-place deployment at C:\Documents and Settings\student\My Documents\NetBeansProjects\WebEJBExample\build\web
    deploy?path=C:\Documents and Settings\student\My Documents\NetBeansProjects\WebEJBExample\build\web&name=WebEJBExample&force=true failed on GlassFish v3
    C:\Documents and Settings\student\My Documents\NetBeansProjects\WebEJBExample\nbproject\build-impl.xml:586: The module has not been deployed.
    BUILD FAILED (total time: 0 seconds)

    Pls anyone reply me for this problem……Thanks in advance

  8. jayanthi says:

    While Executing Im getting an error like GlassFish Server Failed, why? pls anyone help me

  9. navneet says:

    very helpful

  10. arun narwal says:

    Thanks a Lots You Give a First step to Learn EJB SessionBean. Thank you so much

  11. beginner_java says:

    awesome tutorial .. very helpful to beginners 🙂

  12. Sandeep says:

    Thanks a lot Mr. Prashanth,for this useful info.It helped me a lot..

  13. karthik says:

    its very useful

  14. N.Gunaseeli says:

    hai,
    i am gunaseeli, i am a professor in an engineering college. This tutorial was very very …..helpful for lab session. but i expect the same type of tutorial for stateful bean as well as entity bean

  15. uv says:

    Useful man..

  16. Ijas says:

    Nice, Thank u

  17. manju says:

    it’s very good program

  18. tutul says:

    good tutorials.. keep it up dud

  19. isaac says:

    hi get this error when from the output after i click ok button:

    HTTP Status 404 – Servlet UseBean is not available

    type Status report

    messageServlet UseBean is not available

    descriptionThe requested resource (Servlet UseBean is not available) is not available.

    GlassFish Server Open Source Edition 3.1.1

    please help

  20. Magudesh says:

    Instead of return type String I use Void then How to execute void method in servlet??
    pls help me..

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: