2016-12-30 14 views
2

ServletDispatcher.includeを実行するThymeleafダイアレクトプロセッサを作成しようとしています。私は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コンテキストを隠すことができないと受け入れるだけですか?

答えて

3

あなたはThymeleafビューで直接属性(あなたjavax.servlet.http.HttpSessionオブジェクトに直接アクセスすることができます#sessionオブジェクトで)パラメータとセッション(あなたのjavax.servlet.http.HttpServletRequestオブジェクトに直接アクセスすることができます#requestオブジェクトを使用して)要求にアクセスすることができます。

${#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

ありがとう、DimaSan。私はこれを認識していますが、私はこの意見を書いている人たちからこのすべてを抽象化したいと思います。彼らはちょうどこのように私の方言を使うことができるはずです: Quirijn

+0

私は、この記事があなたに役立つかもしれないことを知っています:[Thymeleafの拡張](http://www.thymeleaf.org/doc/tutorials/3.0/extendingthymeleaf .pdf)。 ** 3.4章を見てください。当社の見出し**の要素プロセッサ。 – DimaSan

+0

ありがとうございます。この記事を読んだ後も、現在のリクエスト、サーブレット・コンテキスト、および/またはプロセッサーからの応答にアクセスする方法はまだわかりません。私はそれが単純にできないと思う。私は別の解決策を探します。 – Quirijn

関連する問題