Shortcuts for generating text using Java programs

Source: Internet
Author: User

 


Most programs need to output some text, such as mail messages, HTML files, or console output. However, computers can only process binary data in essence. programmers must make the software generate understandable texts. In this article, I will introduce why the template engine can save time when generating and outputting text. You will understand the advantages of templates and how to create efficient templates for different situations. Say goodbye to System. println!

Although programmers can easily compile code that outputs text information (because this is the first thing they have learned from the Hello World example, programmers are not the best candidates for writing or organizing text information (such as emails. Therefore, we often ask the marketing or PR department to do those things. Unfortunately, even for the most common emails, writers often rely on program output to complete the task. This cooperative approach can easily cause misunderstandings and mistakes for email writers and programmers.

For example, a Java program collects customer information from a data source and sends the account balance information to each customer in the company by email. The following is the Java program that completes this task (the complete sample code can be downloaded from the end of this article ):

For (int I = 0; I {Customer customer = (Customer) MERs. get (I); StringBuffer message = new StringBuffer (); message. append ("Dear Sir/Madam:"); message. append (customer. getCustName (); message. append (""); message. append (""); message. append ("Your account balance is"); message. append (customer. getAccountTotal (); message. append (""); message. append (""); message. append ("ceremony! "); Message. append (""); message. append ("XXX Decoration company"); // send email to mm. sendMail (customer. getFirstName (), customer. getEmail (), "Account", message. toString ());}


The preceding example shows one of the worst ways to send messages. Because the message is embedded in the program code, without the help of a programmer, it is almost impossible for others to edit the message. At the same time, it is difficult to edit a professional programmer if he does not know the code. If you anticipate these troubles, write the code in the following form:

Static public final String STR_HELLO = "Dear Sir/Madam:"; static public final String STR_MESSAGE = "Your account balance is"; static public final String STR_BEY = "! XXX Decoration Company ";


If the code above makes message editing easier, there will be no more help. It is difficult to ask a person without programming to understand the meaning of static and final. In addition, the above Code is not flexible enough to change the message structure. For example, people may ask you to add more information from the data source to the mail message. In this case, you have to modify the code for constructing the mail, or add more static final String objects.

Template Introduction
Loading message text from a text file can solve some problems-but it cannot provide dynamic content, which is very important for the system. You need to insert dynamic content into pre-written text messages. However, if you use a text template engine, it can help you complete all the complicated work.

The template engine solves the problem of inserting dynamic content into text messages. When using the template engine, we no longer directly embed messages into the program, but create a simple text file containing text content, called "Text Template ". The template engine parses text templates and inserts dynamic content into the template output results with some simple template instructions.

The template engine I selected is the Velocity of the Jakarta Project, but you can choose any one of the other template engines. Velocity and WebMacro may be the two most versatile and popular engines currently, and both are provided free of charge according to the source code open protocol. Although Velocity is used in this example, you can easily transplant these examples to different template engines by following the target engine syntax.
Let's take a look at the example of an email program completed with Velocity. To compile and run the modified program, you must download Velocity and add it to classpath. If you want the email to run properly, you also need JavaMail.
For (int I = 0; I & lt; MERs. size (); I ++) {Customer customer Customer = (Customer) MERs. get (I); // create an environment and add all the objects VelocityContext context = new VelocityContext (); context. put ("CustName", customer. getCustName (); context. put ("total", new Double (customer. getAccountTotal (); context. put ("customer", customer); // parses the template and generates the result string StringWriter message = new StringWriter (); template. merge (context, message); // send email mm. sendMail (customer. getFirstName (), customer. getEmail (), "Account", message. toString ());}


First, you should understand the above Java source code. Here we will not generate text as in the first example. The above code references a text file called "Velocity template" and then sends the result to the recipient. The Velocity template can be any text file, but generally it contains instructions for inserting dynamic content.

The content related to VelocityContext is the most noteworthy part in the above Code. VelocityContext provides connections between Java programs and Velocity text templates, while Velocity text templates can be written by others. In the template, all objects added to VelocityContext can be accessed by the name specified by the first parameter of the put () method. For more information, see the following template file:

Dear Sir/Madam, $ CustName: Your account balance is $ total! XXX Decoration Company


When the Velocity engine reads a template file, it directly outputs all the text in the file, except for those starting with $. The $ symbol identifies a position. In the template output result, the object value should be inserted to the position indicated by the $ symbol. For example, the Java code contains a context. put ("CustName", customer. getCustName () statement. When the Velocity template engine parses and outputs the template results, the customer's name will be inserted in all the places where $ CustName appears in the template; that is, the Return Value of the toString () method of the object to be added to VelocityContext replaces the Velocity variable (the variable starting with $ in the template ).

One of the most powerful and frequently used functions of the template engine is its ability to search for object information through the built-in image (Reflection) engine. This image engine allows you to use a convenient Java "." operator to extract values of any public methods or any data members of objects that are added to the VelocityContext object. The image engine also brings about another improvement: Quick Reference to the attributes of JavaBean. When using the JavaBean attribute, we can ignore the get method and brackets (for more information, see the template engine instructions ). See the following template example. In the previous Java code example, I added the Customer object to VelocityContext, so I can rewrite the template to the following form:

Dear Sir/Madam, $ customer. CustName: Your account balance is $ customer. AccountTotal! XXX Decoration Company


In addition to replacing variables, advanced engines such as Velocity and WebMacro can do many other things. They are used to compare and iterate the built-in commands (although the comparison and iteration functions are the same between the two template engines, their syntax is very different and not fully compatible. Note This when selecting a template engine or replacing a template engine ).

For example. In February December, your boss wants to send a Christmas greeting email to all customers. You can add the message to the template and delete it later. In this case, you have to work on the New Year's Day to delete the Christmas greetings.

A better way is to instruct the template when to display the Christmas greeting message. Therefore, you must first add the current month to VelocityContext:

Int month = (new GregorianCalendar ()). get (Calendar. MONTH); // Add the value of month to 1 because it calculates context from 0. put ("month", new Integer (month + 1 ));

Now, you only need to compare in the template:

Dear Sir/Madam, $ customer. CustName: Your account balance is $ customer. AccountTotal! XXX Decoration company # if ($ month = 12) wish you and your family a Merry Christmas! # End


# The if Command has a clear role: tests a logical expression to determine whether to include the content in the instruction block in the template output result. In addition to comparison, You can execute more complex comparisons. However, these functions are closely related to specific template engines, so I will not introduce them here.

The iteration instruction is as simple as the # if instruction. The template engine supports any implementation of iterative Java Collections Framework, including Array, List, And Iterator. For JDK 1.2 or later, Java Vector and ArrayList both implement List

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.