开发者

spring - how to pass a value from an app to a filter

So I need to add a filter to a spring app, such that after the response has been flushed back to the client, I write to a log file. The values I want to write to the log file are determined within the app. In other words, I would like to pass values, ideally a hashmap of values, to the filter that sits after the main processing has completed.

Is there a best practice way of doing this? I could imagine that I could instantiate the hashMap in the filter when the request first comes in, stash that hashmap somewhere (where?), retrieve it in the app and write to it, and then retrieve it again in the exit filter and write the value out. Is that the best practice way to do it, and if so:

1) Do I have just one filter that fires on entry and exit or do I need to set up two, one for before the app and one for after?

2) Where is the best practice place 开发者_StackOverflow社区to stash my data store?


@Adi's answer explains how to do the job with a single filter and filter chaining.

But instead of using ThreadLocal, I suggest that you use ServletRequest.getAttribute(...) and ServletRequest.setAttribute(...); see the ServletRequest API docs.


  1. One filter is enough. In filter

    //Before calling the servlet. Do something

    chain.doFilter(request, wrapper);
    

    //After servlet completes processing. Retrieve data here.

  2. Consider ThreadLocal variables. I am not sure if this is best practice. You will store data in servlet and retrieve in filter (after 'chain.doFilter()'. But make sure that you clean up the data stored in ThreadLocal before the request is complete because server pool threads so your data in thread locals may not be cleaned.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜