Java中是否有请求上下文? [英] Is there a request context in Java?

查看:73
本文介绍了Java中是否有请求上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定如何在这里说出标题,因此我不确定如何去寻找答案。

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.

我有一个处理请求的java servlet引擎。假设我们有一个doGet请求:

I have a java servlet engine that handles requests. Say we have a doGet request:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //set up user data

    //do whatever the user requested
    SomeClass c = new SomeClass();
    c.doSomething();
}

现在在doSomething中,我希望能够访问哪个用户提出了请求。现在我通过创建一个java对象并将其传递到我需要的任何地方来实现:

Now in doSomething, I want to be able to access which user made the request. Right now I'm doing it by creating a java object and passing it to wherever I need:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //set up user data
    MyUserObj userObj = new MyUserObj();
    userObj.setId('123');

    //do whatever the user requested
    SomeClass c = new SomeClass(userObj);
    c.doSomething();
}

通过这样做,我可以访问MyUserObj的实例,它可以如果需要,可以进一步传递。

By doing this, I have access to the instance of MyUserObj, and it can be further passed along if needed.

这感觉很草率。在asp.net MVC3中(我目前正在学习它,在我开始学习java之后开始,但发现这非常方便,所以让我重新思考我是如何在java中做的)我可以,例如,为当前存储项目像这样的线程: HttpContext.Current.Items.Add(myId,123)。然后 HttpContext 可以在其他函数中使用,而不必传递一个对象。

This feels sloppy. In asp.net MVC3 (I'm currently learning it, started after I began learning java, but found this to be really convenient so made me rethink how I was doing it in java) I can, for example, store items for the current thread like this: HttpContext.Current.Items.Add("myId", "123"). HttpContext is then available in other functions without me having to pass around an object.

java中有没有办法为每个请求设置一些变量(甚至设置 MyUserObject 以便稍后访问)而不将对象作为参数传递?

Is there a way in java to set some variables per request (or even set the MyUserObject to be accessed later) without passing the object through as a parameter?

如果这是一个常见的已经回答的问题,请随意指出我正确的方向,因为我不确定如何表达它。

If this is a common already-answered question feel free to point me in the right direction as I wasn't sure how to phrase it.

推荐答案

servlet API中没有,但你可以很容易地创建自己的。 (像spring-mvc这样的框架,struts提供了这样的功能)

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

只需使用 public static ThreadLocal 来存储和检索对象。您甚至可以在threadlocal中存储 HttpServletRequest 本身并使用其 setAttribute() / getAttribute ()方法,或者你可以存储threadlocal Map ,以便与servlet API无关。一个重要的注意事项是您应该在请求后清理threadlocal(例如,使用Filter)。

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).

另请注意,将对象作为参数传递被认为是更好的做法,因为您通常将其从Web层传递到服务层,而服务层不应依赖于Web相关对象,如 HttpContext

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);
    }
}

必要的过滤器:

@WebFilter(urlPatterns="/")
public class RequestContextFilter implements Filter {
     public void doFilter(..) {
         RequestContext.initialize();
         try {
             chain.doFilter(request, response);
         } finally {
             RequestContext.cleanup();
         }
     }
}

这篇关于Java中是否有请求上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆