![]() | ||||||||||||||||||||
jsf with java injection
Java Injection (JSR-299) gives JSF a solid foundation for its component model, based on Java Injection's typesafe IoC capabilities and annotation-based discovery.
Java Injection works together with JSF to provide a solid component configuration for the data model of a JSF application. With Java Injection, component classes are automatically registered through classpath scanning,, reducing the amount of configuration XML to a minimum. In this example, we only need XML to define the FacesServlet, and a marker beans.xml to direct Java Injection to search for component classes. The data components automatically populate the JSF EL (expression language), so they are automatically available to the JSF application. This example creates a simple calculator which adds two numbers together.
The The data model is the heart of the JSF application. In this case, a trivial calculator. The The Calculator.java
package example;
import javax.context.RequestScoped;
import javax.annotation.Named;
@RequestScoped
@Named("calc")
public class Calculator {
private int _a;
private int _b;
public int getA() { return _a; }
public void setA(int a) { _a = a; }
public int getB() { return _b; }
public void setB(int b) { _b = b; }
public int getSum()
{
return _a + _b;
}
}
The The optional Java Injection components can also be injected with other
Java Injection, or DataSources, JPA EntityManager or EntityManagerFactory
or JMS Queues, and they can also use the JSF is designed around a UI component tree model. The JSP code builds the JSF component tree, hands it back to JSF, and then JSF will display the component tree based on its current rendering configuration.
test.jsp
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core" %>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html" %>
<f:view>
<h:messages/>
<h:form>
<h:inputText value="#{calc.a}" size="4"/>
+ <h:inputText value="#{calc.b}" size="4"/>
= <h:outputText value="#{calc.sum}" style="color:red"/>
<br>
<h:commandButton value="Add"/>
</h:form>
</f:view>
The JSF expression language expressions The housekeeping overhead is a minimum when using Java Injection. In this example we just need two pieces of XML configuration:
Java Injection will scan classes directories and jars if they contain
a WEB-INF/resin-web.xml
<web-app xmlns="http://caucho.com/ns/resin">
<servlet-mapping url-pattern="*.jsf"
servlet-class="javax.faces.webapp.FacesServlet"/>
</web-app>
META-INF/beans.xml
<Beans xmlns="urn:java:ee">
<!--
- The beans.xml marks a class root for Java Inject to search for
- simple beans. Since the example doesn't need to override any
- defaults, there's no additional configuration necessary.
-->
</Beans>
A more complete application would likely the IoC injection capabilities of Java Injection. For example:
| ||||||||||||||||||||