1.0          Other languages

3.1 ControllerServlet


org.velocityweb.controller.ControllerServlet is a sub class of org.apache.velocity.servlet.VelocityServlet. ControllerServlet will call controller.initApplication() in loadConfiguration(ServletConfig config) which is initial part of VelocityServlet, and call controller.destroyApplication() in destroy() which is destroy part of servlet.

In function named as handleRequest(HttpServletRequest request, HttpServletResponse response, Context context) of class ControllerServlet, the following logic will be done:

The above web request logic is very common that we need to write it every time we start a new J2EE project. As we seldom need to change it, VelocityWeb has done this part for us.

To create a new J2EE project, we only need to write a sub-class of org.velocityweb.controller.ControllerServlet and overwrite function getController(). for example:

    public public class PetStoreControllerServlet extends ControllerServlet {
        static Controller controler = new PetStoreController();

        public Controller getController() {
                return controler;

Controller servlet should be defined in web.xml of J2EE project. And we should put a home page named as index.htm, make it jump to controller servlet home url. Here is a sample web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

                <description>controller for all web request</description>


And this is sample index.htm, it will jump to controller servlet path after it shows.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="refresh" content=