开发者

Configuring dynamic email content with String replace() or replaceAll()

I am using Spring MVC for my web application and I am using my applicationContext.xml file to configure my emails which I am injecting into my controllers in my spring-servlet.xml file.

Some of the emails I need to send will need to be tailored to the customer that they are being sent to. Certain information in the email (First name, Last name, phone number,etc) will need to be filled in once the email text has been injected into controller and is being sent.

An example of this is is shown in the bean below

<bean id="customeMailMessage" class="org.springframework.mail.SimpleMailMessage">
   <property name="from" value="from@no-spam.com" />
   <property name="to" value="to@no-spam.com" />
   <property name="subject" value="Testing Subject" />
   <property name="text">
      <value>
         Dear %FIRST_NAME%

                 Blah Blah Blah Blah Blah...
                 We Understand that we can reach you at the following information

                 Phone:%PHONE%
                 Address:%ADDRESS%
      </value>
   </property>
</bean>

This would be a custom email message that I would define and inject into my controller. The code in my controller would then fill in the values based on the input collected from the customer so the controller would have code similar to the following

    //SimpleMailMessage property is injected into controller
    private SimpleMailMessage simpleMailMessage;

    //Getters and Setters for simpleMailMessage;


    MimeMessage message = mailSender.createMimeMessage();

   try{
        MimeMessageHelper helper = new MimeMessageHelper(message, true);
        helper.setFrom(simpleMailMessage.getFrom());
        helper.setTo(simpleMailMessage.getTo());
        helper.setSubject(simpleMailMessage.getSubject());

                String text = simpleMailMessage.getText();
                text.replace("%FIRST_NAME%",model.getFirstName());
                text.replace("%PHONE%",model.getPhone());
                text.replace("%ADDRESS%",model.getAddress());
        helper.setText(simpleMailMessage.getText());
     }
         catch (MessagingException e) {
    throw new MailParseException(e);
     }
     mailSender.send(message);**strong text**

The problem I am having is that when I try to replace the values such as %FIRST_NAME%,%PHONE% and %ADDRESS%>, it is not replacing it. I am not sure if this is because I am using replace() wrong, or if it is because it is treating it differently because the value is injected. I have also tried to use replaceAll() and that is not working eith开发者_如何学Cer. If anybody has better ideas how to do this, please let me know.

Thank you


Don't forget that in Java Strings are immutable. i.e. you can't change them, but rather create a new one from the old one (see the doc for replaceAll() and note the return value).

So replace() won't change the string that it's called upon, but instead will return a new string with the replacement made. You can use the return value and so just chain these calls together:

String newString = oldString.replace(..).replace(...);

If you need to do a lot of this templating, you may be interested in Apache Velocity, or Freemarker. They are purpose-build templating engines that will do what you're doing with many more options (e.g. providing looping, formatting, conditionals etc.)


I'd suggest not re-inventing the wheel by building your own template system. Use Apache Velocity or another library for this - they offer more features, are more powerful, and more performant than any home-brew solution.

Spring has excellent support for Velocity and I've used Velocity templates in a number of Spring MVC apps (for both email templates and web templates) with zero issues.


I'd like to introduce Rythm template engine here. Here some points about this work:

  • Razor like synatx, very clean and friendly to Java programmer
  • Compiled to Java byte code thus is very fast. 2 to 3 times faster than velocity
  • It covers all features provided with Velocity and much more. See the full feature set demonstration hosted at google application engine
  • The API is simplest among other Java template engines (velocity, freemarker ...)

Sample 1, render with template file and pass parameter by position:

String result = Rythm.render("/path/to/my/template.txt", foo, bar, ...);

Sample 2, render with template file and pass parameter by name:

Map<String, Object> args = new HashMap<String, Object>();
args.put("foo", foo);
args.put("bar", bar);
...
String result = Rythm.render("/path/to/my/template.txt", args);

Sample 3, render with string content and pass parameter by position:

String result = Rythm.render("@args User user;User name is @user.name", user);

Sample 4, render with string content in String Interpolation Mode:

String result = Rythm.render("User name is @name", user.name);

Links:

  • Check the full featured demonstration
  • read a brief introduction to Rythm
  • download the latest package or
  • fork it
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜