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;
020import javax.servlet.http.HttpSessionEvent;
021import javax.servlet.http.HttpSessionListener;
022
023/**
024 * Servlet HttpSessionListener that automatically exposes the session mutex
025 * when an HttpSession gets created. To be registered as a listener in
026 * {@code web.xml}.
027 *
028 * <p>The session mutex is guaranteed to be the same object during
029 * the entire lifetime of the session, available under the key defined
030 * by the {@code SESSION_MUTEX_ATTRIBUTE} constant. It serves as a
031 * safe reference to synchronize on for locking on the current session.
032 *
033 * <p>In many cases, the HttpSession reference itself is a safe mutex
034 * as well, since it will always be the same object reference for the
035 * same active logical session. However, this is not guaranteed across
036 * different servlet containers; the only 100% safe way is a session mutex.
037 *
038 * @author Juergen Hoeller
039 * @since 1.2.7
040 * @see WebUtils#SESSION_MUTEX_ATTRIBUTE
041 * @see WebUtils#getSessionMutex(javax.servlet.http.HttpSession)
042 * @see org.springframework.web.servlet.mvc.AbstractController#setSynchronizeOnSession
043 */
044public class HttpSessionMutexListener implements HttpSessionListener {
045
046        @Override
047        public void sessionCreated(HttpSessionEvent event) {
048                event.getSession().setAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE, new Mutex());
049        }
050
051        @Override
052        public void sessionDestroyed(HttpSessionEvent event) {
053                event.getSession().removeAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE);
054        }
055
056
057        /**
058         * The mutex to be registered.
059         * Doesn't need to be anything but a plain Object to synchronize on.
060         * Should be serializable to allow for HttpSession persistence.
061         */
062        @SuppressWarnings("serial")
063        private static class Mutex implements Serializable {
064        }
065
066}