1.0          Other languages

3.2 Controller


org.velocityweb.controller.Controller is a pure Java class. Application that using VelocityWeb should write a sub-class of this class. There is another class named as org.velocityweb.controller.impl.SimpleController in VelocityWeb that is the sub-class of org.velocityweb.controller.Controller. The new web application should write a new class,for example, PetStoreController, make it as sub-class of either SimpleController or Controller. Normally, new controller should overwrite following functions:

protected Object getDataSource()
public boolean initApplication()
public Object getSessionUser(HttpServletRequest request)
public void setSessionUser(HttpServletRequest request, Object user)
public boolean hasAccessRight(LeafDispatcher leafDispatcher, HttpServletRequest request)
public boolean needLogin(LeafDispatcher leafDispatcher, HttpServletRequest request)
public Template getTemplate(String fileName, String templateHtmlCharsetName)
public void destroyApplication()

Here is an example in VPetstore, PetStoreController use JNDI to lookup datasource, which is used when web application running normally:

    public class PetStoreController extends SimpleController {
        protected Object getDataSource() {
                //some J2EE container need jndi name begin with "java:comp", others not
                Object dataSource = getDataSource("java:comp/env/jdbc/vpetstore");
                if (dataSource == null) {
                        dataSource = getDataSource("jdbc/vpetstore");
                return dataSource;


         public Object getSessionUser(HttpServletRequest request) {
                  HttpSession session = request.getSession(false);
                  if (session == null) {
                           return null;
                  Object user = session.getAttribute(USER_KEY_IN_SESSION);
                  return user;

        public void setSessionUser(HttpServletRequest request, Object user) {
                  HttpSession session = request.getSession(true);
                  session.setAttribute(USER_KEY_IN_SESSION, user);

        public boolean hasAccessRight(LeafDispatcher leafDispatcher, HttpServletRequest request) {
                  // default all user can access all pages
                  return true;



For unit test, we need to write a new controller which overwrite function getDataSource(). For example, we can use Apache DBCP to provide datasource:

    public class TestPetStoreController extends PetStoreController {
        private Log log = LogFactory.getLog(this.getClass());

        protected Object getDataSource() {
                BasicDataSource dataSource = new BasicDataSource();
                return dataSource;


The reason why getDataSource() is protected, is to prevent some code to call it outside DAO class. We put this Datasource object into AppContext object, it will be passed from web dispatcher to DAO.