简体   繁体   English

Java异常处理和HttpSession

[英]Java Exception handling and HttpSession

As part of exception handling, I want to print data from HTTP session like below: 作为异常处理的一部分,我想从HTTP会话中打印数据,如下所示:

try{  
    //business logic
} catch(Exception ex){
    String user = session.get("userId"); //get user from HTTP Session.
    log.info("Exception when processign the user "+user); 
}

My question is do I get the correct UserId for which exception occurred since there will be mulitple threads updating the session? 我的问题是,由于会有多个线程更新会话,因此我是否为发生异常的正确用户ID?

The HttpSession is not shared among clients. HttpSession未在客户端之间共享。 So that part is safe already. 因此该部分已经安全。 The remnant depends on your own code as to obtaining and handling the HttpSession instance. 剩余部分取决于您自己的代码来获取和处理HttpSession实例。 If you're for example assinging the HttpSession as an instance variable of an application wide class, like the servlet itself, then it is indeed not thread safe as it might be overridden by another request at the moment you're accessing it. 例如,如果将HttpSession作为应用程序范围的类的实例变量(例如Servlet本身)来声明,那么它确实不是线程安全的,因为在您访问它时,它可能会被另一个请求覆盖。

public class SomeServlet extends HttpServlet {

    private HttpSession session;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        session = request.getSession();

        // ...

        Object object = session.getAttribute("foo"); // Not threadsafe!
    }  

See also: 也可以看看:

Session will be unique for each user (if code is according to standard). 每个用户的会话都是唯一的(如果代码符合标准)。

Here is sun tutorial on how session works 这是有关会话如何工作的 Sun教程

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM