You are on page 1of 9

Stack Exchange

sign up log in tourhelp stack overflow careers

Stack Overflow

Questions

Tags

Users

Badges

Unanswered

Ask Question
Take the 2-minute tour
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's
100% free, no registration required.

Compile/Run EJB Code in NetBeans (Beginner)

up
vote4do
wn vote

favorite

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.
java

netbeans

ejb-3.0

shareimprove this question

netbeans-7

edited Dec 30 '11 at 8:35

asked Dec 28 '11 at 16:54

alessandro
52731334

add a comment

1 Answer
activeoldest

up
vote5do
wn vote

accepted

votes

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
import
import
import

javax.annotation.PostConstruct;
javax.ejb.Singleton;
javax.ejb.LocalBean;
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.printlninstructions, 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.
shareimprove this answer

edited Dec 28 '11 at 20:56

answered

Piotr Nowicki
7,94032253

2 Please give me a sign if you have a problem with EJB <-> Servlets connection and you already have working
EJBs. Piotr Nowicki Dec 28 '11 at 17:32

1 @alessandro are you sure that you need to go to EJB 2.x world? Are you sure and willing to enter this god-forgotte
land? ;-) Before answering, you should know that "home interface" is not required for connecting EJB with Servlets
It's just EJB 2.x way of accessing your beans. I will shortly update my answer with Servlets and JSP using this
EJB. Piotr Nowicki Dec 28 '11 at 19:49

You can check the updated answer. You should now know how to use these tree concepts. This uses no-interface vie
(LocalBeans) which are EJB 3.1 feature. For remote and home interfaces I'll guess you'll need to google a
bit :-) Piotr Nowicki Dec 28 '11 at 20:58
Thanks, I solved it. alessandro Dec 30 '11 at 8:35
add a comment

Your Answer

Sign up or log in
Sign up using Google

Sign up using Facebook


Sign up using Stack Exchange

Post as a guest

Name
Email
Post Your Answ er

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions


tagged

java

netbeans

ejb-3.0

asked

netbeans-7

or ask your own question.

3 years ago

viewed

4825 times

active

2 years ago

Looking for a job?

Drupal Software Engineer


New Relic
Portland, OR
rubypython

Senior Backend Engineer


InsideTrack
San Francisco, CA
rubyjava

Related
0

how to develop and run ejb in netbean6.7?

Problem running a simple EJB application

How to find Bean Validation Error in Netbeans

Ejb with NetBeans

Ejb Code with NetBeans and GlassFish

Run a ejb outside it's container in Netbeans

About Enterprise Java Session Beans

UML Reverse Engineering in Netbeans Broken

Affable Bean Java EJB Glassfish tutorial issues in netbeans

Netbeans will not treat JSP as Source Level 7

Hot Network Questions

Why is Thor's hammer blue in his Age of Ultron poster?


Mixing coffee without a spoon
Did military operation names ever have any meaning?
Is it bad practice to overload a function to take both a pointer or a reference?
Why are professors' websites so ugly?
Memory Leak Detectors Working Principle
How can I stop the 3D cursor hopping around when positioned in top, front, and right view?
Why Java Stream are one-time?
What is the origin of the "underwater basket weaving" meme in Academia?
Redefine \emph to be both bold and italic
"Zero tolerance for walkers, or them to be." -- grammar, meaning?
Feminism being referred to as equality for all, as opposed to equality for women
Inserting an open and simply-connected set between a compact set and an open set
Be (all) the better for something
Morra, the Noble Game of Kings
Find two numbers whose sum is 20 and LCM is 24
How to handle initial state in an event-driven architecture?
What is the approximate caloric intake of a dragon?
What is the set in D FF?
Simple survey application

Hydra regeneration explained with science


When does a "pez" become a "pescado"?
Looking for a really old novel where the people are geometric figures
Print a Block-Diagonal Matrix

question feed
tour help blog chat data legal privacy policy work here advertising info mobile contact us feedback
TECHNOLOGY

LIFE / ARTS

Stack
Overflow

Programmer
s

Server Fault
Super User

Linux

Webmasters

Different (Apple)
WordPress
Development

Game
Development

Geographic
Information Systems

TeX - LaTeX

Drupal

Science

Electrical
Engineering
Android

& Usage
Skeptics

Graphic
SharePoint
User

Experience
Mathematica
Salesforce
more (14)

Design
Seasoned

Comp
Travel

Advice (cooking)

Christianity

Home

Arqade (gaming)

Improvement

Bicycles

Personal
Academia

Role-playing
Games
more (21)

more (10)

Enthusiasts
Information
Security
site design / logo 2015 stack exchange inc; user contributions licensed under cc by-sa 3.0 with attribution required
rev 2015.2.11.2283

Valida

Mi Yodeya
(Judaism)

Finance & Money

SCIE

English Language

Fiction & Fantasy

Answers
Ask

Ask Ubuntu

Photography

Administrators
Unix &

Web
Applications

Database

CULTURE /
RECREATION