UaiMockServer – A lot of new Features to help you with your tests

Hello, how are you?

The newest release of uaiMockVersion has a lot of new features that will influenciate a lot the HTTP mock open sources frameworks.

The first big feature is a GUI that will allow you to edit your requests:

Index

Index

You will not need to edit those boring configuration files anymore, all you need to do is to use access the GUI through the default url: http://localhost:1234/uaiGui/index

Another feature allows you to analyse everything in your request/response, very easily. All you need to do is to go to the Log tab and fire the request:

Request Log

Request Log

And if you detail a success request you will see:

Success Request

Success Request

And if you detail a request with error:

Error Detail 01

Error Detail 01

To help you to find out what kind of error just happened, you will be able to see the server log:

Error Detail 02

Error Detail 02

The last, but not least, feature is a JUnit runner that will control the server for you:

UaiMockServer JUnit Runner

UaiMockServer JUnit Runner

Using like the sample above you will not need to start and stop the uaiMockServer manually. Using like above the uaiMockServer will search for the default file named: uaiMockServer.json

You could also set specific config file:

UaiMockServer JUnit Runner Configuration

UaiMockServer JUnit Runner Configuration

And if you are a Spring user, you could also use the Spring Runner:

UaiMockServer JUnit SpringRunner Configuration

UaiMockServer JUnit SpringRunner Configuration

The last update in this new version was to change the config file from HCON to JSON. Unfortunately you will need to change your config file from HCON to JSON, sorry for that. I could not keep using the HCON type anymore.

The config file will look like below:

New Configuration File as JSON

New Configuration File as JSON

One advantage of the config file as JSON is that any file editor will be able to give you a better support.

The project site: http://uaimockserver.com/

Source code: https://github.com/uaihebert/uaiMockServer

Standalone version and config example: https://sourceforge.net/projects/uaimockserver/

Maven import:

<dependency>
    <groupId>uaihebert.com</groupId>
    <artifactId>uaiMockServer</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>

I hope you liked the news.

If you have any questions/doubt/suggestion just post it below.

o_

uaiMockServer – Create a Mock Rest Server with a single command line

Hello how are you?

Have you ever needed to invoke a REST service, but this service was not created yet?

Imagine that you are developing an APP that needs to invoke an inexistent REST service. You will need to create a fake code that will be replaced once that the real code is finished. No matter if you are working with Java, .NET, PHP, Ruby, Python, etc. You will always need to create a fake invocation method if the REST service is not ready yet.

When we are programming in our unitary test we face the same problem. We will need to create a Mock code that will be invoked during the tests. The problem with this approach is that the real code is never invoked.

How can we solve this problem? Is there a solution that works for delphi, .NET, PHP, Java, Android, IOS, WindowsPhone, etc?

I present to you now my most recent creation: “uaiMockServer”.

With uaiMockServer you will be create a mock server using only a JAR file and a config file. With this server you will be able to execute real HTTP requests, but using your test data.

There are two ways of using uaiMockServer: Standalone and Unit Tests

Standalone

To use the uaiMockServer as a Standalone server you will manually type the command that starts it. Run the command in a prompt:

java -jar uaiMockServer-{VERSION}.Standalone.jar

You will only need the config file, that we will talk about very soon.

In the sample config file there is a mapping using the port 1234. If you are using linux, type the command:

curl localhost:1234/uaiMockServer/

The HTTP Response will contain a JSON.

Unit Test

First step is to add the project in your pom:

<dependency>
   <groupId>uaihebert.com</groupId>
   <artifactId>uaiMockServer</artifactId>
   <version>1.0.1</version>
   <scope>test</scope>
</dependency>

Now you can create a test code like:

public class YourTest {
    private static UaiMockServer uaiMockServer;
 
    @BeforeClass
    public static void beforeClass() {
        uaiMockServer = UaiMockServer.start();
    }
 
    @AfterClass
    public static void afterClass() {
        uaiMockServer.shutdown();
    }
 
    @Test
    public void aTest() {
        final Customer customer = // invoke the URL
        assertTrue(customer != null);
    }
}

You will be able to invoke the URL using any kind of framework. Below you will see a code sample using the RestEasy framework doing a request mapped in the sample config file (that we will see soon):

@Test
public void isGetRootReturning200() {
    final String url = "http://localhost:1234/uaiMockServer/";
 
    Client client = ClientBuilder.newClient();
    Response response = client.target(url).request().get();
 
    assertEquals(200, response.getStatus());
}

What is the gain in the test? You will not need a mock code anymore. You can fire a HTTP request from your JUnit test.

Configuration

To run the project you will need a config file. A simple sample would be like below:

com.uaihebert.uaimockserver {
    port = 1234
    host = localhost
    fileLog = false
    consoleLog = true
    context = /uaiMockServer
    defaultContentTypeResponse = "text/html;charset=UTF-8"
    routes = [
        {
            request {
                path = "/"
                method = "GET"
            }
            response {
                contentType = "application/json;charset=UTF-8"
                statusCode = 200
                body = """{"mockBody":{"title":"Hello World"}}"""
            }
        }
    ]
}

The file must have the .config extension and is not in the JSON format, but has a superset format of the JSON – HCON – used in configurations files (click here for more details).

With this file you can set up the port that will be invoked, the host, header, queryParm and other several options that are described in the uaiMockServer documentation.

Notice that in the configuration was created a request and a response; with these configurations you can mock every request that you want.

If you are going to use the Standalone version the config file must be in the same directory of the JAR file. You can set a different path with the command:

java -jar uaiMockServer-{VERSION}.Standalone.jar FULL_FILE_PATH

If you will run the project in your Unit Tests (like JUnit) you must put the config file in the “src/test/resources” maven folder. Or you can pass the full path like:

uaiMockServer = UaiMockServer.start(FULL_FILE_PATH);

It is free?

Yes, it is. Use it at your will.

Is open source? Yes: https://github.com/uaihebert/uaiMockServer

Where is the documentation? http://uaimockserver.com/

Where can I find the Standalone and the sample Config file: http://sourceforge.net/projects/uaimockserver/files/

It has any automated test? Yes, we have a lot of tests and we got 100% code coverage.

What about performance?

In the GIT there is a test that executes 300 requests in less than 2s.

Thanks to:

Complete Web Application: Angular Twitter Bootstrap Spring MVC, Data and Security

Hello, how are you?

Today we will see how to create a complete Java web application using Spring, Angular, JQuery, Twitter Bootstrap, Tiles, Maven, Tomcat, JPA/Hibernate.

The project that will be done here in this post will be used in another post that I will write, because of this future post, in this post will be described a detailed environment configuration. I will be using linux as my operational system (OS), but almost nothing will change if you use Windows or other OS.

I received a lot of emails asking for a post using Spring in a full web application, all the applications already posted here were using JEE technology (JSF, EJB, JPA). In this post we will see a project using Spring framework with the following modules: Spring MVC, SpringData e Spring Security. We will see how to do internationalization (i18n) with SpringMVC and templates with Tiles framework.

Postgre will be the database used here, but if you want use it with MySQL just add the MySQL jar to the project and change some configuration. In this post will be displayed both Postgre and MySQL configurations.

It is possible to find the source code of this project in the last page of this post, and to make everybody happy, 3 downloading ways will be available in the end of the post. In this post we will focus in the Spring/JPA code and some of the JPS code highlighting the Angular and Bootstrap libraries, all the JSP code, classes and configurations can be downloaded in the last page.

What we will see in here:

Page 02: Environment Setup
Page 03: Creating the project
Page 04: Understanding the “pom.xml”, “log4j.xml” and the “context.xml” files
Page 05: Creating the Spring and the project XMLs
Page 06: Tiles – Page templates
Page 07: Project Model Classes
Page 08: Using SpringData as Repository (DAO); creating User Service
Page 09: Using SpringData as Repository (DAO); creating Contact Service
Page 10: Creating the Controllers
Page 11: Using Restful approach with SpringMVC
Page 12: Understanding the Login, SpringMVC Interceptor and the Security Rules
Page 13: First Contact with Angular.js and the SpringMVC
Page 14: Using Angular.js bind in a HTML table
Page 15: Internationalization (i18n) with Spring
Page 16: Understanding the Twitter Bootstrap role
Page 17: Running the project

Let us get started!

JSF Mini Book – Tips, concepts and good practices

Hello, how are you?

This post was written as an article to a Brazilian Java magazine. Unfortunately it was not published =(. I decided to post it here! =D

This post will display tips, concepts and solutions to developers that works with JSF 2.0 every day. We will see the concepts and the right way of using the JSF to help those who works with this technology or has interest in learning it – students or developers that works with others frameworks. Using this tool without knowledge of it will give more problems to your software instead solutions. It is really needed to understand how the JSF works, how it handles each user action request and how it is possible to build a software code that will optimize the JSF usage.

We will see some technical questions like: importing images/javascript into the pages, how to upgrade a JSF 1.2 app to a JSF 2.0, using Ajax that is a technology of asynchronously requests, and more; we will see some needed theory that is usually set aside.

With JSF we will be able to face one of the major problems of the web technology, code reuse. The JSF allow us to reuse the code of pages, javascript and validations in Java code that are used in the pages. When we reuse the code we will reduce the maintenance time expend, the change impacts will reduce also and others.

Today we will see:

  • Page 02: Creating a JSF project
  • Page 03: How to import CSS/Images/JavaScript as Library
  • Page 04: XHTML page reuse with Facelets
  • Page 05: JSP x Facelets
  • Page 06: Hiding the comments of the xhtml page
  • Page 07: Avoiding @SessionScoped type. Check all Scope Types
  • Page 08: Avoiding the use of logic in the xhtml page
  • Page 09: Use the h:outputLink to navigate
  • Page 10: Ajax with JSF 2.0
  • Page 11: Smoothing the JSF development
  • Page 12: Upgrading from JSF 1.2 to 2.0
  • Page 13: How to receive null value from the view
  • Page 14: Choosing between action and actionListener
  • Page 15: Flash Scope
  • Page 16: Dot no mix JSF Implementations
  • Page 17: Internationalization as good practice
  • Page 18: JSF 2.2 new features

This post is a celebration for the mark of 200k of viewers that we received in the two years of existence of this blog.

“The Father of Java” uses Jelastic

Hello, how are you?

Today we will have an unusual post, it is more like a good news about this framework that is getting its space in the development world. Jelastic has as characteristic to work as a container of containers.

This news were sent to me by Judah Johns from Jelastic.

As far as we can tell, this is the first PaaS that Dr. Gosling has given his endorsement. We reached out to him to confirm it, and sure enough, it turns out that he is a very happy Jelastic user and is very excited about what he can do with it and what he will be doing with it in the near future.

Though I know that in our community, most everyone knows who James Gosling is, there a lot of younger guys learning Java that have never heard of him, like my 13 year-old brother, Daniel, who is quite an avid Java coder. So, who is James Gosling?

The Dr. James Gosling Bio

This bio comes from Gosling’s own blog: James Gosling received a BSc in Computer Science from the University of Calgary, Canada in 1977. He received a PhD in Computer Science from Carnegie-Mellon University in 1983. The title of his thesis was “The Algebraic Manipulation of Constraints”. He spent many years as a VP & Fellow at Sun Microsystems. He has built satellite data acquisition systems, a multiprocessor version of Unix, several compilers, mail systems and window managers. He has also built a WYSIWYG text editor, a constraint based drawing editor and a text editor called `Emacs’ for Unix systems.

At Sun his early activity was as lead engineer of the NeWS window system. He did the original design of the Java programming language and implemented its original compiler and virtual machine. He has been a contributor to the Real-Time Specification for Java, and a researcher at Sun labs where his primary interest was software development tools. He then was the Chief Technology Officer of Sun’s Developer Products Group and the CTO of Sun’s Client Software Group. He briefly worked for Oracle after the acquisition of Sun. After a year off, he spent some time at Google and is now the chief software architect at Liquid Robotics where he spends his time writing software for the Wave Glider, an autonomous ocean-going robot.

Full Web Application with Tomcat JSF Primefaces JPA Hibernate

Hello, how are you?

We are happy for the 100k visitors. To celebrate this mark in this blog we created this post that will show how to create a full web application using the following tools: Tomcat7, JSF2 (Facelets and Libraries) with Primefaces (with AutoComplete), JPA / Hibernate (with a relationship NxN), Login with Filter.

If you want to see a full web application with JSF + EJB + JPA + JBoss 7 click here.

To run the code of this post you will need the artifacts bellow (all jar file you will find in the last page of this post):

You can use the any database you want, you will need the specific driver of the database and to edit the URL connection at the persistence.xml.

At the end of this post you will find the source code with all needed libraries to download.

What you will see today in this post:

  • Page 02: Entity classes of the model. A relationship NxN (@ManyToMany), NamedQueries with JoinFetch, Enum as attribute.
  • Page 03: Generic DAO, application transaction methods, generic methods to populate query parameters.
  • Page 04: Façades an transactions, using the method findReferenceOnly, care using the entityManager.merge() method.
  • Page 05: Filters.
  • Page 06: ManagedBeans. How to inject a ManagedBean inside another ManagedBean, observations about @ViewScoped.
  • Page 07: JSFMessageUtil.
  • Page 08: Configurations file: log4j.properties, messages.properties.
  • Page 09: xhtml pages, Facelets.
  • Page 10: Primefaces AutoComplete, JSF Converter with “forClass”.
  • Page 11: Easiest way to use CSS/javascript/images with JSF.
  • Page 12: “web.xml” configurations.
  • Page 13: Increasing the security of your application.
  • Page 14: Running the application.
  • Page 15: BUG_FIX

The application that you will find in here will have a Dog and Person CRUD (Create, Read, Update, and Delete); only the ADMIN will have access to the Dog CRUD. Before you run this application you should create a database named “JSFCrudDB”.

Lazy JSF Datatable Pagination (Primefaces)

Hello, how are you?

Today we will do JSF datatable pagination with a Lazy List with a view scoped managed bean. What all those words/expressions mean?

There are several JSF frameworks today that provide datatables with a ready pagination, columns sorter and others functionalities. Today we will use the Primefaces datatable.

Usually the datatables will put the displayed List, with the entities, inside the user http session. Increasing the objects inside the user session will have a direct impact on the server performance; each user that displays a datatable,  that keeps a list in the session, will be allocating more and more memory in the server.

To look like real life, our post will use JPA and HSQLDB as database, and we will use JPQL to query the data.

In the end of this post you will find the link to download the source code.

We will use:

  • JSF 2.0 – JBoss 7 Implementation
  • JBoss 7.1 – the code of this post should be applied to all servers
  • Eclipse Indigo
  • JPA 2.0 – JBoss 7 Implementation
  • HSQLDB (2.2.8) – The HSQL it is a memory database, it will be easier to run it.
  • Primefaces 3.2

This post is not about good development practices nor about adding classes layers of project modeling. I just intend to show how to do a pagination without a session managed bean.

Full WebApplication JSF EJB JPA JAAS

Hello, how are you?

This post will be the biggest so far in my blog! We will see a full web application. It will be done will the newest technologies (until today), but I will give some hints to show how to adapt this post to older technologies.

In the end of this post you will find the source code to download. You can use it as you wish. Just go to the last page and do the download. o/

If you downloaded the code and did not understand something, in this post I will explain every detail found in the code. Just read the subject inside this post that you want.

I will list bellow the technologies that I will use in this post:

  • JSF 2.0 Mojarra – With ManagedBeans as RequestScope and SessionScope.
  • Message Internationalization – File that will have all the messages of our system; it will be easier to translate you pages.
  • Default CSS file that will be imported as a library.
  • EJB 3 – Our DAOs and Façades will be @Stateless.
  • Generic DAO – A generic DAO that will have the CRUD actions to make our life easier.
  • JPA 2 – To map our classes in the DB
  • JAAS – To control the login and the user access to the pages.
  • MVC – I will use this pattern with small modifications.
  • Postgres as database, but I will show how to set up your app to MySQL also.

I will not use TDD – JUnit to test our View/Model/Classes, but in the following link you can see a technique to use the JUnit to test your ManagedBeans: JUnit with HSQLDB, JPA and Hibernate.

Tools that we will use:

This post will have several pages; this first page is just to show the technical details of the post today.

I will not code to interface my model/DAO, just to save space. Remember that you should always code to interfaces (Design Pattern – Strategy).

Before you go to the next pages be sure that you installed the JBoss Tools and the JBoss 7 in this exactly order.

JSF RESTFull Get Request Parameters

Hello, how are you?

How can we pass parameters through a URL using JSF 2.0? I believe this will be smallest post here.

At the end of this post you will find the link to download the created source code.

The other posts about JSF/Web Applications you can find in here: JSF Simple Ajax SamplesJSF Persisting Objects and Messages after a Redirect ,User Login Validation with JAAS and JSFJSF: Converter and Bean AutoCompleteJSF – Hello World, Auto CompleteHandling Exceptions on a WebAppUser Authentication (Filter/Servlet)Creating a WebServer.

Take a look bellow to see that is very easy to receive a parameter through a URL:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
	<f:metadata>
		<f:viewParam name="email" value="#{user.email}" />
		<f:viewParam name="name" value="#{user.name}" />
	</f:metadata>
</h:head>
<h:body>
	<h:form>
		Your email is: #{user.email} <br/>
		Your name is: #{user.name} <br/>
		Your name and email from MB: #{user.nameAndEmail} <br/>
	</h:form>
</h:body>
</html>
package demo;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

/**
 * Created by JBoss Tools
 */
@ManagedBean(name = "user")
@RequestScoped
public class User {

	private String email;
	private String name;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getName() {
		return name;
	}

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

	public String getNameAndEmail(){
		return email + " " + name;
	}
}

The used URL to access that page is: http://localhost:8080/RequestParameter/values.xhtml?email=Read+Romans&name=Chapter10+Ver+09.

As you can see the page expects two parameters and in our ManagedBean exists a method that uses both parameters; in this method you could search for your entities in the database or any other action that you need.

How can we create a link to be navigated by the user? Piece of cake, take a look at the page/code bellow:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>

</h:head>
<h:body>
	<h:form>
		01) A pre-formed link: <br/>
		<h:link outcome="values?email=Read Romans&amp;name=Chapter10 Ver 09" value="Let us go!" />
		<br/>
		<br/>
		02)Link with the f:param component<br/>
		<h:link outcome="values" value="Write all params and let us go!" >
			<f:param name="email" value="Read Romans" />
			<f:param name="name" value="Chapter10 Ver 09" />
		</h:link>
		<br/>
		<br/>
		03) <h:commandLink value="Redirect Me!" action="values?faces-redirect=true&amp;email=Read Romans&amp;name=Chapter10 Ver 09" />
	</h:form>
</h:body>
</html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
	<f:metadata>
		<f:viewParam name="email" value="#{user.email}" />
		<f:viewParam name="name" value="#{user.name}" />
	</f:metadata>
</h:head>
<h:body>
	<h:form>
		Your email is: #{user.email} <br/>
		Your name is: #{user.name} <br/>
		Your name and email from MB: #{user.nameAndEmail} <br/>

		04) <h:link outcome="values" value="Get everybody and leave this place" includeViewParams="true" />
	</h:form>
</h:body>
</html>


I will talk about each approach used in the codes to generate the links (according to each number used like 01, 02…):

  • 01)  A pre-formed link that has all the parameters written in it.
  • 02)  We are using the “f:param” component that gives us a cleaner code.
  • 03)  A link that will use the redirect to navigate through the commandLink component. BE CAREFULL: until today, the JSF will not send paramters in a redirect if you use the “f:param” component. That is why I wrote all URL in the link with the redirect. “<h:commandLink action=”values?faces-redirect=true”.
  • 04)  Using this approach with the option (includeViewParams=”true”) you will automatically includ all the “f:viewParam” that are present in the view. You will not need to write them in the “h:link” component. JSF will gather all the parameters for you.

You can also add parameters when you use the navigation through the “faces-config.xml”:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd">
	<navigation-rule>
		<navigation-case>
			<from-outcome>redirectMe</from-outcome>
			<to-view-id>/myPage.xhtml</to-view-id>
			<redirect include-view-params="true">
				<view-param>
					<name>calculatedValue</name>
					<value>#{myBean.value}</value>
				</view-param>
			</redirect>
		</navigation-case>
	</navigation-rule>
</faces-config>

The code from this post will work with the “h:link” or the “h:commandLink” and both can be used with the redirect option.

I also want to remind you that your URL can be wrote in a ManagedBean and the value used like #{youMB.createTheURL} in the “link/commandLink” components.

Click here to download the source code.

I hope this post helps you.

If you have any question/doubt/suggestion just post it.

See you soon. o_

JSF Simple Ajax Samples

Hello, how are you?

Today we will see some Simple Samples of Ajax with JSF.

If you want to see other posts about JSF/Web Applications click on the next links: JSF Persisting Objects and Messages after a Redirect ,User Login Validation with JAAS and JSFJSF: Converter and Bean AutoComplete, JSF – Hello World, Auto Complete, Handling Exceptions on a WebApp, User Authentication (Filter/Servlet), Creating a WebServer.

In the end of this post you will find the link to download the source code of the samples. In this post (User Login Validation with JAAS and JSF) I show how to install the JBoss 6 in case you want to run the project from today. You will need to install the JBoss tools plugin in your Eclipse.

Take a look at the page bellow and its code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		Your Name: <h:inputText id="inputname" label="${msgs.prompt}" value="#{user.name}"/>
		<br />
		<h:commandButton action="#{user.sayHello}" value="Display my name here, now!"/>
		<br />
	</h:form>
</h:body>
</html>

How could we display the typed name in the same screen using Ajax? Piece of cake, just add the “f:ajax” component. Check the code update and the result:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		Your Name: <h:inputText id="inputname" label="${msgs.prompt}" value="#{user.name}"/>
		<br />
		<h:commandButton action="#{user.sayHello}" value="Display my name here, now!">
			<f:ajax render="myName" execute="inputname" />
		</h:commandButton>
		<br />
		<br />
		<h:outputText id="myName" value="#{user.name}" />
	</h:form>
</h:body>
</html>

It is very easy right? We just need to pass the value that will be carried to the ManagedBean by the “execute” parameter; with the “render” parameter we will tell to the JSF which component will be “refreshed”.

Notice also that the typed name appears in the Console.

With this code we can “refresh” all kind of components. Let us see another sample?

Let us display an error message if the user types a name with less than 4 characters.

Check our new message and the new code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		<h:messages id="myMessage" globalOnly="true" showDetail="true"/>
		Your Name: <h:inputText id="inputname" label="${msgs.prompt}" value="#{user.name}"/>
		<br />
		<h:commandButton action="#{user.sayHello}" value="Display my name here, now!">
			<f:ajax render="myName myMessage" execute="inputname" />
		</h:commandButton>
		<br />
		<br />
		<h:outputText id="myName" value="#{user.name}" />
	</h:form>
</h:body>
</html>
package demo;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

/**
 * Created by JBoss Tools
 */
@ManagedBean(name = "user")
@RequestScoped
public class User {

	private String name;

	public String sayHello() {
		if (isNameIncorrect()) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Too small", "Can you write it a little bigger?"));
		}

		System.out.println(name);
		return null;
	}

	private boolean isNameIncorrect() {
		return "".equals(name.trim()) || name.length() < 3;
	}

	public String getName() {
		return name;
	}

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

Notice that we have the component “h:messages” and its ID is used in the “f:ajax” component. This code also works when you use the “h:message for=“YYY”” component.

What if we work now with comboboxes? Let us display a combobox that will contain 4 items when we have a name with less than 6 characters, and a list with more than 4 items if the typed name has more than 6 characters.

package demo;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UISelectItems;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

/**
 * Created by JBoss Tools
 */
@ManagedBean(name = "user")
@RequestScoped
public class User {

	private String name;

	private List<String> cars;

	private String selectedCar;
	private HtmlSelectOneMenu htmlSelectCars;

	private static final String SELECT_A_CAR = "Select One Car";

	public User() {
		cars = new ArrayList<String>();
	}

	public String sayHello() {
		if (isNameInCorrect()) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Too small", "Can you write it a little bigger?"));
		}

		System.out.println(name);
		return null;
	}

	private boolean isNameInCorrect() {
		return name == null || "".equals(name.trim()) || name.length() < 3;
	}

	public String getName() {
		return name;
	}

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

	public void editMyCarsList(AjaxBehaviorEvent event) {
		if (htmlSelectCars == null) {
			htmlSelectCars = new HtmlSelectOneMenu();
		}

		htmlSelectCars.getChildren().clear();

		UISelectItems items = new UISelectItems();
		items.setValue(getCars());
		htmlSelectCars.getChildren().add(items);
	}

	public List<String> getCars() {
		cars.clear();

		cars.add(SELECT_A_CAR);

		if (!isNameInCorrect() && name.length() >= 6) {
			cars.add("Ferrari");
			cars.add("Porch");
			cars.add("Beetle");
			cars.add("Opala");
			cars.add("Passat");
			cars.add("Vectra");
			cars.add("Chevet");
			cars.add("Corvet");
		} else {
			cars.add("Ferrari");
			cars.add("Porch");
			cars.add("Beetle");
			cars.add("Opala");
		}

		return cars;
	}

	public void setCars(List<String> cars) {
		this.cars = cars;
	}

	public String getSelectedCar() {
		return selectedCar;
	}

	public void setSelectedCar(String selectedCar) {
		this.selectedCar = selectedCar;
	}

	public HtmlSelectOneMenu getHtmlSelectCars() {
		editMyCarsList(null);

		return htmlSelectCars;
	}

	public void setHtmlSelectCars(HtmlSelectOneMenu htmlSelectCars) {
		this.htmlSelectCars = htmlSelectCars;
	}
}

Take a look now at our page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		<h:messages id="myMessage" globalOnly="true" showDetail="true" />
		Your Name: <h:inputText id="inputname" label="${msgs.prompt}" value="#{user.name}" />
		<br />
		<h:commandButton action="#{user.sayHello}" value="Display my name here, now!">
			<f:ajax render="myName myCars myMessage" execute="inputname" listener="#{user.editMyCarsList}" />
		</h:commandButton>
		<br />
		<br />
		<h:outputText id="myName" value="#{user.name}" />
		<br />
		<br />
		Choose your car: <h:selectOneMenu id="myCars" binding="#{user.htmlSelectCars}" value="#{user.selectedCar}" />
		<br />
		<br />
	</h:form>
</h:body>
</html>

Notice that our combobox items size is updated according to the typed name. At the end of this post I will talk more about why I used the binding attribute to the HtmlSelectOneMenu instead returning the List<String>.

As our last sample, let us create a combobox that will appear and disappear according to the selected value in the Car combobox.

Take a look at our ManagedBean:

package demo;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UISelectItems;
import javax.faces.component.html.HtmlSelectOneMenu;
import javax.faces.context.FacesContext;
import javax.faces.event.AjaxBehaviorEvent;

/**
 * Created by JBoss Tools
 */
@ManagedBean(name = "user")
@RequestScoped
public class User {

	private String name;

	private List<String> cars;
	private List<String> colors;

	private String selectedCar;
	private String selectedColor;
	private HtmlSelectOneMenu htmlSelectCars;

	private static final String SELECT_A_CAR = "Select One Car";

	public User() {
		cars = new ArrayList<String>();
		colors = new ArrayList<String>();

		colors.add("Red");
		colors.add("Blue");
		colors.add("Orange");
		colors.add("Pink --> O.o");
	}

	public String sayHello() {
		if (isNameInCorrect()) {
			FacesContext context = FacesContext.getCurrentInstance();
			context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Too small", "Can you write it a little bigger?"));
		}

		System.out.println(name);
		return null;
	}

	private boolean isNameInCorrect() {
		return name == null || "".equals(name.trim()) || name.length() < 3;
	}

	public String getName() {
		return name;
	}

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

	public void editMyCarsList(AjaxBehaviorEvent event) {
		if (htmlSelectCars == null) {
			htmlSelectCars = new HtmlSelectOneMenu();
		}

		htmlSelectCars.getChildren().clear();

		UISelectItems items = new UISelectItems();
		items.setValue(getCars());
		htmlSelectCars.getChildren().add(items);
	}

	public List<String> getCars() {
		cars.clear();

		cars.add(SELECT_A_CAR);

		if (!isNameInCorrect() && name.length() >= 6) {
			cars.add("Ferrari");
			cars.add("Porch");
			cars.add("Beetle");
			cars.add("Opala");
			cars.add("Passat");
			cars.add("Vectra");
			cars.add("Chevet");
			cars.add("Corvet");
		} else {
			cars.add("Ferrari");
			cars.add("Porch");
			cars.add("Beetle");
			cars.add("Opala");
		}

		return cars;
	}

	public void setCars(List<String> cars) {
		this.cars = cars;
	}

	public String getSelectedCar() {
		return selectedCar;
	}

	public void setSelectedCar(String selectedCar) {
		this.selectedCar = selectedCar;
	}

	public List<String> getColors() {
		return colors;
	}

	public void setColors(List<String> colors) {
		this.colors = colors;
	}

	public boolean isColorsAlloweToDisplay() {
		if (isNameInCorrect()) {
			return false;
		}

		if (selectedCar == null || selectedCar.trim().equals("") || selectedCar.equals(SELECT_A_CAR)) {
			return false;
		}

		return true;
	}

	public String getSelectedColor() {
		return selectedColor;
	}

	public void setSelectedColor(String selectedColor) {
		this.selectedColor = selectedColor;
	}

	public HtmlSelectOneMenu getHtmlSelectCars() {
		editMyCarsList(null);

		return htmlSelectCars;
	}

	public void setHtmlSelectCars(HtmlSelectOneMenu htmlSelectCars) {
		this.htmlSelectCars = htmlSelectCars;
	}
}

Our ManagedBean were lightly updated, we just added a List with a method that return a list of colors that will populate our combobox; we added also a method that will return a Boolean – true if the combobox is allowed to be displayed.

Check our new page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html"
	xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
	<h:form>
		<h:messages id="myMessage" globalOnly="true" showDetail="true" />
		Your Name: <h:inputText id="inputname" label="${msgs.prompt}" value="#{user.name}" />
		<br />
		<h:commandButton action="#{user.sayHello}" value="Display my name here, now!">
			<f:ajax render="myName myCars myMessage myColors" execute="inputname" listener="#{user.editMyCarsList}" />
		</h:commandButton>
		<br />
		<br />
		<h:outputText id="myName" value="#{user.name}" />
		<br />
		<br />
		Choose your car:
		<h:selectOneMenu id="myCars" binding="#{user.htmlSelectCars}" value="#{user.selectedCar}">
			<f:ajax render="myColors" execute="inputname myCars"/>
		</h:selectOneMenu>
		<br />
		<br />
		<h:panelGroup id="myColors">
			<h:selectOneMenu value="#{user.selectedColor}" rendered="#{user.colorsAlloweToDisplay}">
				<f:selectItems value="#{user.colors}" />
			</h:selectOneMenu>
		</h:panelGroup>
	</h:form>
	</h:body>
</html>

I will talk about the code used in the post:

  • HtmlSelectOneMenu – I used the component instead a List because the JSF is not so good in render the components in the user screen (DOM Tree). If your combobox has 4 lines and by using ajax you add more lines to the List, the JSF/Ajax will not recognize the new added lines; you will be able to use only the older values. You can try to use the code with a List<String> instead using the HtmlSelectOneMenu and see the result; I spend like 3~4 hours to understand this by a lot of searches on the internet.
  • HtmlSelectOneMenu inside the “h:panelGroup” component – I did this because every time you want to render a non rendered component you need to update its container. If our selectOne were inside the same form of the car selectOne you would need to render all form.

Click here to download the code from this post.

I hope this post might help you.

If you have any question/doubt/suggestion just post it.

See you later. o_