A common job in a web programmers life is to fill a combo box with some possible values.
These values can be isolated in a factory and easily populated with VRaptor using a interceptor.
In this tutorial we will do the following steps:
Let's write a simple factory class which is responsible for creating values which are often used in the web application.
package org.vraptor.example.factory;
public class Factory {
private enum Sizes{MIN,MEDIUM,BIG,HUGE};
public Sizes[] getSizes() {
return Sizes.values();
}
}Here we used a enum and created a public getter to access the values. Normally a factory will have more methods.
The Interceptor will create the factory and outject it to the request.
package org.vraptor.example.factory;
public class FactoryInterceptor implements Interceptor {
@Out
private Factory factory;
public void intercept(LogicFlow flow) throws LogicException, ViewException {
this.factory = new Factory();
flow.execute();
}
}You could also pass a connection to a database or hibernate session to the factory constructor in order to access a database.
Our logic will implement the FactoryInterceptor. This garanties that the factory object will be created and outjected to the request.
@Component
@InterceptedBy(FactoryInterceptor.class)
public class PersonLogic {
public void add() {
System.out.println("do something");
}
}If you access person.add.logic you will be directed to person/add.ok.jsp.
The jsp file could be:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
Size:
<select name="size">
<c:forEach items="${factory.sizes}" var="size">
<option name="${size}">${size}</option>
</c:forEach>
</select>
</html>