Is there a generic RequestContext in Java servlet API?

后端 未结 2 1312
感情败类
感情败类 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 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> attributes = new ThreadLocal<>();
        public static void initialize() {
            attributes.set(new HashMap>());
        }
        public static void cleanup() {
            attributes.set(null);
        }
        public static  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();
             }
         }
    }
    

提交回复
热议问题