06 May 2009

Creating a JEE application in Netbeans 6.5

This is the first thing I do when giving a course on JEE: I open up Netbeans, create a JEE project, create a JavaDB database, create a JPA persistance unit, create an entity bean, create a session bean, create a servlet, create a JSP page and create a cutsom tag (all associated with the entity bean created).

This is a great help to the students as it gives them the overview of what we will be working with and shows them how quick and easy it is to create a JEE application in Netbeans - It takes the complexity fear out of them (to a certain extent).

I thought it would be a great help if this were available as a blog for others to follow. Comments will be most welcome, but not that this is pretty much off the cuff and bares no relevence to a real application.

I'll provide a time line to give you an idea of speed, my slow laptop and making it up as I go along should handicap my normal coding dexterity :)

10:51 - music selection, hmm, Black Keys, Brian Eno and David Byrne, Cake.
Ahh, Thickfreakness!


10:55 - Project creation
New Project -> Java EE -> Enterprise Application
I'm calling it BooksDemo
Using the defaults: Glassfish V2, Java EE 5, Create EJB Module, Create Web Application Module

This will create three projects - BooksDemo 'containing' BooksDemo-ejb and BooksDemo-war

11:02 - Create the Datastore

Under Databases in your 'services' tag, right click on 'Java DB' and select 'Create Database' and create a database called 'BooksDemo' with username and password set to 'books' (I've found it doesn't work so well to not have username and password - go figure).

The creation will also start the database, if you go back to the services tab, you will be able to open and view the database.

Back to the project tab: select 'BooksDemo-ejb', right click -> new -> other -> Persistance -> Persistence Unit - > Next
I use the default unit name (BooksDemo-ejbPU) and for datasource select 'New Data Source' at the bottom of the dropdown. Then select the BooksDemo database you created earlier and make the JNDI name 'jdbc/booksDemo', leave the rest as default and finish.

Now for the Entity Object:
Back to the project tab: select 'BooksDemo-ejb', right click -> new -> other -> Persistance -> Entity Class -> Next

Classname 'Book', package 'com.example.book.model' the rest default and finish.

In the Book class, create a new field 'name' as a String field: <alt>INSERT -> Add Property: make the name 'name' and select OK.

11:15 - Create the SessionBean

(Brian Eno is a genius)

In the project tab: select 'BooksDemo-ejb', right click -> new -> other ->Java EE -> Session Bean -> Next

Call it 'BookService', package 'com.example.book.service', the rest default.

Now we are going to create two 'business' methods: getAll and add for retrieving all books and add a book to the datastore.

<ALT>INSERT -> Add Business Method with name 'getAll' with return type 'List<Book>'

<ALT>INSERT -> Add Business Method with name 'add' and add a parameters called 'book' of type 'Book'.

Next fix the imports - <CTRL>-<SHIFT>-I (in the interface as well)


Next we need a handle on the persistance unit: Right click in the BookServiceBean -> Persistence -> Use Entity Manager

You will now have something like the diagram above.

Now we need to use the EntityManager to store and retrieve the books: for the getAll method:

return em.createQuery("select b from Book b").getResultList();

for the add method:

em.persist(book);

11:31 - The Web

We are going to edit the index.jsp ading a form to add a book and retrieve a list of books.

hmm, we need a Servlet to act as the action storing the book first:

On the 'BooksDemo-war' (note its 'war', dammit) right click -> new -> other -> Web -> Servlet -> Next

Class Name: 'BookAdd'
package: 'com.example.book.web.action'

the rest is default, click 'next' and 'finish' (note that the servlet will be called using '/BookAdd' in the URL.

Add the SessionBean by <ALT>-INSERT (in the servlet class) -> Call Enterprise Bean and select the BookServiceBean and OK.

Edit the 'processRequest' method, take everything out and replace it with the following:

Book book = new Book();
book.setName(request.getParameter("name"));
bookServiceBean.add(book);
response.sendRedirect("index.jsp");

We can see if we are on the right track so far: in the project tab, select the 'BooksDemo' projec, right click and 'Run'

This took me 1 min 6 sec..

You should see 'Hello World!' in your browser, this is the index.jsp we haven't edited yet.

Add 'BookAdd?name=test' to the URL in the browser navigation thingy, you should be redirected to the index page, so you will not see anything of value in the browser. this is good. if you see stack traces, bummer.

Go to the Services tab, select Database, select the BooksDemo database, Tables, Book -> right click -> View Data, you should see a record in the table with the name 'test', Hurrah!

11:50 - The index.jsp



Under 'Web Pages' in the 'BooksDemo-war' project you will find the index.jsp page, open it and add the following code after '<h1>Hello World!</h1>':

<form method="post" action="BookAdd">
<input name="name"/>
<button type="submit">add</button>
</form>

Save it, reload your browser and you should see a form with one input field and an 'add' button, enter a name for a new book and press 'add'. Check that you have a new record in the database.


Custom Tag

On the 'BooksDemo-war' right click -> new -> other -> Web -> Tag Library Descriptor -> next

TLD Name: books
default for the rest and click 'finish'
On the 'BooksDemo-war' right click -> new -> other -> Web ->Tag Handler -> Next

Class Name: BookTag
Package: com.example.book.web.tag
default for the rest and click 'Next'

TLD File: WEB-INF/tlds/books.tld (browse to it)
Tag Name: book
default for the rest and click 'finish'

In the BookTag class, <ALT>-INSERT -> Call Enterprise Bean and select BookServiceBean.

Next, remove everything from the 'doTag' method and add the following:

BookServiceLocal bookServiceBean = lookupBookServiceBean();
List<Book> books = bookServiceBean.getAll();
for(Book book: books){
getJspContext().setAttribute("book", book);
getJspBody().invoke(null);
}

You will also need to throw the IOException.

Back to index.jsp,at the top of the page add the following directive:

under the '<%@page' directive,
<%@taglib uri="/WEB-INF/tlds/books" prefix="b"%>

Note: you can <CTRL>-SPACE to auto complete the uri.

(sheep go to heaven, goats go to hell)

Then add the following under the form:

<hr/>
<table>
<tr>
<th>name</th>
</tr>
<b:book>
<tr>
<td>${book.name}</td>
</tr>
</b:book>
</table>


If you reload your browser you should have a list of your book under the form:
And at 12:09, thats a wrap.
At just under two hours, I don't think its that bad for getting a trivial application up and running (bear in mind I did not prepare for this, so some time was spent thinking each step through), if you had to do it by hand it would be more of a headache. Netbeans adds a lot of value to creating these applications.

The project seems to slow down once we reach the web side of things, but maybe one day we'll have a better way of creating web applications :)

17 comments:

De Mann said...

Hey this looks vaguely familiar ;P

Brian Silberbauer said...

De Mann! Hope things are going well your side, drop me a line :)

Mr.IT said...

Hello buddy!
Nice example.. Raise up ur helping hands always,
cheers
vidhya

siva said...

On following your tutor

1)
"Add the SessionBean by ALT-INSERT (in the servlet class) -> Call Enterprise Bean and select the BookServiceBean and OK."

I could not find the BookServiceBean the choose from.

2)
"We can see if we are on the right track so far: in the project tab, select the 'BooksDemo' projec, right click and 'Run' "

Error comes when I try to run.

Maybe some problem on my side. Just bringing into notice.

I was trying out NetBeans following your tutor and looks like we can create web apps effectively in this IDE. Best part is the database commands from the IDE itself.

Thanks for this post :)

Brian Silberbauer said...

Thanks Vidhya.

siva: Thanks for bringing that to my notice, if anybody else is having problems, please let me know.

Anonymous said...

Thanks for this. I'm trying to learn JEE and there are to many things at once. This tutorial ends with working and small example, so it's great for starters. Thanks!

edruta said...

Just great !! I use your tutorial for our junior programmers, it works very good. Thanks !!

Lorena said...

"We can see if we are on the right track so far: in the project tab, select the 'BooksDemo' projec, right click and 'Run' "

Error comes when I try to run.

Im having the same problem.
Says that cant find class Book.

Ive already checked several times if a did something wrong and cant figure out whats the problem...

tpiko said...

Hi Lorena,
I had the same problem when I tried to run the Project. The error is in the class BookServiceLocal (package com.example.book.service), where you should import packages for List and Book class. This class then looks like:

package com.example.book.service;

import com.example.book.model.Book;
import java.util.List;
import javax.ejb.Local;

@Local
public interface BookServiceLocal {

List <Book> getAll();

void add(Book book);

}

Brian Silberbauer said...

Thanks for pointing that out tpiko.

IlPuccio said...

Cute post Brian.

Which is for you the "best" book for understanding how to design a good JEE application, from the server side and the user side (web app and services) ?

Brian Silberbauer said...

Hi IlPuccio

I can't really comment on specific books as I haven't read through any in a while. I have found Sun's series of books to be well written, maybe one of theirs?

Richard said...

Hi, Brian, it helps a total beginner nicely!

However, I seem to get an error when using the Local interface for BookServiceLocal. All works fine with a Remote interface though.

I don't know enough yet to suggest why, but thought it might help others who have that problem.

I also had a minor problem one time when NetBeans tried to import a different Book class for me - maybe something other newbies like me will find.

Running NetBeans 6.1, GlassFish 2, everything locally on my laptop.

Thanks again, keep up the good blog

Sunil Kalyanpur said...

I loved this example. Thanks a lot.

sangeetha said...

Hello..!!!

simply superb.. i just got the hang of it..

thanks mate..

Sangeetha.

sangeetha said...

Hello Brian!

Simply superb! i just got the hang of it.

thanks mate...

rambo said...

i can run this tutorial in Glassfish. but i can not run it in JBoss.Are you can help me?....
thankyou