001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, 013 * software distributed under the License is distributed on an 014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 015 * KIND, either express or implied. See the License for the 016 * specific language governing permissions and limitations 017 * under the License. 018 */ 019package org.apache.shiro.web.filter.session; 020 021import org.apache.shiro.subject.support.DefaultSubjectContext; 022import org.apache.shiro.web.filter.PathMatchingFilter; 023 024import javax.servlet.ServletRequest; 025import javax.servlet.ServletResponse; 026 027/** 028 * A {@code PathMatchingFilter} that will disable creating new Sessions during the request. This is a useful 029 * filter to place in the front of any filter chains that may result in REST, SOAP or other service invocations that 030 * are not intended to participate in a session. 031 * <p/> 032 * This filter enables the following behavior: 033 * <ol> 034 * <li>If a {@code Subject} does not yet have a Session by the time this filter is called, this filter effectively 035 * disables all calls to {@code subject}.{@link org.apache.shiro.subject.Subject#getSession() getSession()} and 036 * {@code subject}.{@link org.apache.shiro.subject.Subject#getSession(boolean) getSession(true)}. If either are called 037 * during the request, an exception will be thrown.</li> 038 * <li> 039 * However, if the {@code Subject} already has an associated session before this filter is invoked, either because it 040 * was created in another part of the application, or a filter higher in the chain created one, this filter has no 041 * effect. 042 * </li> 043 * </ol> 044 * Finally, calls to <code>subject.getSession(false)</code> (i.e. a {@code false} boolean value) will be unaffected 045 * and may be called without repercussion in all cases. 046 * 047 * @since 1.2 048 */ 049public class NoSessionCreationFilter extends PathMatchingFilter { 050 051 @Override 052 protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception { 053 request.setAttribute(DefaultSubjectContext.SESSION_CREATION_ENABLED, Boolean.FALSE); 054 return true; 055 } 056}