为了解决在模版中通过 @bean.method() 方式调用 spring 的bean对象方法报错问题,参考ThymeleafView的rendFragment()方法, 删减了一些用不到的代码,记录一下备用.
- import org.springframework.context.ApplicationContext;
- import org.springframework.core.convert.ConversionService;
- import org.springframework.web.servlet.support.RequestContext;
- import org.thymeleaf.IEngineConfiguration;
- import org.thymeleaf.context.WebExpressionContext;
- import org.thymeleaf.spring5.ISpringTemplateEngine;
- import org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext;
- import org.thymeleaf.spring5.expression.ThymeleafEvaluationContext;
- import org.thymeleaf.util.FastStringWriter;
-
- import javax.servlet.ServletContext;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
- import java.io.Writer;
- import java.util.HashMap;
- import java.util.Locale;
- import java.util.Map;
-
- /**
- * 结合springMVC使用的thymeleaf 模版手动渲染,解决模版页面 @xxx 调用springbean方法报错问题
- */
- public class ThymeleafUtil {
-
- public static String renderTemplate(String templateName, Map
modelMap, - HttpServletRequest request, HttpServletResponse response,
- ApplicationContext applicationContext,
- ISpringTemplateEngine viewTemplateEngine) throws Exception {
- ServletContext servletContext = request.getServletContext();
-
- Map
mergedModel = new HashMap(30); -
- if (modelMap != null) {
- mergedModel.putAll(modelMap);
- }
-
- RequestContext requestContext = new RequestContext(request, response, servletContext, mergedModel);
- SpringWebMvcThymeleafRequestContext thymeleafRequestContext = new SpringWebMvcThymeleafRequestContext(requestContext, request);
- if (!mergedModel.containsKey("springRequestContext")) {
- mergedModel.put("springRequestContext", requestContext);
- }
- if (!mergedModel.containsKey("springMacroRequestContext")) {
- mergedModel.put("springMacroRequestContext", requestContext);
- }
-
- mergedModel.put("thymeleafRequestContext", thymeleafRequestContext);
- ConversionService conversionService = (ConversionService) request.getAttribute(ConversionService.class.getName());
- ThymeleafEvaluationContext evaluationContext = new ThymeleafEvaluationContext(applicationContext, conversionService);
- mergedModel.put("thymeleaf::EvaluationContext", evaluationContext);
- IEngineConfiguration configuration = viewTemplateEngine.getConfiguration();
- WebExpressionContext context = new WebExpressionContext(configuration, request, response, servletContext, Locale.getDefault(), mergedModel);
-
- Writer templateWriter = new FastStringWriter(1024);
- viewTemplateEngine.process(templateName, null, context, (Writer) templateWriter);
- return templateWriter.toString();
-
- }
- }