Skip to main content

Develop web application with netbeans ,seam and Glassfish

Posted by kalali on August 15, 2006 at 5:05 AM PDT

In this two part series I will try to show you how easily you can  build applications using NetBeans 5.5 based on  seam , facelets , jsf and new EJB 3 standard.

I will not discuss any of framework in details as you can find detailed information about each of them in their homepage and some other articles.
I want just show , How you can use NetBeans with some leading frameworks to build your web based applications. I will not discuss NetBeans specific tasks in details .
I will more focus on leveraging this stuff together using NetBeans IDE.

What you will need to follow  this series :

  • NetBeans enterprise edition 5.5 , you will need Glassfish or JBoss to continue with this series. check and make sure that your NetBeans has application server bundled otherwise get a copy of glassfish from its website.
  • seam 1.0.1 GA  or newer.

seam distribution contain Facelets too , but i strongly suggest you get Facelets distribution separately and take a look at its samples and very good documentation. indeed both Facelets and seam has very good documentation.

In this entry I will introduce each of this frameworks in very brief  to make the series stand alone , and i will show you how to setup the development environment and we will go with first part which is developing seam layer codes.

JBoss seam is created to leverage maximum possible feature of Java EE 5 standards like JSF and EJB3.
seam , seamlessly integrate EJB3 as a backend with JSF as presentation , meanwhile provide management of long running process
by using JBPM . and give you ability to focus on your business logic rather than silly data providing stuff. By leveraging Facelets helps you to do even more with seam and JSF.

To name its features I can say:

  • Lesser XML, More Annotation. (please do not blame me for naming annotation and XML in one line :-))
  • it let you go with your business logic rather thinking and resolving some common issue like user conversation state.
  • seam has a more flexible context model , it has 8 context , by means of this context you can manage your application more effective. for example a business process live in business process context .
  • Accessing each component in entire seam context with one unique name.
  • Managing workplaces and conversations .
  • It easily will let you develop Portlet by providing a Portlet context . we will discuss this item in latter parts

With many more features.

But about JSF , JSF is  a web framework , it is  Standard and  Developed under JSR 127.
Some of JSF features are as follow:

  •  User interface framework
  •  Server-side UI components
  •  Event model , something like desktop applications event model , but very reduced.
  •  Component state
  •  Renderers , Render Kits , for example ADF faces has a telnet render which make it possible to render a ADF faces application for a  telnet client.
  •  Validation
  •  Type conversion
  •  Internationalization

about Facelets , we will discuss more in next articles , but for now you should know that Facelets bring some view related enhancement and features to JSF community .
To name some of features :

  • Facelets make it possible to develop your entire web pages using your favorite page designer like Dream weaver or Microsoft FrontPage. to achieve this feature it introduce a new attribute, jsfc ,that make it possible to change each html element  to a JSF equal component. it is similar to Tapestry 's jwcid attribute. So you can use all binding and event handling stuff of JSF and availability and ease of use of html WYSIWYG.
  • Facelets provide a template-ing  features like Velocity's for JSF . it allows you to test JSF views out of container.
  • Some decoration features like what tile bring to struts community and SiteMesh ,generally, to all java based web application.

lets start the job of creating simplest sample ;) .

I assume that you download seam and extract it in seam_home Also your NetBeans 5.5 is running and an application server capable of  containing ejb3 (Glassfish) is configured with your IDE.

for sake of simplicity we make one   Library in our NetBeans IDE to make our job easier. as you know each library could contain some jar files, etc...
 

Create a library name it seam and add the following jar files to it , the first
seam_home\jboss-seam.jar
seam_home\jboss-seam-ui.jar
seam_home\hibernate-all.jar
seam_home\thirdparty-all.jar

add seam library  to Registeration-EJBModule and Registeration-WebModule

Switch to runtime view (CTRL+5).Extend database node  , if you have no database created in your embedded derby  then create a database and create a table with following  characteristics
Table Name: users
Fields :

username varcahr(255) , primary key
password varchar(255) , not null
name varcahr(255) , not null

after you create this table , create a new enterprise application project by going to , file>new project>enterprise application
name it Registeration. make sure that you have selected the Java EE 5 as j2ee version.

go to project view (CTRL+1) And select Registeration-ejbModule , right click on it and select CMP entity bean from database...
Now you should be able to select the JDBC connection that you have made in above step and give it a package name.
click next and select users table from left column and add it to right column.
click finish.
That's it , you have your CMP ready to go.

  • what we need to add to the CMP bean class in addition to its created structure
  • another constructor with all the CMP  fields.
  • some annotation for getters , to help us in validation

final shape of users CMP will be like :

 

package cmps;

import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.validator.Length;
import org.hibernate.validator.NotNull;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
/**
*
* @author Masoud Kalali
*/
@Entity
@Name("user")
@Scope(org.jboss.seam.ScopeType.SESSION)
@Table(name="users")
public class Users implements Serializable{
   private static final long serialVersionUID = 1881413500711441951L;
    private String username;

    private String password;

    private String name;
   
    /** Creates a new instance of Users */
    public Users() {
    }

   
    public  Users(String name, String password, String username)
{
this.name = name;
this.password = password;
this.username = username;
}
   
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "username", nullable = false)
     @Length(min=5, max=15)
    public String getUsername() {
        return this.username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    @Column(name = "password", nullable = false)
     @Length(min=5, max=15)
    public String getPassword() {
        return this.password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Column(name = "name", nullable = false)
     @Length(min=5, max=15)
    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }
   
}

 

we are finished with our POJO EJB :-) , now lets go and handle web layer stuff , from now we are working with seam view layer and JSF , I will talk about Facelets later in other articles of this series.

as I said in sample scenario we have just one action , so we can use a  managed bean or plain java object or whatever that is useable here as action listener or use a stateless session bean (using session bean is what JBoss offer) so we will use a stateless session bean to implement our action listener , it will also helps you to see how an stateless session bean is implemented in java EE 5.
so create a session bean by using , file > new > session bean , now you can select session bean type to be stateless , and change the package name to be sbeans
click finish  , editor will open up and show you the stateless seasion bean class.   
change the class body , in a way that final class looks like :

import cmps.Users;
import java.util.List;

import javax.ejb.Stateless;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.validator.Valid;
import org.jboss.seam.annotations.Factory;


import org.jboss.seam.annotations.IfInvalid;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Outcome;
import org.jboss.seam.annotations.datamodel.DataModel;
import org.jboss.seam.core.FacesMessages;
import org.jboss.seam.ejb.SeamInterceptor;

@Stateless
@Name("")
public class ActionBean implements sbeans.ActionLocal
{
  
   @IfInvalid(outcome=Outcome.REDISPLAY)
   public String ()
   {
      List existing = em.createQuery("select username from User where username=:username")
         .setParameter("username", user.getUsername())
         .getResultList();
      if (existing.size()==0)
      {
         em.persist(user);
         return "success";
      }
      else
      {
         FacesMessages.instance().add("User #{user.username} already exists");
         return "success";
      }
   }

}

we will need to add same method signature to our session bean local interface , so add the method signature to ActionLocal class. it will looks like :

package sbeans;


/**
* This is the business interface for Action enterprise bean.
*/
public interface ActionLocal {
      public String ();
}

now we are finished with the action , you may ask what are those annotation stuff in the session bean , so I should ask you to take a look at seam reference or wait until next part of this series. I should say that it is a very same version of seam sample that is implemented again in NetBeans IDE.
we are finished with EJBModule for now , lets take a look at what we will have in web module. first of all you need to add JSF framework to web module to do this , right click on web module and select properties , go to frameworks node and add JSF framework to the project. In web module we just have 2 JSF pages , one to , one to show the that s/he ed . Create following JSF files ,

register.jsp same as seam sample register.jsp , used for registering purpose
registered.jsp same as seam sample registered.jsp , used for showing the user that he/she is ed
we need to add some navigation case to our faces-config.xml , so extend web module note and under configuration files open the faces-config.xml we should add 4 navigation case to it , so right click inside the editor ,which show content of faces-config.xml, and select add navigation rule. a dialog will open , just fill the dialog as following table show

Rule From View /register.jsp

Now right click in the editor and add 4 new navigation case , these cases will handle navigating from one view to another.

From View From Outcome To view
/register.jsp success registered.jsp

lets code with the register.jsp , open the register.jsp in your NetBeans editor change the content to :

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<%@ taglib prefix="s" uri="http://jboss.com/products/seam/taglib"%>
<html>
<head>
<title> New User</title>
</head>
<body>
<f:view>
<h:form>
<table border="0">
              <s:validateAll>
<tr>
<td>Username</td>
<td><h:inputText id="username" value="#{user.username}" required="true" /></td>
<td>      <h:message for="username"/>       </td>
</tr>
<tr>
<td>Real Name</td>
<td><h:inputText  id="name" value="#{user.name}" required="true" /></td>
<td>      <h:message for="name"/>       </td>
</tr>
<tr>
<td>Password</td>
<td><h:inputSecret id="password" value="#{user.password}"  required="true" /></td>
<td>      <h:message for="password"/>       </td>
</tr>
          </s:validateAll>
</table>
<h:messages globalOnly="true"/>
<h:commandButton type="submit" value="" action="#{.}"/>
</h:form>
</f:view>
</body>
</html>

No we need to create the registered.jsp which show that our user is registered. open the file in your editor and change its content to looks like :

<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<html>
<head>
<title>Successfully ed New User</title>
</head>
<body>
<f:view>
Welcome, <h:outputText value="#{user.name}"/>,
you are successfully ed as <h:outputText value="#{user.username}"/>.
</f:view>
</body>
</html>

Now we are almost finished with JSf files , there are some changes that we should make in web.xml and faces-config.xml.first open web.xml and add the following lines to it.make sure the you add them directly inside node.

 <context-param>
<description>
</description>
<param-name>org.jboss.seam.core.init.jndiPattern</param-name>
<param-value>java:comp/env/registration/#{ejbName}/local</param-value>
</context-param>

<listener>
<listener-class>org.jboss.seam.servlet.SeamListener</listener-class>
</listener>

<ejb-local-ref>
<ejb-ref-name>registration/RegisterActionBean/local</ejb-ref-name>
<ejb-ref-type>Session</ejb-ref-type>
<local>sbeans.RegisterActionLocal</local>
< ejb-link>RegisterActionBean</ejb-link>
</ejb-local-ref>

Now open faces-config.xml and add the following lines to it.

<lifecycle> <phase-listener>org.jboss.seam.jsf.SeamPhaseListener</phase-listener> </lifecycle>

That's it , you are finished creating your first seam sample in netbeans , lets execute the application and see the result. press f6 and wait until your browser opens , navigate to http://localhost:8080/Registration-WebModule/faces/register.jsp enter some information and then press register button.

You can check whether it applied or not by switching to runtime view and checking your Users table data . you can find complete explanation of jsp/java codes in Seam tutorial chapter 1 at : http://docs.jboss.com/seam/1.0.0.GA/reference/en/html/tutorial.html


Related Topics >>