Bootstrapping a JSF 2 project
Monday, January 12, 2009 |I needed a break this afternoon, so I thought I’d see how easy it is to bootstrap a JSF 2 project. One of the biggest complaints about JSF 1.x is all that XML, so JSF 2 is aiming to fix that. How have we done so far? Based on this quick look (which is my first from-scratch JSF 2 app), really, really well.
Here are the steps I took:
-
Create a web app project using the Maven archetype (because I’m lazy that way : ) :
mvn archetype:create -DgroupId=com.mycompany.app -DartifactId=my-webapp \ -DarchetypeArtifactId=maven-archetype-webapp
-
Add FacesServlet to web.xml:
<servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping>
-
Add the JSF 2 jars (and their repo) to pom.xml:
<repositories> <repository> <id>maven2-repository.dev.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2</url> </repository> </repositories> <dependencies> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-api</artifactId> <version>2.0.0-b08</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.sun.faces</groupId> <artifactId>jsf-impl</artifactId> <version>2.0.0-b08</version> <scope>compile</scope> </dependency> </dependencies>
-
Create a managed bean:
@ManagedBean(name="main", eager=true) public class MainBean { public MainBean() { System.err.println ("MainBean starting up!"); } public String getText() { return "Here is some text!"; } }
-
Create the view:
<!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:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets"> <head> <title>Should Not Be Displayed</title> </head> <body> <ui:composition> <ui:define name="content"> #{main.text} </ui:define> </ui:composition> </body> </html>
-
Build, deploy, browse
Your web browser should now say "Here is some text!"
Did you notice that all but two of those steps are things you would do for any Java web app? As soon as someone creates a JSF 2 Maven archetype, even that can be simplified. Also notice that there was no mention of faces-config.xml. The application doesn’t have one. Granted, this is an insanely simple application, so the need for faces-config.xml may still arise (navigation comes to mind, but I think we’re working on a simplification for that too).
The rule of thumb seems to be that JSF is not well-suited for smaller, simpler apps where things like Grails, RoR, etc. are a better choice. I think we’ll see that JSF 2 changes that.