Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatter not applied to values (non-mvc SpringBoot application) #324

Closed
fml2 opened this issue Mar 25, 2024 · 1 comment
Closed

Formatter not applied to values (non-mvc SpringBoot application) #324

fml2 opened this issue Mar 25, 2024 · 1 comment

Comments

@fml2
Copy link

fml2 commented Mar 25, 2024

I've asked this question on StackOverflow. Since I think that the behaviour I see is a bug, I'm creating this issue.

I have a SpringBoot based application (SpringBoot 3.2.4). The application is not a web application, i.e. it does not use servlets, views etc.

In the application, I want to create a report in the HTML format and send it via email. For creating the HTML, I want to use ThymeLeaf. I do it like this:

Context context = new Context();

context.setVariable("reportName", reportName);
context.setVariable("someOtherData", data);

return templateEngine.process("report", context);

The templateEngine bean is prepared and configured by SpringBoot.

Some of the values to be displayed in the report are of type java.time.Duration, others are of type java.util.Date (and some others). My goal is that those values are automatically formatted as I like it.

For that purpose, I created Printer classes and registered them in the Spring registry:

@Configuration
public class Config implements WebMvcConfigurer {

	@Override
	public void addFormatters(FormatterRegistry registry) {
		registry.addPrinter(new DatePrinter());
		registry.addPrinter(new DurationPrinter());
	}

}

where e.g. the DatePrinter looks like

public class DatePrinter implements Printer<Date> {

	@Override
	public String print(Date date, Locale locale) {
		return new SimpleDateFormat("yyyy-MM-dd").format(date);
	}

}

But that registrations do not seem to have any effect: In the report, all the values are displayed via their toString method. The report template looks e.g. like this: <td>[[${process.startTime}]]</td>, where the field startTime is a java.util.Date. My custom formatter does not get applied to it.

I also tried to register the formatters as Formatters rather than Printers, but it still didn't work.

In my view, I did everything as described e.g. in the Thymeleaf docs.

@fml2
Copy link
Author

fml2 commented Apr 8, 2024

@fml2 fml2 closed this as completed Apr 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant