Greg
Greg

Reputation: 147

Java Exception handling and HttpSession

As part of exception handling, I want to print data from HTTP session like below:

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?

Upvotes: 0

Views: 1588

Answers (2)

kosa
kosa

Reputation: 66637

Session will be unique for each user (if code is according to standard).

Here is sun tutorial on how session works

Upvotes: 0

BalusC
BalusC

Reputation: 1108782

The HttpSession is not shared among clients. So that part is safe already. The remnant depends on your own code as to obtaining and handling the HttpSession instance. 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.

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:

Upvotes: 1

Related Questions