To demonstrate the dependency injection with JSF 2 I use a service to reverse the name. Simply add the @ManagedProperty with the name of the service and it will get injected. Of course we need the service. Here it is:
The only thing what’s missing is the web.xml and the webpage itself.
The web.xml is pretty straight forward and should not show any surprises.
12345678910111213141516171819202122
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app><display-name>Web Application</display-name><servlet><servlet-name>Faces Servlet</servlet-name><servlet-class>javax.faces.webapp.FacesServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>Faces Servlet</servlet-name><url-pattern>*.xhtml</url-pattern></servlet-mapping><context-param><param-name>javax.faces.PROJECT_STAGE</param-name><param-value>Development</param-value></context-param></web-app>
The index.xhtml has some differences from earlier versions of JSF. First, JSF now supports Ajax out of the box. To have this enabled you need to load the jsf.js javascript library. The inputText tag binds to our managed bean and includes an f:ajax tag. This tag determines which part should be rerendered (in this case the element with the id reverseName). F:ajax will execute on value holding components always with an ‘onchange’ event and on action components (like commandButtons) with an ‘onclick’ event.
The output will trigger the injected service in our managed bean and return the reversed input string.
1234567891011121314151617181920212223242526272829
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"xmlns:ui="http://java.sun.com/jsf/facelets"xmlns:f="http://java.sun.com/jsf/core"xmlns:h="http://java.sun.com/jsf/html"><h:head><title>JSF Demo</title></h:head><h:body><h:outputScriptname="jsf.js"library="javax.faces"target="body"></h:outputScript><h1>Ajax JSF 2 Demo</h1><h:form><h:inputTextid="name"value="#{helloWorldBean.name}"><f:ajaxrender="reverseName"/></h:inputText><h:commandButtonvalue="Say reverse Hi via Ajax"><f:ajaxexecute="name"render="reverseName"/></h:commandButton><h:outputTextid="reverseName"value="#{helloWorldBean.reverseName}"/></h:form></h:body></html>
And that’s it. Sure it’s a simple example, but so far I do like the minimal configuration and the ajax integration.