Hello Velocity [转]

xiaoxiao2021-03-06  65

Velocity is a Java-based template engine provided by Apache. Let's take a Hello level example, experience the power of Velocity. Its completion is to say "Hello" to the name set in the code.

First source code: hellovelocity.java. Import java.io.bufferedwriter; import java.io.outputstreamwriter;

Import org.apache.velocity.template; import org.apache.velocity.velocityContext; import org.apache.velocity.app.velocity;

Public class hellovelocity {public static void main (string [] args) throws exception {velocity.init (); velocityContext context = new velocityContext (); context.put ("name", "Dreamhead");

BufferedWriter Writer = New OutputStreamWriter (System.out); Template Template = Velocity.getTemplate ("Hello.vm"); Template.Merge (Context, Writer);

Writer.flush (); Writer.close ();}}

Another time template file, Hello.vmhello, $ Name

If you don't encounter any difficulties, run the result of the above code is Hello, Dreamhead

We can understand the template as a script, the script sets the plots and roles, such as the above story is to "Hello" for a role --NAME. Given that Name is a role, in order not to mix with the contents of the script, we need to add a "$" when we have written to distinguish. A good script also needs to perform, in other words, the role is coming, and these people will follow the script in accordance with the script. In the above example, finally playing the Name role is a string of "Dreamhead". It completed the task specified by the plot, the result is "Hello, Dreamhead".

In this process, we - programmers are directed, take the script, find actors, specify their roles, and see how we complete this guidance process! Before everything is ready, we must do some preparatory work: velocity.init (); then assign a role, but in order to prevent death without a loss, we need to record the result, this is a strong term for VelocityContext: velocityContext = New VelocityContext ); Start allocation roles, "Dreamhead" role is Name: context.put ("name", "Dreamhead"); personally, ready to start shooting! How to shoot? Of course, the camera is used, and finally stored on the film, prepared film: bufferedwriter = new bufferedwriter (new outputReamWriter (system.out); no script, what do I take? Script, script ... template template = velocity.getTemplate ("Hello.vm"); right, actor wants to look at the script: Template.mege (Context, Writer); All departments, Action! Writer.flush (); cut! Writer.close (); a tension and busy shooting process is completed, although we look for the hand from the process of shooting, we are still ideal, because our familiar "Hello" appeared in front of us. . The power of the template is that the same scripts can be interpreted by different actors. Maybe try to re-interpret the legend of Hello with your own name, you can experience this.

转载请注明原文地址:https://www.9cbs.com/read-88370.html

New Post(0)