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"
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

        <display-name>vpetstore</display-name>
        <servlet>
                <description>controller for all web request</description>
                <display-name>ControllerServlet</display-name>
                <servlet-name>ControllerServlet</servlet-name>
                <servlet-class>
                        org.vpetstore.controller.PetStoreControllerServlet
                </servlet-class>
        </servlet>
        <servlet-mapping>
                <servlet-name>ControllerServlet</servlet-name>
                <url-pattern>
                        /html/control/servlet/ControllerServlet
                </url-pattern>
        </servlet-mapping>

        <welcome-file-list>
                <welcome-file>index.htm</welcome-file>
        </welcome-file-list>
</web-app>

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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
<meta http-equiv="refresh" content=
        "0;URL=html/control/servlet/ControllerServlet?m1=system&m2=store_main">
</head>
<body>
</body>
</html>