Develop Java Enterprise Application with Netbeans 6.1

In this post I’ll show you how easy to develop full Java Enterprise application with Netbeans 6.1beta. For example I’ll develop a simple “Contact Person” application. I’ll used JPA for the model layer, SessionBean for facade object and Jsp/Servlet for the web client. All of this technology are supported by Netbeans6.1beta. Thanks for NetBeans teams your are rock!!

This application will have 2 entity model: Person and Address. A Person can have more than one Address.

contact.jpg

From the design above lets start to develop the application😀

  • Start you Netbeans6.1beta IDE. If you don’t have it please download here. You have to download the Web & Java EE bundled.
  • Create a new project. Click on File>New Project
new-project.jpg
  • Chose Enterprise for the Categories and Enterprise Application for the Project.
  • On the New Enterprise Application Window, set the Project Name with person-jee, Server with GlassFish and check the Create EJB Module and Create Web Application Module checkbox then click Next and Finish.
project-name.jpg
  • Netbeans will create a new Enterprise Application project with EJB Module and Web Module project.
project-tree.jpg
  • Next we start to create the EJB Modul. We have to create the model: Person and Address using JPA and Facade Object using SessionBean.
  • SessionBean as facade object will encapsulates and centralizes the interactions between calling clients (web client) and the model entities and operations of the Java Persistence APIs. It provides a single interface for operations on a set of entities.
  • The client using this facade does not have to be aware of all the details of the APIs of each entity and does not have to be aware of any persistence mechanisms being used when accessing the entity managers or other transaction managers.
arsitekture.jpg
  • Clients and the entities in the model tier makes the code more loosely-coupled and easier to maintain.
  • Ok lets create the entity model. From the EJB Module project, right click on the Source Package>New>Entity Class
new-entity.jpg
  • From the New Entity Class Window fill in the Class Name with Person and Package with entity and then click on Create Persistence Unit button. We have to create new Persistence unit.
person1.jpg
  • From the Create Persistence Unit window, set the Persistence Unit Name to personPU and select TopLink as the Persistence Provider. Next we have to create New Data Source.
persistenceunit.jpg
  • From the Create Data Source window, set the JNDI Name to jdbc/dbperson and then we have to create New Database Connection. In this example we using MySQL as the Database Server.
datasource.jpg
  • We will create a Connection to a database in MySQL Server. For example we will create connection to dbperson. Dbperson is an empty database that don’t have any tables. The tables structure will be create by JPA automatically😀
dbconnection1.jpg
  • Fill in the database connection property according to your database server. Klik Ok until you back to the Create Persistence Unit Window.
pu.jpg
  • Now click Create to create to Persistence Unit and you will back to the New Entity Class window. From this window click Finish to create the Person class.
  • Netbeans will create the entity Person source. Do the same step to create the entity Address but you don’t have to create Persistence Unit.
  • Now we have to modify the Person and Address source code. First please modify Person class.
@Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String occupation;
@OneToMany(cascade = CascadeType.ALL)
private List<Address>address = new ArrayList<Address>();
//other source here
}
  • Don’t forget to create setter and getter method for name,occupation and address field. Netbeans6.1beta have nice feature for this😀
  • Press Alt+Ins on your keyboard and netbeans will show a popup for create setter and getter method😀
setergeter.jpg
  • Select all field and click Generate. Netbeans will create the setter and getter method
setergeter2.jpg
  • Next modify the Address class. Add field street, city, province and phone. And don’t forget to add the setter and getter method too
  • After that we will create the Facade object that is SessionBean. Right click on Source Package>New>Session Bean
facade1.jpg
  • Fill in PersonFacadeSession for the EJB Name, facade for the package, Stateles for the Session type and Remote for the Interface and then click Finish. Netbeans will create the PersonFacadeSession source code.
  • We will add 5 business method in this facade object.
    • insert(Person p) : to insert New Person
    • delete(long id): to delete Person object by Id
    • update(long oldId,Person p): update a Person object by Id
    • list(): to get all person object
    • load(long id): to get a Person object by Id
  • To add business method in SessionBean (the facade object) is very simple. Netbeans has this feature too😀
  • Right click on the source code area, select EJB Methods>Add Business Method…
addbusiness.jpg
  • On Add Business Method window set the method Name to insert and add a parameter person that has Object type.
businessmethodadd.jpg
  • And for the other business methods do the same way.
load.jpg
laod Person
delete.jpg
delete Person
update.jpg
update Person
list.jpg
list Person
  • Our facade object then will use EntityManager from JPA API to manipulated the model. So we must add it too. Right click on the source code area and select Persistence>Use Entity Manager
em.jpg
  • Modify your PersonFacadeSessionBean class
@Stateless
public class PersonFacadeSessionBean implements PersonFacadeSessionRemote {
@PersistenceContext
private EntityManager em;
public void insert(Object person) {
em.persist(person);
}
public void delete(long id) {
em.remove(em.find(Person.class, id));
}
public void update(long id, Object person) {
Person p = em.find(Person.class, id);
p = (Person) person;
em.refresh(p);
}
public java.util.List list() {
List list = em.createQuery("SELECT p FROM Person p").getResultList();
return list;
}
public Person load(long id) {
Person p = em.find(Person.class, id);
return p;
}
}
  • Because we using MySQL Server for the database, so we need to add MySQL Connector to the EJB module project.
  • Right click on the Library>Add Library
addlibrary.jpg
  • Find MySQL JDBC Driver and then click Add Library button
mysqljdbc.jpg
  • Right here we just finish develop the EJB module😀 Next step we will create the web base client using struts framework.
  • First we prepare the Servlet class. Right click on Source Packages>New>Servlet
servlet1.jpg
  • The first Servlet is a servlet that get all person from database through the Facade object Session Bean.
  • Set the Class Name to GetListPersonServlet and the Package to servlet and click Next.
servlet2.jpg
  • On the Next Window, set the URL Pattern(s) to /list and Finish. It is the URL to call the Servlet.
servlet3.jpg
  • Then Netbeans will create the source code. Because this Servlet will call the Facade Object SessionBean, so we add some code for it. Netbeans is very helpful for this😀
  • Right click on the source area, select Enterprise Resources>Call Enterprise Bean
callsession.jpg
  • On Call Enterprise Bean Window select PersonFacadeSessionBean and then click OK button
sessioncal2.jpg
  • You will see this code at top of the servlet source.
@EJB
private PersonFacadeSessionRemote personFacadeSessionBean;
  • Update the processRequest method
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
List persons = personFacadeSessionBean.list();
request.setAttribute("persons", persons);
RequestDispatcher dis = request.getRequestDispatcher("list.jsp");
dis.forward(request, response);
} catch(Exception ex) {
ex.printStackTrace();
}
}
  • Next Servlet is DeletePersonServlet. Create this servlet just like the other one before, but the URL Pattern(s) set to /delete. Don’t forget to add the SessionBean too
  • Modify the processRequest method for DeletePersonServlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
long id = Long.parseLong(request.getParameter("id"));
personFacadeSessionBean.delete(id);
RequestDispatcher dis = request.getRequestDispatcher("list");
dis.forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
  • Next Servlet is InsertPersonServlet. Create this servlet just like the other one before, but the URL Pattern(s) set to /insert. Don’t forget to add the SessionBean too
  • Modify the processRequest method for InsertPersonServlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String name = request.getParameter("name");
String occupation = request.getParameter("occupation");
String street1 = request.getParameter("street1");
String city1 = request.getParameter("city1");
String province1 = request.getParameter("province1");
String phone1 = request.getParameter("phone1");
String street2 = request.getParameter("street2");
String city2 = request.getParameter("city2");
String province2 = request.getParameter("province2");
String phone2 = request.getParameter("phone2");Address addr1 = new Address();
addr1.setStreet(street1);
addr1.setCity(city1);
addr1.setProvince(province1);
addr1.setPhone(phone1);
Address addr2 = new Address();
addr2.setStreet(street2);
addr2.setCity(city2);
addr2.setProvince(province2);
addr2.setPhone(phone2);Person person = new Person();
person.setName(name);
person.setOccupation(occupation);
person.getAddress().add(addr1);
person.getAddress().add(addr2);personFacadeSessionBean.insert(person);
RequestDispatcher dis = request.getRequestDispatcher("list");
dis.forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
  • Next Servlet is DetailPersonServlet. Create this servlet just like the other one before, but the URL Pattern(s) set to /detail. Don’t forget to add the SessionBean too
  • Modify the processRequest method for DetailPersonServlet
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
long id = Long.parseLong(request.getParameter("id"));
Person p = personFacadeSessionBean.load(id);
request.setAttribute("person", p);
RequestDispatcher dis = request.getRequestDispatcher("detail.jsp");
dis.forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
  • Ok.. now we have to create the user interface with jsp page.
  • Create new JSP file: right click on Web Pages>New>JSP…
jsp1.jpg
  • Set JSP file name to list and then click Finish.
jsp2.jpg
  • Before we modify the source, we need to add JSTL library to our web module because we will use it in the JSP page. Right click on the Libraries>Add Library
addjstl.jpg
  • Find the JSTL 1.1 library and click Add Library
jstllib.jpg
😦 wiuh… i will continue this post next week

47 Responses to Develop Java Enterprise Application with Netbeans 6.1

  1. wilbertliu says:

    Hahaha..,kalau ak mending kasih source langsung, coz ribet nulis2nya itu pak… hahaha!🙂

  2. Hendro Steven says:

    kalo sourcenya banyak di internet..
    tapi bisa ngerti gak cara buatnya???
    tapi kalo step by step mungkin lebih mudah dimengerti dari pada hanya source codenya yang di tampilin..
    btw ada gak yang mau capek-capek tulis step by stepnya?? hehehehe.. semoga aku gak bosan😀

  3. wilbertliu says:

    Huhuhu, aku sih capek kalo nulis segitu banyak di blog pak…🙂

    ya biar jadi teladan deh ini…🙂

  4. t33d says:

    step by step aja pak, saya lebih gampang ngikutinnya😀 (kayak yang di video tutorialnya)

  5. radu says:

    how about creating a web service from the session beans and calling webservice methods from the jsp pages?

  6. kfng99 says:

    This is good. Are you planning on completing it?

  7. Hendro Steven says:

    yes of course but wait for my free time😦

  8. Hendro Steven says:

    hallo radu..
    creating web service from session bean is very simple.. I plan to post about it

  9. eva says:

    pak saya mau tanya, ada ga perbedaan antara membuat aplikasi enterprise sperti jsf or ejb di netbean dengan di eclipse?
    thx b4

  10. Hendro Steven says:

    secara konsep sama aja yang berbeda hanya di wizard-wizard yang disediakan oleh masing-masing IDE. Yang lebih mudah penggunaanya Netbeans🙂

  11. eva says:

    saya mw tny lagi pak,
    klw di netbean misalkan kita membuat taglib seperti maka netbeans ga akn bawel alias ga eror.
    tapi begitu saya coba di eclipse, maka keluar eror yang mengatakan tidak menemukan lib ny.
    apakah di eclipse harus membuat pulgin dl? karena saya baca dibeberapa web mengatakan bahwa harus mendownload WTP. Bagaimana menurut bpk?

  12. eva says:

    tag lib nya seperti ini pak :
    %@ taglib prefix=”f” uri=”http://java.sun.com/core” % (tanda kurungny saya hilangkan karena pada comment diatas tidak keluar syntax ny

  13. Hendro Steven says:

    kalo ingin membuat aplikasi web dengan eclipse sebaiknya instal wtp juga. Atau biar gak repot download aja eclipse yang udah ada dengan wtpnya

  14. eva says:

    wah repot juga y pak, ga semudah dinetbean
    >.<
    pak klw bs ks tw website yang bs bwt download wtp or eclipse yang ud include wtpny.
    Karena ini sya coba download di eclipse.org ga bs trus. thx b4

  15. Hendro Steven says:

    Hallo Eva sory baru balas🙂
    wah aku gak punya alama lain selain di eclipse.org😦
    Coba deh di http://www.eclipse.org/downloads/
    trus pilih yang Eclipse IDE for Java JEE Developer nah nanti tinggal pilih mirornya.. ada server untuk Indonesia tuh..

    semoga membatu

  16. eva says:

    ok2 pak.
    thx a lot ^^
    ni masalah nya sudah terselesaikan dengan sempurna ^^

  17. Ranbir Rastogi says:

    I want to know more about NetBean IDE for developing large Enterprise Application which involvs N-Tier architecture.

  18. echo says:

    ditunggu, sambungannya🙂

  19. Ida says:

    I have problem creating Enterprise application with Glassfish and MySQl….please continue.
    Do you have complete source code for reference?

  20. csr says:

    where is the second part of developing enterprise application in nebeabs 6.1

  21. victor bruno says:

    Greetings sir:
    I’ve fully appreciated this tutorial and feel very grateful for it,since it assisted me to build a student database application.Yet,now I’ve got a new challenge: build a file database application.that’s why I’m asking for your help on creating the code for the user
    to upload the files from elsewhere to the database.If you have,please assist me.

    Thank you so much!

  22. ila says:

    please continue the Enterprise application i need some more.

  23. bruno says:

    Hello Hendro! Thank you for this fine tutorial.
    I’ve got a problem in creating a code to upload files and save them in a database created with this in view.Have you got the code? please let me know

  24. ersan says:

    bi boka yaramıyo

  25. Rah says:

    hey i wonder if you can help me, Iam trying to create a smart card application (Id Card) for members of a certain hospital staff. I have decided to use netbeans 6.1 and also downloaded java card development kit 2-2-2, please i need a guide of how i can make this happen, i am new with all these.
    You can get intouch with me using my email address
    much appreciation
    Thanks

  26. Hendro Steven says:

    halo Rah,
    I’m so sorry.. i can’t help you in that case😦 cause i don’t know about smart card well..
    but thanks for your comment

  27. marwa says:

    I need the reminder of this project steps

  28. Kate says:

    Hi,
    Just wanted to say thankyou for this tutorial, has been the most helpful I have found in regards to ejb’s.

    Also wondering if the second half has been uploaded anywhere?

    Thankyou again

    Kate

  29. Bruno says:

    Greetings Mr Evandro:
    Hope you are doing well.I’ve got a problem and thought you to be up to it.
    When trying to start a new connection to mysql server in my IDE(the server is registered) it issues the following: unable to add connection.for input string:””.
    Why is that?
    Thank you so much

  30. Joni Q says:

    Mas bisa bikin tulisan khusus ga? Yang memetakan tentang arsitektur java ee, beserta jenis2 teknologi java ee dan tempat imlementasinya pada konsep mvc, seperti Struts 2.0, velocity, jsf, iBatis, hibernate, Tapestry, dll. Dari yang opensource dan yang ikut standar JCP.
    Kalo bisa saya juga minta saran, mulai dari mana tahap belajar JavaEE, dan apa saja toolsnya.

  31. Hendro Steven says:

    halo bruno,
    sory for my late response😦
    are your mysql server is running?
    or your username and password is correct?

  32. akhyar says:

    hehehe mas agak ribet tapi akan aku coba mas hehehehehe

  33. mahbub says:

    please continue with jsp.

  34. Kat says:

    Please continue – or update ASAP.

    Regards,

    Kat.

  35. aDONZ says:

    olease continue for jsp

  36. aDONZ says:

    mana kelanjutannya nih….

    trus methode update pada servlet kok g ada..?

    tlg dilengkapi ya masss….

    biar selesai saya mempelajarinya

  37. Misu says:

    I wonder have you completed this application. If so please send me the link I really need to understand how this application works. I have a similar but much bigger project to build and I need all the information I can get

  38. misu says:

    Hi Hendro
    please continue this application

  39. adi says:

    mas hendro tutorial java card ada nggak? mohon pencerahannya

  40. syam k mohan says:

    Please continue the jsp page
    up to this was very useful to me
    thanks and regards

  41. zulkifli says:

    Ayo pak lanjutin lagi dong mpe selesai. byk yg minta nih!🙂

  42. Helmut Orth says:

    Hi Hendro
    I wonder have you completed this application. If so please send me the link I really need to understand how this application works. I have a similar but much bigger project to build and I need all the information I can get.

    I express my sincere thanks for your efforts.

  43. Helmut Orth says:

    Hi Hendro
    I wonder have you completed this application. If so please send me the link I really need to understand how this application works. I have a similar but much bigger project to build and I need all the information I can get.

    I express my sincere thanks for your efforts.

    Helmut Orth

  44. yugi says:

    ada bukunya g

  45. uthee says:

    pak, sangat membantu saya dalam belajar euy tutorialnya tq ya pak….

  46. Hendro Steven says:

    senang bisa membantu🙂

  47. lin says:

    tutorial ini sangat membantu saia, bisa tolong dilanjutkan hingga selesai🙂

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: