Compiling / Running EJB Code in NetBeans (Beginner)

I am very new to Java EE / EJB, with very little knowledge of this.

I downloaded NetBeans (7.01) and GlassFish (3.01). But, since I have no idea about EJB, and I don’t get how to run the code in NetBeans, which includes a simple stateless session, Bean, JSP and some servlets.

I found a good code example . Example calculator . Can any body help me with a step-by-step procedure for running the NetBeans example? Thanks in advance.

+4
source share
1 answer

I would advise you not to use a related tutorial. This seems to be from 2011, but he still talks about a lot of deployment descriptors and home interfaces (which are currently old, bad, ugly, and unnecessary ).

You can refer to this JBoss tutorial about EJB 3.0.

NetBeans has excellent support for Java EE development. Just a very quick tutorial (in Java EE 6):

1. Create an EJB project (EJB module)

Create a new project: Shift + Ctrl + N β†’ Java EE β†’ EJB Module β†’ Next . Choose any name that suits you and click Next . Select the target application server (NetBeans should offer you Glassfish Server 3.x) and the version of Java EE (select Java EE 6) -> Finish .

2. Add EJB to your project

Now you have created your EJB project. Right-click on the project name in the Projects tab on the left. Choose New β†’ Session Bean . Choose any name that suits you, define your package and select Singleton (if you are using EJB 3.0 you cannot create single EJBs - just choose a different type). Make sure that local and remote interfaces are not marked . Click Finish .

You have just created your first EJB; -)

3. Call the EJB business method

Now you can try to use it. You need to execute your EJB class method - for this you need someone to call your method. It could be:

  • servlet
  • standalone client
  • a @PostConstruct .

I will show you how to use the latter option, which seems the easiest if you can use Singleton EJB. All you need to know about the @PostConstruct annotated method is that it will be called when the application container creates your bean. It looks like a special type of constructor.

The fact is that you usually do not control EJB initialization. However, if you used @Singleton EJB, you can force the container to initialize your bean during server startup. This way you will find out that your @PostConstruct method will be called during server startup.

At this point, you should have code similar to the following:

 package your.package; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.LocalBean; import javax.ejb.Startup; @Singleton @Startup public class NewSessionBean { // This method will be invoked upon server startup (@PostConstruct & @Startup) @PostConstruct private void init() { int result = add(4, 5); System.out.println(result); } // This is your business method. public int add(int x, int y) { return x + y; } } 

After running this sample code (the big green arrow on the toolbar), you should see GlassFish logs similar to this:

INFO: portable JNDI names for EJB NewSessionBean: [Java: global / EJBModule 1 / NewSessionBean sss.NewSessionBean, Java: global / EJBModule 1 / NewSessionBean]
INFO: 9
INFO: EJBModule1 was successfully deployed in 78 milliseconds.


This example also shows another feature of EJB 3.1 - right now, not only do you not need to use home interfaces, but you do not even need to use any interfaces. You can just use your class directly.

Note that there are several errors in this example. You should not use the System.out.println instructions, I did not use the business interface, but used this to call the business method, I did not use Servlets to call my EJB business method, etc.
This is just a very simple example, allowing you to start developing EJB.


As requested below, you can find a mini tutorial for the EJB ↔ Servlet ↔ JSP workflow:

1. Creating a web project

(Note: you could achieve the above example - using Singleton EJB - with a web project. In this case, we need a web project, since we will create the servlet and JSP in one package.)

Ctrl + Shift + N β†’ Java Web β†’ Web Application β†’ Next . Set the name of your application β†’ Next β†’ the default values ​​(remember that the context path - you need it to access your application) β†’ Finish .

2. Create your EJB

At this time, it will be standstill by EJB, as it better reflects what a bean calculator should be.

You do this exactly as described above - just select Stateless instead of Singleton in the corresponding window.

3. Put the business logic in your EJB

Find an example below:

 package com.yourpckg; import javax.ejb.Stateless; // Stateless EJB with LocalBean view (default when no interface is implementated) @Stateless public class Calculator { // Business method (public) that may be invoked by EJB clients public int add(int x, int y) { return x + y; } } 

4. Create a servlet that will invoke your business logic

yuan in your project or Ctrl + N β†’ Web β†’ Servlet β†’ Next β†’ define the name of the servlet and its package β†’ Next β†’ define its URL pattern (remember - he will need access to your servlet) β†’ Finish .

5. Define the dependency between your servlet and EJB.

Your controller (servlet) must use your EJB. You do not want to do any searches or unpleasant boilerplate code. You simply determine that your servlet will use your Calculator EJB using the annotation.

 @EJB Calculator calculator; 

You put this as a field in your servlet class, so it should look something like this:

 @WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"}) public class MyServlet extends HttpServlet { @EJB Calculator calculator; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // ... } 

6. Put the controller logic in your servlet

NetBeans by default delegates all HTTP method requests into a single method - processRequest(-) , so this is the only method you need to change.
Find an example below:

 protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { // Fetch the user-sent parameters (operands) int operand1 = Integer.parseInt(request.getParameter("operand1")); int operand2 = Integer.parseInt(request.getParameter("operand2")); // Calculate the result of this operation int result = calculator.add(operand1, operand2); // Put the result as an attribute (JSP will use it) request.setAttribute("result", result); } catch (NumberFormatException ex) { // We're translating Strings into Integers - we need to be careful... request.setAttribute("result", "ERROR. Not a number."); } finally { // No matter what - dispatch the request back to the JSP to show the result. request.getRequestDispatcher("calculator.jsp").forward(request, response); } } 

7. Create a JSP file

Ctrl + N in your project β†’ Web β†’ JSP β†’ Next β†’ enter the name of the file (in my case its Calculator , since the servlet code uses this name (look in the getRequestDispatcher part). Leave the value of the input folder empty. β†’ Finish .

8. Fill the JSP file with user interface code

This should be a simple form that defines two parameters: operand1 and operand2 and redirects the request to map the servlet URL. In my case, it is something like the following:

 <%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <form action="MyServlet"> <input type="text" name="operand1" size="3" value="${param['operand1']}" /> + <input type="text" name="operand2" size="3" value="${param['operand2']}" /> = <input type="submit" value="Calculate" /> </form> <div style="color: #00c; text-align: center; font-size: 20pt;">${result}</div> </body> </html> 

Just look at the value of the action attribute of the form (this should be your servlet URL mapping.).

  • Enter your application

You need to know which port uses GlassFish. I think in NetBeans its default is 37663 . The following are the web application URL and the name of the JSP file. Combine all this together, and you should get something like:

http: // localhost: 37663 / MyWebApp / calculator.jsp

In two input texts, you enter the operands, and after clicking "Calculate" you should see the result.

+6
source

Source: https://habr.com/ru/post/1388336/


All Articles