Velocity単純サンプルソース解析


WEBベースのアプリケーションでは、通常、servletでVelocityを使用することが多い.servletでのVelocityの基本的な応用は非常に簡単で、2つの必要なステップだけで実現できます.
1.orgを継承する.apache.velocity.servlet.VelocityServicelet抽象クラス:
public class SampleServlet extends VelocityServlet
2.VelocityServeretクラスを実装する1つの方法handleRequest()のみ:
public Template handleRequest(HttpServletRequest req, HttpServletResponse resp, Context context)
Webプロジェクトを作成し、Web rootの下でtemplatesフォルダを作成してテンプレートファイルを保存します.
srcの下でvelocityを確立する.propertiesプロファイルの内容は次のとおりです.
file.resource.loader.Path=templates##テンプレートファイル格納ディレクトリの指定
runtime.log = log/velocity.log##ログファイルの場所の指定
Veloctyで中国語の文字化けし問題が発生した場合、velocity.propertiesファイルに次の3行を加えると解決できます.
default.contentType=text/html; charset=UTF-8
input.encoding=UTF-8
output.encoding=UTF-8
templatesフォルダにsampleという名前を設定します.vmのテンプレートです.内容は次のとおりです.
<html>
<head><title>Sample velocity page</title></head>
<body bgcolor="#ffffff">
	<center>
			<h2>Hello Velocity</h2>
			<table width="100" cellpadding="5" cellspacing="1" bordercolor="#333333">
			<tr><td bgcolor="#eeeeee" align="center">Names</td></tr>
			#foreach ($name in $theList)
			<tr><td bgcolor="#6666FF" align="center">$name</td></tr>
			#end
		</table>
	</center>
</body>
</html>

次に、VelocityServiceを継承する独自のサーブレットを開発する必要があります.
public class SampleServlet extends VelocityServlet {
	private static final long serialVersionUID = 1L;
	/** for setting up the Velocity runtime            
	 * Loads the configuration information and returns that information as a Properties, 
	 * which will be used to initialize the Velocity runtime. */
	protected Properties loadConfiguration(ServletConfig config)
			throws IOException, FileNotFoundException {
		String propsFile = config.getInitParameter(INIT_PROPS_KEY); //      
		Properties p = new Properties();
		if (propsFile != null) {
			String realPath = getServletContext().getRealPath(propsFile);
			if (realPath != null) {
				propsFile = realPath;
			}
			p.load(new FileInputStream(propsFile));
		}
		String log = p.getProperty(Velocity.RUNTIME_LOG); //  velocity       
		if (log != null) {
			log = getServletContext().getRealPath(log);
			if (log != null) { p.setProperty(Velocity.RUNTIME_LOG, log); }
		}
		String path = p.getProperty(Velocity.FILE_RESOURCE_LOADER_PATH); //       
		if (path != null) {
			path = getServletContext().getRealPath(path);
			if (path != null) { p.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, path); }
		}
		return p;
	}
	/** Implement this method to add your application data to the context, 
	 * calling the getTemplate() method to produce your return value. */
	public Template handleRequest(HttpServletRequest request, HttpServletResponse response, Context ctx) {
		String p1 = "Hoffman";
		String p2 = "Song";
		Vector personList = new Vector();
		personList.addElement(p1);
		personList.addElement(p2);
		ctx.put("theList", personList); //      list        context 
		Template outty = null;
		try {
			outty = getTemplate("sample.vm");
		} catch (ParseErrorException pee) {
			System.out.println("SampleServlet : parse error for template " + pee);
		} catch (ResourceNotFoundException rnfe) {
			System.out.println("SampleServlet : template not found " + rnfe);
		} catch (Exception e) {
			System.out.println("Error " + e);
		}
		return outty;
	}
}

そしてweb.xmlでこのサーブレットを構成するには、次のようにします.
<servlet>
	<servlet-name>SampleServlet</servlet-name>
	<servlet-class>com.mixele.velocity.SampleServlet</servlet-class>
	<init-param>
		<param-name>org.apache.velocity.properties</param-name>
		<param-value>/WEB-INF/classes/velocity.properties</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>SampleServlet</servlet-name>
	<url-pattern>/SampleServlet</url-pattern>
</servlet-mapping>

プロジェクトを配備して起動し、その後このサーブレットを実行すると、ブラウザにvmテンプレートを使用して表示されるページが表示されます.
org.apache.velocity.servlet.VelocityServiceletはHttpServiceletを継承するので、HttpSetvletのライフサイクルの管理を継承します.また、私たちが自分のvelocity servletを実現するときにorgを継承します.apache.velocity.servlet.VelocityServiceletは、その重要な方法を継承して実際のビジネスを完了することができます.
Webエンジニアリングが開始されると、SampleServiceletの親VelocityServiceletのinit()メソッドが先に実行されます.
VelocityServiceletソース:
/**    Veocity */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		initVelocity(config); //   Velocity
		/* Velocity           */
		defaultContentType = RuntimeSingleton.getString(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
		System.out.println("defaultContentType = "+defaultContentType);
	}
	/** Velocity       ,  Velocity     */
	protected void initVelocity(ServletConfig config) throws ServletException {
		try {
			Properties props = loadConfiguration(config); //  velocity.properties
			Velocity.init(props); //   Velocity
		} catch (Exception e) {
			throw new ServletException("Error initializing Velocity: " + e, e);
		}
	}

VelocityServiceletクラスのinitVelocityメソッドを実行すると、SampleServiceletクラスが呼び出されたloadConfigurationメソッドを継承して書き換えているため、SampleServiceletクラスのloadConfigurationメソッドが実行されます.このプロシージャは、独自にvelocityログファイルを設定する場所と、独自にテンプレートを設定する場所を取得します.
この過程でVelocityは自分でvelocityにアクセスします.propertiesプロファイルを使用して、情報を読み込みます.プロファイルを構成しない場合、またはkeyをfileに設定しない場合.resource.loader.pathの項目は、Template outty=getTemplate(「sample.vm」)を実行します.文またはTemplate outty=getTemplate("/templates/sample.vm");を選択すると、テンプレートが見つからないエラーが発生します.
これで、Velocityはコンテナの起動初期化を完了します.
ブラウザに入力するとhttp://localhost:8080/Mixele_Velocity/SampleServletの場合、Velocityの処理手順は次のとおりです.
SampleServicelet親VelocityServiceletを実行するdoGetから-->doRequest-->createContext-->setContentType-->chooseCharacterEncoding-->handleRequest(SampleServicelet継承)-->getTemplate(String name)-->mergetemplate(テンプレートとテンプレートに埋め込まれた値をマージ)-->requestCleanup