{"id":647,"date":"2009-12-16T09:20:03","date_gmt":"2009-12-16T14:20:03","guid":{"rendered":"http:\/\/www.andygibson.net\/blog\/?p=647"},"modified":"2010-07-29T21:41:22","modified_gmt":"2010-07-30T02:41:22","slug":"getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1","status":"publish","type":"post","link":"http:\/\/www.andygibson.net\/old-blog\/tutorial\/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1\/","title":{"rendered":"Getting Started with JSF 2.0 and CDI in JEE 6 part 1"},"content":{"rendered":"<p>Here&#8217;s a quick tutorial on how easy it is to get started with JSF 2.0 and JSR 299, Java Contexts and Dependency Inject (CDI) using the latest release of Netbeans 6.8.<br \/>\n<!--more--><br \/>\nRead <a href=\"http:\/\/www.andygibson.net\/blog\/tutorial\/getting-started-with-jsf-2-0-and-cdi-in-jee-6-part-1\/\">Part 1<\/a><br \/>\nRead <a href=\"http:\/\/www.andygibson.net\/blog\/tutorial\/getting-started-with-cdi-part-2-injection\/\">Part 2<\/a><br \/>\nRead <a href=\"http:\/\/www.andygibson.net\/blog\/tutorial\/getting-started-with-jsf-2-0-and-cdi-part-3\/\">Part 3<\/a><\/p>\n<h1>Getting Netbeans and JEE6<\/h1>\n<p>First download the latest version of Netbeans (at the time of writing 6.8 has just been released). Make sure the download version you choose includes Glassfish V3 and java web and EE. Once downloaded, install it and get it up and running and we can start writing the application.<\/p>\n<h1>Starting the Project<\/h1>\n<p>Once Netbeans is up and running, start a new web project by clicking New Project and select the Java Web category and select a Web Application project and click next.<\/p>\n<p>Give the new project a name (I called mine ee6demo) and a directory and click next. On the server settings, Glassfish v3 should already be selected so select next. In this tab, make sure Java Server Faces is selected and stick with the defaults in the lower panel that appears when you select it.<\/p>\n<p>You can now click finish and Netbeans will create the project and open it up for you in the IDE. On the left you can see the project explorer and in the main tab you can see a file called index.html. Without doing anything, open the Run menu in the main menu and select &#8220;Run Main Project&#8221;. After a moment of activity and console logging a web browser window should open up with the message &#8220;Hello From Facelets&#8221; which is exactly what we can see in the index.xhtml file. So far, we haven&#8217;t done anything and we already have a working web application shell.<\/p>\n<p>Just take a moment and look at the tabs on the left hand side, you should see Project,Files, and Services. Click on the services tab and expand the Servers node and you should see the Glassfish server we are using with a little green arrow on it indicating that the server is running. For now, we don&#8217;t need this because we aren&#8217;t actually going to deploy to the server again, no restarts and no manual deployments, so go back to the projects tab on the left.<\/p>\n<h1>Adding some code<\/h1>\n<p>In the projects tab, expand the &#8220;Source Packages&#8221; node and right click and select New->Java Class. Give the class the name <code>MessageServerBean<\/code> and a package name (I used <code>eedemo<\/code>). We annotate the class with the <code>javax.inject.Named<\/code> annotation and a single method to return a string.<\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage eedemo;\r\n\r\nimport javax.inject.Named;\r\n\r\n@Named\r\npublic class MessageServerBean {\r\n\r\n    public String getMessage() {\r\n        return &quot;Hello World!&quot;;\r\n    }\r\n}\r\n<\/pre>\n<p>This a managed bean as defined by CDI which in Glassfish v3 is implemented using Weld from JBoss. One thing we need to do now is tell the server that this project is a module containing CDI beans. We add a file called <code>beans.xml<\/code> to the project in the WEB-INF folder. Right click on the WEB-INF folder in the project manager in the ee6Demo\/Web Pages\/folder and select New->XML Document. In the file name editor, just call it <code>beans<\/code>, <b>not<\/b> <code>beans.xml<\/code> as the IDE will add the xml extension for you and if you add the xml extension, the file will be called <code>beans.xml.xml<\/code> (I&#8217;ve often tripped myself up with that one!). Open the beans.xml file in the editor, and select all the text and delete it so it is an empty file.  You could alternatively just put <code><beans><\/beans><\/code>. (<b>Note<\/b> This file can be used to specify bean related information in xml so you aren&#8217;t limited to annotations)<\/p>\n<p>The last change is to edit the <code>index.xhtml<\/code> and replace the &#8220;Hello From Facelets&#8221; with our own text.<\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n        Message is : #{messageServerBean.message}&lt;br\/&gt; \r\n        Message Server Bean is : #{messageServerBean}\r\n<\/pre>\n<p>Save it and go to your browser and refresh the page (<code><a href=\"http:\/\/localhost:8080\/ee6demo\/\">http:\/\/localhost:8080\/ee6demo\/<\/a><\/code>). <\/p>\n<p>Message is : Hello World!<br \/>\nMessage Server Bean is : eedemo.MessageServerBean@xxxxxxx <\/p>\n<p>You should now see the message from the bean displayed on the page. Now go back into your message bean and change the message to something else (I used <code>Hello From Weld!<\/code>), save the file and then refresh the browser. Your new message appears automatically since your application code has been hot deployed automatically by Netbeans . If you don&#8217;t see your changes just give it a second and refresh again.<\/p>\n<p>From the second line in our page you can see that the class name is <code>eedemo.MessageServerBean<\/code> and the bean is just a pojo. Even though this is JEE, there is no complex class hierarchy wrapped in layers of transactions, interceptors and all that &#8216;Heavy&#8217; stuff you keep hearing about. <\/p>\n<h1>What&#8217;s going on?<\/h1>\n<p>When the application is deployed, the presence of a <code>beans.xml<\/code> file signals that this module contains CDI managed beans so the classes on the path are scanned for CDI annotations. Our bean was annotated with the <code>@Named<\/code> annotation and so this class was registered with Weld (under that name) (<b>edit<\/b> in a CDI module, all beans are registered with Weld, the named annotation is just used to match beans to injection points). When our JSF page was rendered, JSF tried to resolve the value of <code>messageServerBean<\/code> in the page using the registered expression resolvers in JSF. One of these is the Weld EL Resolver which has the MessageServerBean class registered under the name <code>messageServerBean<\/code>. We could have specified a name with the annotation, but since we didn&#8217;t it was registered under the default name of the class name with a lower case first name. The Weld resolver returns an instance of this bean in response to the request from JSF. Bean naming is only needed when using EL expressions and should not be used as the default mechanism for injection. CDI provides type safe injection by class type and stereotypes or qualifiers as we&#8217;ll see later.<\/p>\n<h1>Upgrading to an EJB<\/h1>\n<p>As we are using a JEE stack, we can easily deploy our bean as an EJB with some small changes thanks to EJB 3.1. Just open up the <code>MessageServerBean<\/code> and add the <code>javax.ejb.Stateless<\/code> annotation at the class level. Again, just save the file and go to your browser and refresh (no manual deploying, just save the file), and you should see something like :<\/p>\n<p>Message is : Hello From Weld!<br \/>\nMessage Server Bean is : eedemo.__EJB31_Generated__MessageServerBean__Intf____Bean__@xxxxxxx <\/p>\n<p>Amazingly, we turned our pojo bean into a fully featured EJB with just one annotation, we saved it, and refreshed our page and our changes appeared, we don&#8217;t have to create any weird project configurations, local interfaces or arcane deployment descriptors.  <\/p>\n<h1>Different EJB types<\/h1>\n<p>You can also try using the <code>@Stateful<\/code> annotation (don&#8217;t forget to implement the <code>java.io.Serializable<\/code> interface in the bean as it needs to be able to passivate (<b>edit<\/b> This isn&#8217;t necessary for it to be an EJB, but it is necessary if you want it to be session or conversation scoped)). Alternatively, you could try the new <code>@Singleton<\/code> annotation for singleton instances. If you do, you may notice that there is a <code>javax.ejb.Singleton<\/code> and <code>javax.inject.Singleton<\/code>. Why two Singleton annotations? A single annotation in CDI lets you define a singleton instance outside of EJB in case you are using CDI in a non-EJB environment. An EJB singleton will have all the features of an EJB such as transaction management so you have the choice depending on your needs and whether the environment is EJB or not.<\/p>\n<p>In this first part, we have created a new JSF 2.0 application, made it CDI enabled and added a managed bean which we then referenced from the web page. In part 2, we&#8217;ll start looking at creating more complex beans and injecting them into and with other beans.<\/p>\n<p>Click to view <a href=\"http:\/\/www.andygibson.net\/blog\/index.php\/2009\/12\/22\/getting-started-with-cdi-part-2-injection\/\">Part 2<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Here&#8217;s a quick tutorial on how easy it is to get started with JSF 2.0 and JSR 299, Java Contexts and Dependency Inject (CDI) using the latest release of Netbeans 6.8.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0},"categories":[64],"tags":[49,20,50,32,53,54],"_links":{"self":[{"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts\/647"}],"collection":[{"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/comments?post=647"}],"version-history":[{"count":44,"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts\/647\/revisions"}],"predecessor-version":[{"id":1241,"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/posts\/647\/revisions\/1241"}],"wp:attachment":[{"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/media?parent=647"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/categories?post=647"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/www.andygibson.net\/old-blog\/wp-json\/wp\/v2\/tags?post=647"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}