001/* 002 * Copyright 2002-2017 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.reactive.result.method.annotation; 018 019import reactor.core.publisher.Mono; 020 021import org.springframework.beans.factory.config.ConfigurableBeanFactory; 022import org.springframework.core.MethodParameter; 023import org.springframework.core.ReactiveAdapterRegistry; 024import org.springframework.util.Assert; 025import org.springframework.web.bind.annotation.SessionAttribute; 026import org.springframework.web.bind.annotation.ValueConstants; 027import org.springframework.web.server.ServerWebExchange; 028import org.springframework.web.server.ServerWebInputException; 029 030/** 031 * Resolves method arguments annotated with an @{@link SessionAttribute}. 032 * 033 * @author Rossen Stoyanchev 034 * @since 5.0 035 * @see RequestAttributeMethodArgumentResolver 036 */ 037public class SessionAttributeMethodArgumentResolver extends AbstractNamedValueArgumentResolver { 038 039 public SessionAttributeMethodArgumentResolver(ConfigurableBeanFactory factory, ReactiveAdapterRegistry registry) { 040 super(factory, registry); 041 } 042 043 044 @Override 045 public boolean supportsParameter(MethodParameter parameter) { 046 return parameter.hasParameterAnnotation(SessionAttribute.class); 047 } 048 049 @Override 050 protected NamedValueInfo createNamedValueInfo(MethodParameter parameter) { 051 SessionAttribute ann = parameter.getParameterAnnotation(SessionAttribute.class); 052 Assert.state(ann != null, "No SessionAttribute annotation"); 053 return new NamedValueInfo(ann.name(), ann.required(), ValueConstants.DEFAULT_NONE); 054 } 055 056 @Override 057 protected Mono<Object> resolveName(String name, MethodParameter parameter, ServerWebExchange exchange) { 058 return exchange.getSession() 059 .filter(session -> session.getAttribute(name) != null) 060 .map(session -> session.getAttribute(name)); 061 } 062 063 @Override 064 protected void handleMissingValue(String name, MethodParameter parameter) { 065 String type = parameter.getNestedParameterType().getSimpleName(); 066 String reason = "Missing session attribute '" + name + "' of type " + type; 067 throw new ServerWebInputException(reason, parameter); 068 } 069 070}