Velocity

Velocityについて

コミュニティ

ドキュメント

ツール

比較

日本語訳について

Generation? − 生成?

JSP touts as an advantage that it takes an existing .jsp page and compiles that into a Servlet for speed and efficiency reasons. What this means is that it first parses the .jsp page into the resulting mess below and then it uses javac or your favorite Java compiler (ie: Jikes) to compile that Servlet into a .class file which is then loaded by the Servlet Engine. Wow, just explaining all of that gave me a headache, how about you?

JSPでの利点として、既存の .jsp ページを速度と効率上の理由からコンパイルして Servletにできることが喧伝されています。 それがどういうことかと言えば、まず .jspページを解析し、 このページの最後に出てくるようなごちゃごちゃしたコードにした上で、 その Servletが、javacやあなたの好きな Java コンパイラ (例えば Jikes) で .class ファイルにコンパイルされて、Servlet エンジンにロードされます。 ふぅ・・・これを説明するだけで頭痛がしてきましたが、いかがですか?

The point being that using JSP is now a multi step process. The authors of JSP have done a good job of hiding this process stuff behind the scenes in such a way that you do not even notice it. One simply edits the .jsp page in their favorite editor and then uses their browser to call the page via a URI which starts the process of transforming it into a .class file.

要するに、今のところ、JSP を使うには多段階のプロセスが必要だということです。 JSP の作者は、ユーザがプロセスの存在さえ気がつかないぐらい、 こうしたプロセスのあれこれを裏に隠すのに成功しています。 ユーザは好きなエディタで .jsp ページを編集し、ブラウザを使って、 ページを .class ファイルに変換するプロセスを開始する URI で、 ページを呼び出すだけです。

There are some fundamental issues that are being dealt with in the generated .jsp template. The first one is the class name. What happens is that the engine needs to produce a name that is unique in order to work around class loader issues that might crop up. Therefore, each and every time one modifies a .jsp page, a new file is created on disk in the temporary directory. Unfortunately, this directory ends up growing in size until someone decides to clean it up. The engine could probably do this for you, except then it might make the mistake of actually removing the wrong file.

生成された .jsp テンプレートにはいくつかの根本的な問題があります。 まずは、そのクラス名についてです。つまり、クラスローダーの問題に対処するために、 エンジンは(コンパイルを行うたびに)一意な名前を生成する必要があるということです。 したがって、誰かが .jsp ページを修正するたびに、 新しいファイルがディスクのテンポラリディレクトリに作成されます。 残念なことに、誰かがそれを掃除しない限り、 このディレクトリのサイズは増えつづけることになります。 ひょっとしたらエンジンが代わりに削除してくれるかもしれませんが、そうすると、 削除してはならないファイルを間違って削除してしまうかもしれません。

The point being that this whole process of edit->transform->compile->load->run is really unnecessary and in particular, a bad design. On the other hand, Velocity will simply load templates, parse them a single time and then store an Abstract Syntax Tree (AST) representation of the template in memory which can then be re-used over and over again. The process is simply edit->parse->run. The benefit is that working with Velocity templates ends up being much faster and it also removes the requirement of having a javac compiler and temporary scratch directory hanging around. In Velocity, when the template changes, the existing cached template is simply replaced with a freshly parsed version.

要するに、編集→変換→コンパイル→ロード→実行という全体のプロセスは、 実際不要ですし、何より設計として良くないということです。 それに対して、Velocity は単にテンプレートをロードし、一度だけ解析し、 何度でも再利用できるように、テンプレートを抽象構文木(AST)表現でメモリに格納します。 プロセスは、単に編集→解析→実行と、単純です。 利点としては、Velocity テンプレートを使うと非常に処理が速くなり、 javacコンパイラとテンポラリディレクトリの間を行ったり来たりする必要がなくなることです。 Velocityでは、テンプレートを変更する際も、既存の蓄積されたテンプレートが、 新たに解析されたバージョンと置き換わるだけです。

Another advantage to Velocity's approach for templates is that the actual template data can be stored anywhere, including a database or remote URI. By using configurable template loaders, it is possible to create template loaders that can do anything that you want.

テンプレートを使う Velocity のアプローチのもう一つの利点は 実際のテンプレートデータをどこにでも格納できることです。 格納場所としてはデータベースやリモートURIも含まれます。 設定可能なテンプレートローダを使用することにより、 何でもできるテンプレートローダを作成することが可能です。

Even without Turbine, Velocity offers several ways to deal with errors. Where frameworks such as Struts and Turbine come handy is by providing ways of properly dealing with errors. However, due to the fact that Struts is based on top of JSP, it also inherits the same amount of problems associated with JSP. The next chapter will go into more details on that.

Turbine がなくても、Velocity でエラー処理を行う方法がいくつかあります。 StrutsとTurbineのようなフレームワークの便利なところは、 エラー処理を適切に行えることです。 しかし、Struts は JSP を基礎に置いているので、 JSP に関する問題をそのまま引き継いでいます。 次の章では、これに関してさらに詳細に説明します。

One final problem in the design shown below is that the JSP page only catches Exception's. What if the code within a JSP page throws another exception like OutOfMemoryError? The problem here is that OOME is based on Throwable, not Exception. Therefore, it is much more difficult to catch this exception with just a JSP page. Future versions of the JSP spec and implementations will improve on this.

後述される設計の問題の中でも決定的なのは、 JSP ページは Exception しか捕えられないことです。 もし、JSP ページが OutOfMemoryError といった他の例外を投げたらどうなるでしょうか? ここでの問題は、OutOfMemoryError が (Exception ではなく) Throwable ベースにしているということです。 したがって、JSP ページだけでこの例外を捕えるのは、ずっと難しいです。 将来のバージョンの JSP 仕様・実装では、これに関しては改善される予定です。

This nice example provided by our friends at NASA, which sends multi-billion dollar equipment through the heavens, is a perfect example of why JSP needs better error handling.

この格好のは、 NASA (数10億ドルの機器を天国に送り出しています) の友人が提供してくれたもので、 JSP でのエラー処理の改善がなぜ必要か、ということに関する完璧な例です。

Buffering is also another big issue as constantly writing to the output stream is not very efficient.

バッファリングはもう一つの大きな問題です。なぜなら、 絶えず出力ストリームに書くのはあまり効率的でないからです。

<%@ page buffer="12kb" %>
<%@ page autoFlush="true" %>

These are examples of telling JSP to buffer the output 12kb and to autoFlush the page. Struts+JSP has implemented the MVC model by providing the View portion through JSP templates. What part of the MVC model do you think that those tags belong? You guessed it, not the part where they are being used.

この例では、出力を 12kb だけバッファリングし、ページを autoFlush するように JSP に命令します。Struts と JSP の組み合わせでは、JSP テンプレートで View の部分を提供することによって、MVC (Model-View-Controller) モデルを実装しています。 上記のタグは MVC モデルのどこに属していると思いますか? ご想像の通り、ここ [View] はこれらのタグを使うべきところではありません。

Velocity's approach to dealing with this issue is by allowing the developer to pass a stream into the rendering engine. If there is an exception thrown, during rendering, then the exception can be caught and dealt with. Buffering is also handled by passing properly buffered stream to the parser. Again, if there is an error, then another stream can be easily substituted for the output.

この問題に対する Velocity でのアプローチは、 開発者がテンプレート処理エンジンにストリームを渡すというものです。 ドキュメント生成の途中で例外が投げられたら、例外を捕えて処理できます。また、 バッファリングについてはパーサに対し適切にバッファされたストリームを渡すことで 対応できます。この場合も、エラーが発生したら、 その出力の代わりに別のストリームを使うこともできます。

Here is an example of the intermediate code generated by Tomcat 3.3m2:

Tomcat 3.3 m2 で生成された中間コードの例を以下に示します。

package jsp;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;

public class helloworld_1 extends org.apache.jasper.runtime.HttpJspBase {

    static {
    }
    public helloworld_1( ) {
    }

    private static boolean _jspx_inited = false;

    public final void _jspx_init() throws org.apache.jasper.JasperException {
    }

    public void _jspService(HttpServletRequest request, HttpServletResponse  response)
        throws java.io.IOException, ServletException {

        JspFactory _jspxFactory = null;
        PageContext pageContext = null;
        HttpSession session = null;
        ServletContext application = null;
        ServletConfig config = null;
        JspWriter out = null;
        Object page = this;
        String  _value = null;
        try {

            if (_jspx_inited == false) {
                _jspx_init();
                _jspx_inited = true;
            }
            _jspxFactory = JspFactory.getDefaultFactory();
            response.setContentType("text/html;charset=8859_1");
            pageContext = _jspxFactory.getPageContext(this, request, response,
			"", true, 8192, true);

            application = pageContext.getServletContext();
            config = pageContext.getServletConfig();
            session = pageContext.getSession();
            out = pageContext.getOut();

            out.write("<html>\r\n<head><title>Hello</title></head>\r\n<body>\r\n<h1>\r\n");
            if (request.getParameter("name") == null) 
              out.write("\r\n          Hello World\r\n");
            else 
              out.write("\r\n          Hello, ");
            request.getParameter("name"); 
              out.write("\r\n</h1>\r\n</body></html>\r\n");

        } catch (Exception ex) {
            if (out != null && out.getBufferSize() != 0)
                out.clearBuffer();
            if (pageContext != null) pageContext.handlePageException(ex);
        } finally {
            if (out instanceof org.apache.jasper.runtime.JspWriterImpl) { 
                ((org.apache.jasper.runtime.JspWriterImpl)out).flushBuffer();
            }
            if (_jspxFactory != null) _jspxFactory.releasePageContext(pageContext);
        }
    }
}

You make the decision.

[どちらを選ぶかは] あなたが判断してください。

[ Saying Hello <- Previous | Next -> Error Handling ]

[ Saying Hello <- 前 | 次 -> エラーの扱い ]



このドキュメントは、 熊坂祐二 、 高橋達男 、 羽生田恒永 が訳しました。
コメントがある場合は、 report@jajakarta.org までお願いします。
オリジナル英文 Copyright © 1999-2005, The Apache Software Foundation