• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

在Thymeleaf方言处理器中访问HttpServletRequest和HttpServletResponse

spring-mvc 来源:Quirijn 20次浏览

我试图创建一个Thymeleaf方言处理器,它执行ServletDispatcher.include。我扩展了AbstractElementTagProcessor并重写了doProcess方法。相关的代码片段是:在Thymeleaf方言处理器中访问HttpServletRequest和HttpServletResponse

@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上下文?

===========解决方案如下:

您可以访问请求(通过使用#request对象,让你javax.servlet.http.HttpServletRequest对象直接访问)参数和会话(与#session对象,让您在javax.servlet.http.HttpSession对象直接访问)在Thymeleaf观点属性直接:

${#request.getAttribute('foo')} 
${#request.getParameter('foo')} 
${#request.getContextPath()} 
${#request.getRequestName()} 

<p th:if="${#request.getParameter('yourParameter') != null 
     th:text="${#request.getParameter('yourParameter')}"}">Request Param</p> 

${#session.getAttribute('foo')} 
${#session.id} 
${#session.lastAccessedTime} 

<p th:if="${session != null}"> th:text="${session.yourAttribute}"</p> 

阅读更多here。


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)