Is there a generic RequestContext in Java servlet API?

后端 未结 2 1314
感情败类
感情败类 2021-02-13 09:43

(I\'m not sure exactly how to phrase the title here, and because of that I\'m not really sure how to go about searching for the answer either.)

I have a Java se

相关标签:
2条回答
  • 2021-02-13 09:58

    You can attach an object to the current request with setAttribute. This API is primarily used for internal routing, but it's safe to use for your own purposes too, as long as you use a proper namespace for your attribute names.

    0 讨论(0)
  • 2021-02-13 10:06

    There isn't in the servlet API, but you can make your own pretty easily. (Some frameworks like spring-mvc, struts provide such functionality)

    Just use a public static ThreadLocal to store and retrieve the object. You can even store the HttpServletRequest itself in the threadlocal and use its setAttribute()/getAttribute() methods, or you can store a threadlocal Map, to be agnostic of the servlet API. An important note is that you should clean the threadlocal after the request (with a Filter, for example).

    Also note that passing the object as parameter is considered a better practice, because you usually pass it from the web layer to a service layer, which should not be dependent on web-related object, like a HttpContext.

    If you decide that it is fine to store them in a thread-local, rather than passing them around:

    public class RequestContext {
        private static ThreadLocal<Map<Object, Object>> attributes = new ThreadLocal<>();
        public static void initialize() {
            attributes.set(new HashMap<Map<Object, Object>>());
        }
        public static void cleanup() {
            attributes.set(null);
        }
        public static <T> T getAttribute(Object key) {
            return (T) attributes.get().get(key);
        }
        public static void setAttribute(Object key, Object value) {
            attributes.get().put(key, value);
        }
    }
    

    And a necessary filter:

    @WebFilter(urlPatterns="/")
    public class RequestContextFilter implements Filter {
         public void doFilter(..) {
             RequestContext.initialize();
             try {
                 chain.doFilter(request, response);
             } finally {
                 RequestContext.cleanup();
             }
         }
    }
    
    0 讨论(0)
提交回复
热议问题