001/*
002 * Copyright 2002-2015 the original author or authors.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *      https://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.springframework.web.util;
018
019import java.io.Serializable;
020
021import javax.servlet.http.HttpSessionEvent;
022import javax.servlet.http.HttpSessionListener;
023
024/**
025 * Servlet HttpSessionListener that automatically exposes the session mutex
026 * when an HttpSession gets created. To be registered as a listener in
027 * {@code web.xml}.
028 *
029 * <p>The session mutex is guaranteed to be the same object during
030 * the entire lifetime of the session, available under the key defined
031 * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a
032 * safe reference to synchronize on for locking on the current session.
033 *
034 * <p>In many cases, the HttpSession reference itself is a safe mutex
035 * as well, since it will always be the same object reference for the
036 * same active logical session. However, this is not guaranteed across
037 * different servlet containers; the only 100% safe way is a session mutex.
038 *
039 * @author Juergen Hoeller
040 * @since 1.2.7
041 * @see WebUtils#SESSION_MUTEX_ATTRIBUTE
042 * @see WebUtils#getSessionMutex(javax.servlet.http.HttpSession)
043 * @see org.springframework.web.servlet.mvc.AbstractController#setSynchronizeOnSession
044 */
045public class HttpSessionMutexListener implements HttpSessionListener {
046
047        @Override
048        public void sessionCreated(HttpSessionEvent event) {
049                event.getSession().setAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE, new Mutex());
050        }
051
052        @Override
053        public void sessionDestroyed(HttpSessionEvent event) {
054                event.getSession().removeAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE);
055        }
056
057
058        /**
059         * The mutex to be registered.
060         * Doesn't need to be anything but a plain Object to synchronize on.
061         * Should be serializable to allow for HttpSession persistence.
062         */
063        @SuppressWarnings("serial")
064        private static class Mutex implements Serializable {
065        }
066
067}