基于ftl:template的Java消息读取与解析方案咨询
Part 1: Working with FreeMarker Templates in Java
FreeMarker is a reliable template engine for generating structured text output (like messages) from your data models. Here's a step-by-step breakdown of how to implement it in Java:
Add the FreeMarker Dependency
First, include the library in your project. For Maven users, add this to yourpom.xml:<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.32</version> <!-- Use the latest stable version available --> </dependency>Configure FreeMarker
Set up the engine to locate your template files (here, we're loading from the classpath):import freemarker.template.Configuration; import freemarker.template.Template; import java.io.StringWriter; import java.util.HashMap; import java.util.Map; public class MessageHandler { public static void main(String[] args) throws Exception { // Initialize configuration with a compatible version Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); cfg.setClassForTemplateLoading(MessageHandler.class, "/templates"); // Path to your .ftl files cfg.setDefaultEncoding("UTF-8"); // Load your target template Template messageTemplate = cfg.getTemplate("message-format.ftl"); } }Create Your Data Model
Populate a data structure (either aMapor custom class) with the values you want to inject into the template. A custom class works well for your use case:// Define a class to hold your message data (getters are required for FreeMarker access) class CustomerInfoRequest { private String messageDate; private String messageTime; public CustomerInfoRequest(String messageDate, String messageTime) { this.messageDate = messageDate; this.messageTime = messageTime; } public String getMessageDate() { return messageDate; } public String getMessageTime() { return messageTime; } } // Build the data model Map<String, Object> data = new HashMap<>(); data.put("customerInfoMessageRequest", new CustomerInfoRequest("29032020", "134901"));Generate the Final Message
Merge your data model with the template to produce the output:StringWriter outputWriter = new StringWriter(); messageTemplate.process(data, outputWriter); String generatedMessage = outputWriter.toString(); System.out.println("Generated message: " + generatedMessage); // Output will be "29032020134901" since your right_pad calls don't add extra zeros here
Part 2: Parsing Your Example Message
A quick note: FreeMarker is designed for generating output, not parsing input. So to reverse the process and extract the original messageDate and messageTime from your example string "29032020134901ECCINOU ", manual parsing is the simplest approach. Here's how to do it:
Simple Manual Parsing
Your template concatenates an 8-character right-padded messageDate and a 6-character right-padded messageTime. That means the first 8 characters of your input are the date, and the next 6 are the time. We just need to strip any trailing zeros added by the right_pad operation:
String inputMessage = "29032020134901ECCINOU "; // Extract messageDate (first 8 characters) String messageDate = inputMessage.substring(0, 8).replaceAll("0*$", ""); // Extract messageTime (characters 8 to 14) String messageTime = inputMessage.substring(8, 14).replaceAll("0*$", ""); System.out.println("Extracted Date: " + messageDate); // Output: 29032020 System.out.println("Extracted Time: " + messageTime); // Output: 134901
The replaceAll("0*$", "") removes any trailing zeros that right_pad added (if your original date/time was shorter than 8/6 characters).
Using Apache Commons Lang for Cleaner Trimming
For a more robust way to strip trailing zeros, you can use Apache Commons Lang's StringUtils:
import org.apache.commons.lang3.StringUtils; String messageDate = StringUtils.stripEnd(inputMessage.substring(0, 8), "0"); String messageTime = StringUtils.stripEnd(inputMessage.substring(8, 14), "0");
To use this, add the Commons Lang dependency to your pom.xml:
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.12.0</version> </dependency>
Template-Driven Parsing Alternatives
If you need template-based parsing for more complex scenarios, tools like ANTLR (for building custom parsers with grammars) or Apache Camel (which has parsing components) could work. But for your specific case, manual parsing is the most straightforward and efficient solution.
内容的提问来源于stack exchange,提问作者Abd26s

