Happyfaces archetype tutorial. Easy JSF with custom components!

Update: check out my react maven archetype!

If you want to create a new JSF project from scratch it would really take significant amount of time. All the configurations, problem solving and learning takes more time than we would like. Maven archetypes are great solution to this problem. Lets try my new project – happyfaces maven archetype.

To get started you will need: My Sql database, Maven, Tomcat and of course Java and some IDE (I use Eclipse). Archetype creates JSF 2.2/Spring/Tomcat/Mysql project for you. It already contains small sample application. The reason it is not removed is because of time constraint I do not provide very good documentation and it’s best to learn by doing. After project is created take a look at readme.txt to see what files you need to remove if you don’t want an example.

Project creation

Archetype is already in maven central so you simply need to run this command:

  mvn archetype:generate -DarchetypeGroupId=com.github.happyfaces -DarchetypeArtifactId=happyfaces-archetype -DarchetypeVersion=1.0.2 -DgroupId=com.test -DartifactId=MyTestApp

Open eclipse, Import -> Maven -> Existing Maven Projects and select your newly created project. Open Servers view add your tomcat server and add project MyTestApp to tomcat. Open filter-dev.properties and enter your database name (need to create it in MySql of course) and db username/password.

And that’s almost it! We would be already starting up tomcat and enjoying our awesome project. However I decided to use QueryDSL with spring-data as another layer for database access and it needs to generate some code. For some reason it doesn’t work out of box in eclipse. If you know how to do it let me know! So lets go to the project’s root dir and run this maven command:

  mvn generate-sources

Now there should be bunch of source files in target/generated-sources/java. You should add it to build path (left click on this directory in eclipse -> Build path -> Use as source folder). And that’s it! You can start tomcat and go to http://localhost:8080/MyTestApp now. In case you get some errors on startup try to Project -> Clean.

P.S. If you see annoying You need to run build with JDK or have tools.jar on the classpath. error in pom, take a look here.

Sample application

Lets review what do we have now. After project start up you should see login screen like this.


You can login with user=admin password=admin. Application already has spring security configured. On top right corner you can change language and logout. There are few sample windows: Customers, Accounts, Operations where user can view list of those entities, delete them, view details, edit details, export list and of course search by various properties. Also it has REST webservices exposed. In the next chapter we will see how the code for all this looks.




Getting familiar with code base

It is easy if you are familiar with JSF. Lets take an Account window as an example and figure out how it is implemented. For all pages template.xhtml is used. It also provides countdown dialog before logging out user if session is running out. Template is like this: top header.xhtml, bottom – footer.xhtml, left – menu.xhtml and in the center is content where accounts.xhtml content will be put. Its pretty standard facelets templating and of course you can modify it according to your needs. If you open accounts.xhtml you will notice how little code there are(especially if you remove comments). Everything is implemented using custom JSF components. You will find custom components in webapp/resources/tags directory and taglibs in webapp/taglib directory.

Now on the Java side backing bean is implemented in AccountBean.java. It is surprisingly short for a backing bean which is doing so much. However it does extend BaseBean.java and that’s how custom JSF components are able to do their magic. In simplest CRUD cases you basically don’t need to do anything – simply extend BaseBean.java! AccountBean also has Spring service injected – AccountService.java. It also extends BaseService.java which provides all the required transactional methods for searching, loading, deleting etc. That’s why AccountService does not contains any code! And you can search lists, delete and edit entities without writing any code at all – simply use custom components and extend from base classes!

Spring-data repositories is used for data access and in case you need some custom query you don’t even need to write hql. Take a look at repository UserRepository.java for example. Other repositories are in the same package, but they don’t have any custom queries for this example.

Application configurations can be found under WEB-INF directory. Security uses spring security framework and is configured in applicationContext-security.xml. Login logic is done in UserService.java. REST webservices are configured in springREST-servlet.xml and example can be viewed at CustomerRestController.java. And of course standard configurations: applicationContext.xml for Spring, faces-config.xml for JSF and web.xml for servlets.

After reviewing code base its time to get our hands dirty. Lets try to implement a new CRUD window for a new entity – Issue.java.

Implementing new window

Lets say users of our sample application needs to solve some issues time to time. Of course the best way to do that is incorporate issue management into already existing application. Lets say simple issue has Title, Description, Status, Date and Account for which it is created.

Lets create simple CRUD for it. Starting with Issue.java and IssueStatus.java enum.

public enum IssueStatus {
    NEW(1, "IssueStatus.NEW"),
    WORKING(2, "IssueStatus.WORKING"),
    SOLVED(3, "IssueStatus.SOLVED");
    private Integer id;
    private String label;
    private IssueStatus(Integer id, String label) {
        this.id = id;
        this.label = label;
    public Integer getId() {
        return id;
    public String getLabel() {
        return label;

@Table(name = "ISSUE")
public class Issue extends BaseEntity {

    private static final long serialVersionUID = 1L;

    @Column(name = "TITLE", nullable = false)
    private String title;

    @Column(name = "DESCRIPTION", length = 5000)
    private String description;
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "ACCOUNT_ID")
    private Account account;
    @Column(name = "ISSUE_DATE")
    private Date issueDate;
    @Enumerated(value = EnumType.STRING)
    @Column(name = "ISSUE_STATUS")
    private IssueStatus status;

    // getters setters skipped

Don’t forget to run mvn generate-sources after adding/editing entity and also don’t forget to add translatable messages to messages.properties:

IssueStatus.NEW=New issue

Now we need to create spring service and jsf backing bean for Issue entity:

// Add spring data repository. Required for service.
public interface IssueRepository extends GenericRepository<Issue, Long> {

public interface IIssueService extends IService<Issue> {

// simply extend BaseService
public class IssueService extends BaseService<Issue> implements IIssueService {
    private static final long serialVersionUID = 1L;
    private IssueRepository repository;
    @SuppressWarnings({ "unchecked", "rawtypes" })
    protected JpaRepository<Issue, Long> getRepository() {
        return (JpaRepository) repository;

@ManagedBean(name = "issueBean")
public class IssueBean extends BaseBean<Issue> {

    private static final long serialVersionUID = 1L;
    @ManagedProperty(value = "#{issueService}")
    private IIssueService issueService;

    public IssueBean() {

    protected IService<Issue> getPersistenceService() {
        return issueService;
    public void setIssueService(IIssueService issueService) {
        this.issueService = issueService;
     * Fetch account field so no LazyInitialize exception is thrown when
     * we access it from account list view.
     * @see com.test.beans.base.BaseBean#getListFieldsToFetch()
    protected List<String> getListFieldsToFetch() {
        return Arrays.asList("account");
     * Fetch customer field so no LazyInitialize exception is thrown when
     * we access it from account edit view.
     * @see com.test.beans.base.BaseBean#getFormFieldsToFetch()
    protected List<String> getFormFieldsToFetch() {
        return Arrays.asList("account");

As you can see we are barely writing any code – simply creating classes that extend something. One exception is overridden getFormFieldsToFetch() and getListFieldsToFetch() methods which does nothing more than select * from Issue i join fetch i.account. That way we don’t need to use eager fetch on domain object and simply fetch account on select. If we wouldn’t fetch an account and would like to show its name we would get LazyInitializeException. When overriding those methods we simply let BaseBean to take care of fetching (take a look at BaseBean.initEntity() method for example).

So from Java part that’s it. Pretty cool huh? πŸ™‚ Now lets add xhtmls and enjoy our new window πŸ™‚ We need to add issues.xhml for issue list, issueEdit.xhtml for edit and view and of course modify menu.xhtml and faces-config.xml.

Append this navigation case to faces-config.xml:


Add this sub menu to menu.xhtml:

<p:submenu label="#{messages['menu.issues']}">
<p:menuitem value="#{messages['menu.issues']}" outcome="issues" />

Create new issues.xhtml in pages dir:

<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:hftl="http://hftl.org" xmlns:hf="http://xmlns.jcp.org/jsf/composite/tags"

    <ui:param name="pageTitle" value="#{messages['issue.search']}" />

    <ui:define name="content">
        <hf:searchPanel id="searchPanel" columns="3" backingBean="#{issueBean}">
            <hf:searchField label="#{messages['issue.title']}" field="title" />
            <hf:searchField label="#{messages['issue.status']}" field="status" />
            <hf:searchField label="#{messages['issue.issueDate']}" field="issueDate" rangeSearch="true" />
            <hf:searchField id="accountField" label="#{messages['issue.account']}" field="account" childField="accountNumber" popup="true" />
        <hftl:dataList label="#{messages['issue.search.results']}" backingBean="#{issueBean}">
            <hftl:column label="#{messages['issue.title']}" field="title" />
            <hftl:column label="#{messages['issue.status']}" field="status" childField="label" isMessage="true" sort="false" />
            <hftl:column label="#{messages['issue.issueDate']}" field="issueDate" isDate="true" />
            <hftl:column label="#{messages['issue.account']}" field="account" childField="accountNumber" />
            <hftl:actionsColumn />
        <hftl:entityPopup id="accountsPopup" header="#{messages['account.search']}" updateField=":searchPanel:searchForm:accountField:account_child" selection="#{issueBean.filters['account']}"
            backingBean="#{accountBean}" searchField1Label="#{messages['account.accountNumber']}" searchField1="accountNumber"
            column1Label="#{messages['account.accountNumber']}" column1="accountNumber" />

Create new issueEdit.xhtml in pages dir:

<ui:composition xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://xmlns.jcp.org/jsf/html" xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:p="http://primefaces.org/ui" xmlns:ui="http://xmlns.jcp.org/jsf/facelets" xmlns:hf="http://xmlns.jcp.org/jsf/composite/tags" xmlns:hftl="http://hftl.org"
    <ui:define name="metadata">
            <f:viewParam name="edit" rendered="#{sessionPreferences.editAllowed}" value="#{issueBean.edit}" />
            <f:viewParam name="objectId" value="#{issueBean.objectId}" />
    <ui:param name="pageTitle" value="#{messages['issue.page.title']}" />
    <ui:define name="content">
        <hf:formPanel id="formPanel" label="#{messages['issue.page.panel']}" backingBean="#{issueBean}" >
            <hf:formField label="#{messages['issue.title']}" field="title" />
            <hf:formField label="#{messages['issue.description']}" field="description" textArea="true" />
            <hf:formField label="#{messages['issue.status']}" field="status" />
            <hf:formField label="#{messages['issue.issueDate']}" field="issueDate" rangeSearch="true" />
            <hf:formEntityField id="account" label="#{messages['issue.account']}" field="account" childField="accountNumber" popup="true" />
        <hftl:entityPopup id="accountsPopup" header="#{messages['account.search']}" updateField=":formPanel:formId:account:account" selection="#{issueBean.entity.account}"
            backingBean="#{accountBean}" searchField1Label="#{messages['account.accountNumber']}" searchField1="accountNumber"
            column1Label="#{messages['account.accountNumber']}" column1="accountNumber" />

And of course messages.properties:

issue.search=Issue search
issue.search.results=Search results
issue.page.panel=Issue edit

And that’s it! Now you can search issues by title, by date, by account, by status. Go on create 10 or 20 of issues. You will have lazy datatable with pagination and sorting. You can also delete them or edit them. Or simply view details. Basically without writing any code. You can still use regular JSF. You can mix custom components with regular JSF tags. You can also modify those components or code to fit your needs. It is not a black box framework – its simply maven archetype and you own all the code! Sure all those classes we had to create could have been easily generated. That would be cool. Maybe some time in the future πŸ˜‰

New issues window should look something like this after you are done:


Custom search

Creating simple crud pages is really easy with happyfaces custom components. But most of the time we need to work on something more complicated. That is not problem here: you can still use your regular jsf, implement additional method in services and modify all base classes provided by archetype. One of the most used feature is search. Searching auto magically is really cool but sometimes it can be a little bit limited. Of course you can simply implement new methods or create more complex page from scratch, but sometimes it would be nice to mix it up – have custom components search and some customized search working together.

First of all I recommend you to read a little bit about QueryDSL and then understand the magic of how the search with custom components works. Take a look at BaseService.getPredicate() method for that. If I need to explain how it works in one sentence I would say that JSF search component simply puts filter key (which is property to search) and value into filters map and then it is processed in getPredicate() method.

So lets say we want to see only issues that are not yet solved. That means new and working issues is shown and solved ones are filtered out. Status search filter can select only single status so to solve this we have to add another non standard filter. Lets use checkbox for that. Your issues.xhtml search part should look like this:

<hf:searchPanel id="searchPanel" columns="3" backingBean="#{issueBean}">
   <hf:searchField label="#{messages['issue.title']}" field="title" />
   <hf:searchField label="#{messages['issue.status']}" field="status" />
   <hf:searchField label="#{messages['issue.issueDate']}" field="issueDate" rangeSearch="true" />
   <hf:searchField id="accountField" label="#{messages['issue.account']}" field="account" childField="accountNumber" popup="true" />
   <h:panelGrid columns="2">
      <p:outputLabel for="excludeSolved" value="#{messages['issue.excludeSolved']}" />
      <p:selectBooleanCheckbox id="excludeSolved" value="#{issueBean.filters['issue.notSolved']}" />

We’ve added custom filter. However it will not be processed by getPredicate() method because key “issue.notSolved” is not property of Issue. The good news getPredicate() invokes processNonStandardFilters() method before processing filters map. We can override this method in our IssueService.java and use it to filter out all solved issues. It should look like this:

    protected BooleanExpression processNonStandardFilters(Map<String, Object> filters, List<String> filtersToRemove,
            @SuppressWarnings("rawtypes") PathBuilder pathBuilder) {
        BooleanExpression expression = null;
        Boolean notClosedFilter = (Boolean) filters.get("issue.notSolved");
        if (notClosedFilter != null) {
            if (notClosedFilter) {
                expression = pathBuilder.get("status").ne(IssueStatus.SOLVED);

        return expression;

This code returns predicate that shows only issues with status NOT equal to SOLVED. Also don’t forget to remove that filter (by adding it to filtersToRemove list) so it won’t be processed again.

Of course this is only one of the ways to solve such a problem. You are of course free to modify code as you like and as your project requires but for not too complicated searches this method really allows mixing standard and customized searches easily.

Here is what the end result with “not solved” filter looks like:


The end

That is it. I hope you liked this tutorial. As you can see this archetype could save you quite some time. There are more stuff like unit tests and integration tests – they are pre configured with dbunit and load spring context! Also you can run mvn site:run and get maven site with various reports up and running in seconds! And for REST web services you just need to implement controller for it. Take a look at HappyFacesExceptionHandler.java for some centralized error handling for your application. There are much more πŸ™‚ I hope you will find all of this useful.

You can find the project on github here. I’m really looking forward to feedback! Let me know what do you think.


One thought on “Happyfaces archetype tutorial. Easy JSF with custom components!

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s