Shortcuts for generating text using Java programs

Source: Internet
Author: User
The shortcut for generating text using Java programs-Linux general technology-Linux programming and kernel information. The following is a detailed description. 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 ("\ n"); message. append ("\ n"); message. append ("Your account balance is"); message. append (customer. getAccountTotal (); message. append ("\ n"); message. append ("\ n"); message. append (" Ceremony! "); Message. append ("\ n"); 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 = "! \ N XXX ornament Company "; if the above Code 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. In the template introduction, loading message text from a text file solves some problems ?? However, dynamic content cannot be provided, 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 In ". # The foreach command iterates the list, puts each element in the list into the item parameter, and then parses the content in the # foreach block. For each element in the list, the content of the # foreach block is parsed again. In terms of effect, it is equivalent to telling the template engine: "Put every element in the list into the item variable in sequence, put one element each time, and output the content of # foreach block once ". Before looking at the next example, let's review the content we discussed above. The biggest benefit of using the template engine is that it separates code (or program logic) and performance (output ). Because of this separation, you can modify the program logic without worrying about the mail message itself. Similarly, you (or a staff member of the PR department) can recompile the program without re-compiling the program, re-compile the email message. In fact, we have separated the system's Data Model (that is, the class that provides Data), the Controller (that is, the Mail Program), and the View (View, that is, the template ). This layer-3 system is called the Model-View-Controller Model (MVC ). If the MVC model is followed, the code is divided into three completely different layers, which simplifies the work of all relevant personnel in the software development process (MVC has been around for a while, for more information, see "reference resources" at the end of this article ). The data mode used in combination with the template engine can be any Java object, preferably an object using the Java Collection Framework. As long as the controller understands the template environment (such as VelocityContext), this environment is generally easy to use. Some Relational Database "Object-relationship" Ing tools can work well with the template engine to simplify JDBC operations. For EJB, the situation is similar. The template engine is more closely related to the visual part in MVC. The template language is rich and powerful enough to process all the necessary view functions. It is often very simple and can be used by people who are not familiar with programming. The template language not only frees the designer from an overly complex programming environment, but also protects the system and avoids code that brings danger intentionally or unintentionally. For example, template writers cannot write code that leads to infinite loops or occupy a large amount of memory. Do not underestimate the value of these security mechanisms; most template writers do not know programming. In the long run, avoiding them from accessing complex programming environments is equivalent to saving your time. Many template engine users believe that in the template engine solution, the Controller and view are clearly separated, coupled with the inherent security mechanism of the template engine, make the template engine an alternative to other content publishing systems (such as JSP. Therefore, it is not surprising that the most common use of the Java template engine is to replace JSP. HTML processing because people always pay attention to the role of the template engine to replace JSP, sometimes they forget that the template has a wider range of uses. So far, the most common purpose of the template engine is to process HTML Web content. However, I also used the template engine to generate SQL, email, XML, and even Java source code. Here I can only cover some of the template's applications, but you can find more examples from the reference resources at the end of this article. In the following HTML example, I will use the data mode in the previous email Example. This HTML page is a hypothetical Enterprise Intranet page that displays detailed information about the customer account. In this example, the Controller class is a Java Servlet, And the view section contains an HTML template. The following code shows the most important code in the Servlet class. To make this example more representative, I wrote this Servlet manually from the beginning. However, in general, the template provides some Servlet tools to help users reduce the burden of coding. // Load the Template template = Velocity. getTemplate ("html. vm "); // create the environment VelocityContext context = new VelocityContext (); context. put ("customers", Customer. getCustomers (); // resolution template, output response ServletOutputStream output = response. getOutputStream (); Writer writer = new OutputStreamWriter (output); template. merge (context, writer); writer. flush (); there is nothing surprising about this example. Like in the previous example, I just add the necessary objects to VelocityContext and output the parsing template results. However, note that in the previous example, only one Customer is added to VelocityContext, but a group of Customer objects is added to VelocityContext. I can use the # foreach command to iteratively access all Customer objects. The following is an HTML template:Customer Report # foreach ($ customer in $ MERs mers) $ customer. CustName # Foreach ($ transaction in $ customer. Transactions)
$ Transaction. Date
Related Article

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.