Adding session synchronization to Spring MVC

北城以北 提交于 2019-12-06 11:00:54

问题


I need to add session synchronization to a Spring MVC application. I'm using Spring 3.1.2.

The synchronization is required because I will have multiple AJAX calls updating session data. Rather than synchronize the session data within the web app, the design decision was made to force the incoming calls to be processed synchronously.

In my servlet.xml, I have the following:

<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="synchronizeOnSession" value="true" />
</bean>

Yet if I do two AJAX calls from the same session to the same request handler, they both will execute at the same time. I was expecting the synchronizeOnSession to prevent this.

Am I missing something in the configuration?


回答1:


I ended up adding a BeanPostProcessor to set the synchronizeOnSession flag.

Added this new class:

@Component
public class MyPostProcessor implements BeanPostProcessor
{
  @Override
  public Object postProcessBeforeInitialization( Object bean, String name ) throws BeansException
  {
    if( bean instanceof RequestMappingHandlerAdapter )
    {
      RequestMappingHandlerAdapter adapter = ( RequestMappingHandlerAdapter ) bean;
      adapter.setSynchronizeOnSession( true );
    }

    return bean;
  }

  @Override
  public Object postProcessAfterInitialization( Object bean, String beanName ) throws BeansException
  {
    return bean;
  }
}

Along with a component scan entry in the application context:

<context:component-scan base-package="com.company.base.spring.MyPostProcessor" />

You can set a breakpoint in the RequestMappingHandlerAdapter (org.springframework.web.servlet.mvc.method.annotation) at handleInternal(...) to confirm that the synchronizeOnSession is set to true.



来源:https://stackoverflow.com/questions/21705024/adding-session-synchronization-to-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!