在 NetBeans 中编译/运行 EJB 代码(初学者)

发布于 2024-12-23 10:53:11 字数 327 浏览 2 评论 0原文

我对 Java EE/EJB 非常陌生,对此知之甚少。

我已经下载了 NetBeans (7.01) 和 GlassFish (3.01)。但是,由于我对 EJB 一无所知,并且不知道如何在 NetBeans 中运行代码,其中包括一个简单的无状态会话 Bean、一个 JSP 和一些 Servlet。

我找到了一个很好的示例代码计算器示例。任何人都可以通过提供如何运行 NetBeans 示例的分步过程来帮助我吗?提前致谢。

I am very new to Java EE/EJB, with very little knowledge about it.

I have downloaded NetBeans (7.01) and GlassFish (3.01). But, as I have no idea about EJB, and am not getting how to run the code in NetBeans which includes a simple Stateless Session Bean, a JSP and some Servlets.

I found a nice example code Calculator Example. Can any body help me by giving a step by step procedure how to run the NetBeans example? Thanks in advance.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

所谓喜欢 2024-12-30 10:53:11

我建议您不要使用链接的教程。它似乎是 2011 年的,但它仍然讨论了很多部署描述符和 home 接口(现在这些都是旧的、坏的、丑陋的和不必要的)。

您可以参考这个关于 EJB 3.0 的 JBoss 教程

NetBeans 对 Java EE 开发提供了大力支持。只是一个非常快速的教程(在 Java EE 6 中):

1。创建您的 EJB 项目(EJB 模块)

创建新项目:Shift + Ctrl + N -> Java EE -> Java EE EJB 模块 -> 下一步。选择适合您的名称并点击下一步。选择目标应用程序服务器(NetBeans 应该建议您使用 Glassfish Server 3.x)和 Java EE 版本(选择 Java EE 6)-> 完成

2.将 EJB 添加到您的项目

现在您已经创建了 EJB 项目。右键单击左侧Projects 选项卡中的项目名称。选择新建 -> 会话 Bean。选择适合您的名称,定义您的包并选择 Singleton(如果您使用的是 EJB 3.0,则无法创建单例 EJB - 只需选择其他类型)。确保本地和远程接口未选中。点击完成

您刚刚创建了您的第一个 EJB ;-)

3。调用EJB业务方法

现在您可以尝试使用它了。您需要执行 EJB 类方法 - 为此,您需要有人调用您的方法。它可以是:

  • 一个 servlet、
  • 一个独立的客户端、
  • 一个 @PostConstruct 方法。

我将向您展示如何使用最后一个选项,如果您可以使用 Singleton EJB,这似乎是最简单的选项。关于 @PostConstruct 注解的方法,您需要了解的只是它会在应用程序容器创建您的 bean 时被调用。它就像一种特殊类型的构造函数。

关键是您通常无法控制 EJB 的初始化。但是,如果您使用@Singleton EJB,则可以强制容器在服务器启动期间初始化您的bean。这样,您就会知道您的 @PostConstruct 方法将在服务器启动期间被调用。

此时,您应该拥有类似于以下代码的代码:

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;
    }
}

运行此示例代码(工具栏上的大绿色箭头)后,您应该看到类似于以下代码的 GlassFish 日志:

信息:EJB NewSessionBean 的可移植 JNDI 名称:
[java:global/EJBModule1/NewSessionBean!sss.NewSessionBean,
java:global/EJBModule1/NewSessionBean]
信息:9
信息:EJBModule1 是
78 毫秒内成功部署。


这个示例还展示了 EJB 3.1 的另一个功能 - 现在,您不仅不需要使用 home 接口,而且甚至不需要使用任何接口。你可以直接使用你的类。

请注意,这个示例有几个问题。你不应该使用System.out.println指令,我没有使用业务接口,而是使用this来调用业务方法,我没有使用Servlet来调用我的EJB业务方法等等。
这只是一个非常简单的示例,让您开始 EJB 开发。


根据要求,您可以在下面找到 EJB<->Servlet<->JSP 工作流程的迷你教程:

1.创建 Web 项目

(注意:您也可以使用 Singleton EJB 来实现上述示例 - 使用 Web 项目。在本例中,我们需要 Web 项目,因为我们将在一个包中创建 servlet 和 JSP。)

Ctrl + Shift + N -> Java Web -> Web 应用程序 -> 下一步。设置您的应用程序的名称 -> 下一步 ->默认值很好(记住上下文路径 - 您需要它来访问您的应用程序)-> 完成

2.创建您的 EJB

这次,它将是无状态 EJB,因为它更好地反映了计算器 bean 的样子。

您完全按照上述方式进行操作 - 只需在相应的窗口中选择 Stateless 而不是 Singleton 即可。

3.将业务逻辑放入您的 EJB

查找下面的示例:

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.创建Servlet,它将

在您的项目上调用您的业务逻辑 RMB 或Ctrl + N -> 网络 -> Servlet -> Servlet 下一步 ->定义 servlet 名称及其包 -> 下一步 ->定义它的 URL 模式(记住它 - 您将需要它来访问您的 servlet)-> 完成

5.定义 Servlet 和 EJB 之间的依赖关系。

您的控制器 (Servlet) 需要使用您的 EJB。您不想执行任何查找或令人讨厌的样板代码。您只需使用注释定义您的 Servlet 将使用您的 Calculator EJB。

@EJB
Calculator calculator;

您将其作为 servlet 类中的一个字段,因此它应该是这样的:

@WebServlet(name = "MyServlet", urlPatterns = {"/MyServlet"})
public class MyServlet extends HttpServlet {

    @EJB
    Calculator calculator;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // ...
}

6。将控制器逻辑放入您的 Servlet

默认情况下,NetBeans 将所有 HTTP 方法请求委托给一个方法 - processRequest(-),因此它是您应该修改的唯一方法。
查找以下示例:

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. 在您的项目上创建 JSP 文件

Ctrl + N -> 网络 -> JSP -> 下一步 ->输入文件名(在我的例子中是计算器,因为 Servlet 代码使用此名称(查看 getRequestDispatcher 部分)。将文件夹输入值留空。-> ; 完成

用用户界面代码填充 JSP 文件

它应该是一个定义两个参数的简单表单:operand1operand2 并推送请求在我的例子中,它类似于以下内容:

<%@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>

只需观察表单 action 属性值(它应该是您的 Servlet URL 映射。)。

  1. 输入您的应用程序

您应该知道您的 GlassFish 的端口。我猜想在 NetBeans 中,默认情况下它是 37663。 将它们组合在一起,您应该得到如下内容:

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

在两个输入文本中键入操作数,然后单击“计算” ' 你应该看到结果。

I'd advise you not to use the linked tutorial. It seems to be from 2011, but it still talks about a lot of deployment descriptors and home interfaces (which are old, bad, ugly and unnecessary nowadays).

You can refer to this JBoss tutorial about EJB 3.0.

NetBeans have great support for Java EE development. Just a very fast tutorial (in Java EE 6):

1. Create your EJB project (EJB Module)

Create new project: Shift + Ctrl + N -> Java EE -> EJB Module -> Next. Choose whatever name suits you and hit Next. Choose the target application server (NetBeans should suggest you Glassfish Server 3.x) and Java EE version (choose Java EE 6) -> Finish.

2. Add EJB to your project

Now you have your EJB project created. Right click on the project name in Projects tab on the left hand side. Choose New -> Session Bean. Choose whatever name suits you, define your package and choose Singleton (if you're using EJB 3.0 you cannot create singleton EJBs - just choose another type). Make sure Local and Remote interfaces are unchecked. Hit Finish.

You've just created your first EJB ;-)

3. Invoking EJB business method

You can now try to use it. You need to execute your EJB class method - to do it, you'd need somebody to invoke your method. It can be i.e.:

  • a servlet,
  • a standalone client,
  • a @PostConstruct method.

I'll show you how to use the last option which seems to be the easiest if you can use Singleton EJBs. All you need to know about @PostConstruct annotated method is that it will be invoked when the application container creates your bean. It's like a special type of the constructor.

The point is that you normally don't have any control over EJBs initialisation. However, if you used the @Singleton EJB, you can force the container to initialise your bean during the server startup. In this way, you'll know that your @PostConstruct method will be invoked during server startup.

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

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 exemplary code (big green arrow on the toolbar), you should see GlassFish logs similar to this one:

INFO: Portable JNDI names for EJB NewSessionBean :
[java:global/EJBModule1/NewSessionBean!sss.NewSessionBean,
java:global/EJBModule1/NewSessionBean]
INFO: 9
INFO: EJBModule1 was
successfully deployed in 78 milliseconds.


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

Note that there are several things wrong with this example. You should not use System.out.println instructions, I've not used business interface but used this to invoke business method, I haven't used Servlets to invoke my EJB's business method and so on.
This is just a very simple example to let you to start EJB developing.


As requested, below you can find mini-tutorial for EJB<->Servlet<->JSP workflow:

1. Create Web Project

(Note: you could achieve the above example - with Singleton EJB - with Web Project as well. In this case we need Web Project as we'll create a servlet and JSP in one package.)

Ctrl + Shift + N -> Java Web -> Web Application -> Next. Set the name of your application -> Next -> the defaults are fine (remember the context path - you'll need it to access your application) -> Finish.

2. Create your EJB

In this time, it'll be stateless EJB as it betters reflects what the calculator bean should be.

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

3. Put business logic into your EJB

Find the 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 Servlet which will call your business logic

RMB on your project or Ctrl + N -> Web -> Servlet -> Next -> define servlet name and its package -> Next -> define its URL pattern (remember it - you'll need it to access your servlet) -> Finish.

5. Define dependency between your Servlet and EJB.

Your controller (Servlet) need to use your EJB. You don't want to do any lookups or nasty boilerplate code. You just defines that your Servlet will use your Calculator EJB by using annotation.

@EJB
Calculator calculator;

You put this as a field in your servlet class, so it should be 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 controller logic into your Servlet

NetBeans by defaults delegates all HTTP Method requests into one method - processRequest(-), so it's the only method you should modify.
Find the 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 JSP file

Ctrl + N on your project -> Web -> JSP -> Next -> type the file name (in my case its calculator, as the Servlet code uses this name (take a look at getRequestDispatcher part). Leave the folder input value empty. -> Finish.

8. Fill JSP file with user interface code

It should be a simple form which defines two parameters: operand1 and operand2 and pushes the request to your servlet URL mapping. In my case its 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 watch the form action attribute value (it should be your Servlet URL mapping.).

  1. Enter your application

You should know what port your GlassFish uses. I guess that in NetBeans by default its 37663. Next thing is the Web Application URL and JSP file name. Combine it all together and you should have something like:

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

In two input texts you type the operands and after clicking 'Calculate' you should see the result.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文