What is the springMacroRequestContext called in bind macro of spring.ftl?

4.4k views Asked by At

The Springframework is able to integrate with the freemarker template engine. Spring provides a spring.ftl with core macros and functions to ease form support. To call a macro that builds a form field for you as well as resolves value selection (even for singleSelects or multiSelects).

The essential component that does the myth is their bind macro, which calls some mysterious springMacroRequestContext to get bind status information.

Where the hell does this variable come from and what is hidden behind it?

2

There are 2 answers

0
s10z On BEST ANSWER

Responsible for this is the class org.springframework.web.servlet.view.AbstractTemplateView, provided by spring-mvc.*.jar - line 154 / method renderMergedOutputModel(.*).

The template variable is injected by hard coding. Next to some other environmental stuff, I recognized.

When using the springMacroRequestContext we are talking to an instance of org.springframework.web.servlet.support.RequestContext.

The bind call creates an instance of org.springframework.web.servlet.support.BindStatus.

I do not write a blog. But there might be folks like me who were searching for this to understand what is going on :)

0
Oleksii Kyslytsyn On

By researching it was found the following sequence of procedure calls for manual instantiation:

String SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE = "springMacroRequestContext";
Map<String, Object> model = new HashMap();
model.put(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE,
                    new RequestContext(request, /*response, */
                                            /*request.getSession().getServletContext(),*/
                                            /*getServletContext()*/ model));

and later

Template t = freemarkerConfig.getConfiguration().getTemplate(templateName);
String text = FreeMarkerTemplateUtils.processTemplateIntoString(t, model);

It will seamlessly provide for developer an access to common spring "macro"-s(like spring.message, singleSelects and others).

As it is evident, it is required to pass at least non-null http servlet request instance.

Now I am searching for an instantiation approach of springMacroRequestContext for a case of unavailability of http servlet request instance.

For now: I do not know "Where the hell does this variable come from" initially, because I did not debug or trace spring own instantiations. However, I partially answered the second part of the question: "and what is hidden behind it" so actually it is a RequestContext();.