Weld Tutorial – Part 1


Following my recently published article about integrating Weld with Tomcat6 here’s Part 1 of my Weld tutorial.

In this first part I want to create a really really really simple example application – the so called “Hello Weld” example. For the Non-German readers: “Hello Weld” is a litte pun. “World” is “Welt” in German which is pretty close to Weld. ;) Enough jokes for now, let’s go to work.First we create the simplest bean known to mankind:

package de.publicstaticfinal.web.jsf;
import java.io.Serializable;

import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named("helloWeld")
@SessionScoped
public class HelloWeld implements Serializable {
private String message = "Hello Weld";

 public String getMessage() {
   return message;
 }
}
  • 9: @Named(“helloWeld”) tells Weld that this bean is accessible under the name “helloWeld”. You don’t have to specify a value the default would be the camel-cased de-capitalized name of the Class.
  • 10: @SessionScoped tells Weld that this bean resides in session scope. Be aware: When you use JSF 2.0 the are two @SessionScoped annotation. If using Wled always use the annotation in the javax.enterprise package.

Now consider the following Facelets page which just outputs the “message” field from the bean referenced by the name “helloWeld”:

<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">
<head>
<title>Test</title>
</head>
<body>
<h:outputText value="#{helloWeld.message}" />
</body>
</html>

And with little surprise you get this output:

helloWeld01

What happened? When helloWeld.jsf is requested Weld does a lookup of “#{helloWeld}” and since we declared the bean it can be found by Weld. Weld creates an instance of the bean and puts it into session scope. If you debug the application and create a breakpoint you can see that it is indeed always the same instance within a session.

There’s nothing that special about it since the scoped annotations are also included in JSF 2.0. Part 2 of my tutorial will show you the real fun with dependency injection.

, , , ,

  1. No comments yet.
(will not be published)
Please leave these two fields as-is:

Protected by Invisible Defender. Showed 403 to 163 bad guys.