我试图创建一个执行ServletDispatcher.include的Thymeleaf方言处理器。我扩展了AbstractElementTagProcessor并重写了doProcess方法。相关的代码片段是:
@Override
protected void doProcess(final ITemplateContext context, final IProcessableElementTag tag, final IElementTagStructureHandler structureHandler) {
ServletContext servletContext = null; // TODO: get servlet context
HttpServletRequest request = null; // TODO: get request
HttpServletResponse response = null; // TODO: get response
// Retrieve dispatcher to component JSP view
RequestDispatcher dispatcher = servletContext.getRequestDispatcher("/something");
// Create wrapper (acts as response, but stores output in a CharArrayWriter)
CharResponseWrapper wrapper = new CharResponseWrapper(response);
// Run the include
dispatcher.include(request, wrapper);
String result = wrapper.toString();
// Create a model with the returned string
final IModelFactory modelFactory = context.getModelFactory();
final IModel model = modelFactory.parse(context.getTemplateData(), result);
// Instruct the engine to replace this entire element with the specified model
structureHandler.replaceWith(model, false);
我过去以自定义JSP标记的形式编写了类似的代码。问题是:我不知道如何访问ServletContext,HttpServletRequest和HttpServletResponse! 可以这样做,还是我应该接受Thymeleaf擅长隐藏HTTP上下文?
答案 0 :(得分:4)
您可以访问请求(使用#request
对象,可以直接访问javax.servlet.http.HttpServletRequest
个对象)参数和会话(使用#session
对象,可以直接访问{{直接在Thymeleaf视图中的1}} object)属性:
javax.servlet.http.HttpSession
了解更多here。
答案 1 :(得分:1)
我发现自己有一个非常相似的要求,即从request
的实现中访问IExpressionObjectFactory
。
我解决问题的方式(在上一条评论中,@ Sebastian Marsching建议之后)是访问在模板IExpressionContext
中注册的对象,这些对象可在模板评估的上下文中从视图中使用({ {3}}和Appendix A),因此您可以访问请求,响应,servletContext和许多其他实用程序对象。
以代码发言:
IExpressionObjects expressionObjects = context.getExpressionObjects();
HttpServletRequest request = (HttpServletRequest)expressionObjects.getObject("request");
还有一个expressionObjects.getObjectNames()
方法,您可以调用该方法以获取包含所有已注册对象名称的Set<String>
,在我的情况下,该列表提供了以下列表:
[i18nutils, ctx, root, vars, object, locale, request, response, session,
servletContext, conversions, uris, calendars, dates, bools, numbers, objects,
strings, arrays, lists, sets, maps, aggregates, messages, ids, execInfo,
httpServletRequest, httpSession, fields, themes, mvc, requestdatavalues]