2015-07-01 4 views
1

В моем проекте мне требуется SessionBean для хранения объектов, связанных с текущим сеансом. В сеансе создается, и пользователь аутентифицирован. Я хочу установить объекты в свой компонент.Инициализация инициализации начальной сессии сеанса в событии

Bean определение:

<bean scope="session" class="org.example.SessionBean"> 
    <aop:scoped-proxy/> 
</bean> 

Authentication СЛУШАТЕЛЬ:

public class SpringAuthenticationListener implements ApplicationListener<ApplicationEvent> { 

private LogService logService; 

private UserService userService; 

@Autowired 
private SessionBean sessionBean; 

public SpringAuthenticationListener(LogService logService, UserService userService) { 
    this.logService = logService; 
    this.userService = userService; 
} 

@Override 
public void onApplicationEvent(ApplicationEvent e) { 
    LogEvent logEvent = new LogEvent(); 

    if (e instanceof AuthenticationSuccessEvent) { 
     AuthenticationSuccessEvent event = (AuthenticationSuccessEvent) e; 
     UserDetails userDetails = (UserDetails) event.getAuthentication().getPrincipal(); 

     User loggedUser = userService.getUser(userDetails.getUsername()); 
     sessionBean.setLoggedUser(loggedUser); 
    } 
} 

}

Но, проблема в том, что я не могу получать экземпляр текущего SessionBean экземпляра. Это моя ошибка:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.org.example.SessionBean#0': Scope 'session' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. 

Как это сделать? Какое событие или слушатель разрешит мне инициализировать SessionBean с текущим пользователем.

ответ

1

Spring Security работает с использованием фильтров Filter, которые выполняются перед любыми Servlet и как таковые также перед DispatcherServlet. Чтобы иметь возможность использовать request или session скошенные бобы a RequestContext. Обычно это готовится с помощью DispatcherServlet. Если вы хотите использовать скошенные бобы за пределами DispatcherServlet, вам необходимо выполнить дополнительную настройку. Кроме того, как заявил, за исключением:

use RequestContextListener or RequestContextFilter to expose the current request.

Чтобы исправить добавить RequestContextListener или RequestContextFilter к вашему web.xml. При использовании последнего убедитесь, что он выполнен до springSecurityFilterChain, иначе он не вступит в силу. Слушатель всегда выполняется перед любым фильтром.

+0

RequestContextListener отлично работает – kris14an