Friday, September 10, 2010

Spring 3 session level Model Attributes with Multi Tab browsers

I wanted to share a solution that I came up with using Spring 3 with SessionAttributes and multiple tabs within the same session. Basically the issue is that if you open the first tab and do a get
to load the command object into the session and then open a second tab and do a get on the same controller with a different command object then the first tab's command object has been replaced by the second tab's command object and if you submit the form on the first tab then it will update the second tab's command object with the data from the first command object!

Spring by default uses the class DefaultSessionAttributeStore to store and retrieve the command objects from the session based upon the session attribute name only. This is what causes the command objects to be stomped on by multiple requests within the same session.

This is a known issue and a JIRA ticket has been created that will address this in version 3.1M1.

To address this issue until the fix is incorporated into Spring, I created the following solution:

I created the a class that implements the SessionAttributeStore interface. This class stores and retrieves the session level command objects based upon a unique (conversation id) that is automatically generated when the command object is stored on the session. So when you do a get request with a controller that has session attributes and you assign your command object to the model map, the storeAttribute method will be invoked and it will generate a unique conversation id (System.currTimeInMillis()) and append this to the attribute name (your command object name) and store it on the session as well as set the conversation id as a request attribute so that the view that is displayed can post back the conversation that it will be involved in. So all you have to do is add a hidden input field in your form that will post back the conversation id that it is in and the controller will issue a retrieveAttribute method and based upon the incoming conversation id will retrieve the correct command object from the session. I created a simple tag library that will create a hidden input field for you.

It is pretty simple to setup, basically you do the following:

In your dispatcher-servlet.xml file you define the class that you want to do the storing and retrieving of command objects from the session

<bean id="sessionConversationAttributeStore" class="com.marty.support.SessionConversationAttributeStore">
    <property name="numConversationsToKeep" value="10"/>
</bean>


Then you tell the AnnotationMethodHandlerAdapter class that you want to use a custom sessionAttributeStore:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="webBindingInitializer">
        <bean class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
            <property name="conversionService" ref="conversionService" />
        </bean>
    </property>
    <property name="sessionAttributeStore">
        <ref bean="sessionConversationAttributeStore"/>
    </property>     
</bean>


Finally you add the following tag library call inside your forms that use session model attributes:

<sessionConversation:insertSessionConversationId attributeName="<your command name here>"/>


Here is a link to a sample application that shows how to use the custom SessionAttributeStore along with the source code for the SessionConversationAttributeStore class and the SessionConversationIdTag tag library.


Hopefully someone else will find this helpful.

Marty

84 comments:

  1. Hello, Very usefull post about spring conversations. There are no any info about that.
    Could you please upload sample to another place? It is unavailable now.

    ReplyDelete
  2. Alexandr, I have updated the link to the sample application. You should be able to get to it now.

    Marty

    ReplyDelete
  3. I modified your SessionConversationAttributeStore to automatically attach itself to the AnnotationMethodHandlerAdapter - this allows you to still use mvc:annotation-driven. (Having to unroll the latter is problematic.)

    ie:

    public class SessionConversationAttributeStore implements SessionAttributeStore, InitializingBean {
    ...

    @Autowired private AnnotationMethodHandlerAdapter annotationMethodHandlerAdapter;

    public void afterPropertiesSet() throws Exception {
    annotationMethodHandlerAdapter.setSessionAttributeStore(this);
    }


    I also found it useful to implement a SessionConversationUrlParamTag to generate a name/value pair when you want to create a URL (ie. when you're not submitting a form).

    ReplyDelete
  4. Very thanks Marty,
    that worked very well for me.

    Eros

    ReplyDelete
  5. Very important post on SessionAttributes. I had many confusion with this this attribute but now I am very much clear about it. All credits goes to you. You described it briefly and in simple manner...loving it.

    forum widget

    ReplyDelete
  6. Thank You very much Marty !! It worked well. It was really best post about the spring conversation. Keep up posting ! I would love to add your blog in my favorite blog list.

    records management

    ReplyDelete
  7. I am glad the patch is working for you guys. It has served me well.

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Appriceate your detailed explanation.
    I have similar issue however, i am using spring 2.5.
    Can you please let me know how i can implement your fix in Spring 2.5?

    Thanks for your time!!

    ReplyDelete
  10. I believe the code should work in 2.5 although I have not tested it.

    What kind of problems are you having getting it implemented?

    ReplyDelete
  11. Hi Marty,

    Since i have added "mvc:annotation-driven" in my spring config, your implementation stopped working.

    Is there something you could help me with ?

    By the way thanks it is appreciated

    ReplyDelete
  12. here is a similar attempt which works with "mvc:annotaion-driven" - see 'afterPropertiesSet' http://duckranger.com/2012/11/add-conversation-support-to-spring-mvc/

    ReplyDelete
  13. For Spring 3.1+ you need to make following changes:

    1.Remove
    2. Add following bean config









































    ReplyDelete
  14. Very useful and Informative blog, keep updating and rocking..


    Java Training in Chennai

    ReplyDelete
  15. It seems you are so busy in last month. The detail you shared about your work and it is really impressive that's why i am waiting for your post because i get the new ideas over here and you really write so well.
    Java training in Bangalore | Java training in Indira nagar

    Java training in Bangalore | Java training in Rajaji nagar

    Java training in Bangalore | Java training in Marathahalli

    Java training in Bangalore | Java training in Btm layout

    ReplyDelete

  16. Greetings. I know this is somewhat off-topic, but I was wondering if you knew where I could get a captcha plugin for my comment form? I’m using the same blog platform like yours, and I’m having difficulty finding one? Thanks a lot.

    Advanced AWS Online Training | Online AWS Certification Course
    Best AWS Training in Chennai | Amazon Web Services Training Institute in Chennai Velachery, Tambaram, OMR
    Advanced AWS Training in Bangalore |Best AWS Training Institute in Bangalore BTMLA ,Marathahalli

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    mobile service center chennai
    mobile service centre near me
    mobile service centre chennai
    best mobile service center in chennai
    best mobile service center in chennai

    ReplyDelete
  19. You have made your points in a smart way. I am impressed with how interesting you have been able to present this content. Thanks for sharing a nice information. Do support us
    Fashion Design courses in chennai
    BSC Interior Design Colleges in Banaglore
    Fashion Designing Colleges In Bangalore
    Photography Courses In Chennai
    Fashion Designing Colleges In Chennai

    ReplyDelete
  20. nice blog
    get best placement at VSIPL

    digital marketing services
    web development company
    seo network point

    ReplyDelete
  21. Card màn hình cũ là một trong những linh kiện không thể thiếu của một máy tính để bàn trọn bộ. Một màn hình máy tính có kèm theo bộ card màn hình cũ sẽ giúp cho máy tính để bàn cho ra hình ảnh sắc nét hơn. Tuy nhiên card màn hình cũ cũng giống như hầu hết các linh kiện máy tính chúng đều cần vệ sinh định kỳ và sử dụng đúng cách.

    Thông tin bài viết này chúng tôi sẽ chia sẻ tới bạn cách vệ sinh card màn hình cũ của máy tính để bàn. Mời bạn tham khảo để có thông tin cho mình nhé

    Hướng dẫn cách vệ sinh card màn hình cũ của máy tính để bàn

    ReplyDelete

  22. This is most informative and also this post most user friendly and super navigation to all posts. Thank you so much for giving this information to me. Devops training in Chennai.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  23. ery interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    ReplyDelete
  24. I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. Definitely a great post. Hats off to you! The information that you have provided is very helpful.

    data science courses

    ReplyDelete
  25. Hi it's really informative,
    Thanks to share with us and keep more updates,

    https://www.porurtraining.in/hardware-and-networking-training-in-porur-chennai
    https://www.porurtraining.in/xamarin-training-in-porur-chennai
    https://www.porurtraining.in/ios-training-in-porur-chennai
    https://www.traininginvelachery.org/iot-training-in-velachery-chennai

    ReplyDelete
  26. The content is utmost interesting! I have completely enjoyed reading your points and have come to the conclusion that you are right about many of them. You are great,

    Data Science Training in Hyderabad

    ReplyDelete
  27. I am really happy to say it’s an interesting post to read . I learn new information from your article , you are doing a great job . Keep it up

    Devops Training in USA

    Hadoop Training in Hyderabad

    Python Training in Hyderabad

    ReplyDelete
  28. event planners are testing people associating results with registrants and tracking potential contact exposure. event marketing and conference bios

    ReplyDelete
  29. Thanks for the interesting content. I like your post and your blog is amazing.
    If you are interested in Video Downloader apps you can check my blog site. It is new and really informative.

    VidMate 2013

    ReplyDelete
  30. Hung was formerly an official distributor of industrial lubricants of Shell in the North. Currently, in addition to oil trading, we also trade in transportation and equipment trading. After nearly 12 years of establishment and development, Yen Hung is now a prestigious partner of nearly 10,000 large and small domestic and international factories. Main products:
    giá dầu truyền nhiệt
    dầu bánh răng
    dầu tuần hoàn
    dầu dẫn nhiệt
    dầu thủy lực shell
    mỡ bò bôi trơn chịu nhiệt

    ReplyDelete
  31. Goodness, so excellent and great post! A debt of gratitude is in order for offering a chance to peruse an incredible and fanciful blog. It gives me loads of joy and interest. A debt of gratitude is in order for sharing…

    AWS Training in Hyderabad

    ReplyDelete
  32. Nice blog. The process in which a web developer in Honolulu manages your website from start to finish, adding the latest content to keep your customers informed, and backing up your data. Hawaii webmaster services use SEO best practices to ensure that your site ranks highly. For more information, call 808-330-5506. Address:-350 Ward Avenue #262, Honolulu HI. 96814.

    ReplyDelete
  33. Superb Blog. If you are looking for Junk Car Removal Hawaii Company? Finest Towing Oahu is here to provide you with the best towing service available. We provide 24 hour towing service for all types of vehicles and models. Our junk car removal air services also give you a fair price.

    ReplyDelete
  34. Thanks for sharing. Finest Towing Maui is a certified, professional operator’s team expert that provides heavy-duty towing and towing truck services in Maui car removal services as soon as possible, across the island of Maui. Please contact 808-744-1964.

    ReplyDelete

  35. It's great to be back on your blog after a long absence. I have been eagerly awaiting this article for months. I require it to complete my college assignment, as it covers the same topic as your write-up. Thank you for sharing it.

    Best Colleges for MEC in Hyderabad

    ReplyDelete
  36. It's great to be back on your blog after such a long time. I've been eagerly anticipating this article for months. It will be very helpful for me to complete my college assignment, as it covers the same topic as your write-up. Thank you for sharing.

    CMA Coaching in Hyderabad

    ReplyDelete
  37. This post is incredibly fascinating and I thoroughly enjoyed reading it. It's exactly the kind of information I was searching for. Please continue to share more. Thank you for sharing.

    Best Junior Colleges in Hyderabad for MEC

    ReplyDelete
  38. Your blog post is great and it has inspired me, providing valuable information. I appreciate you sharing this exclusive content for our benefit.

    Best MEC Colleges in Hyderabad

    ReplyDelete
  39. To be completely honest, this blog is truly incredible when it comes to learning about a subject and expanding one's knowledge. It also helps in developing practical skills that can be applied in real life. Lastly, I would like to express gratitude to the blogger for their efforts and encourage them to continue launching more content in the future.

    Best Colleges for MEC in Hyderabad</

    ReplyDelete
  40. I find it quite refreshing to come across a well-written article for once. You have raised several intriguing points that I wholeheartedly agree with. Your piece has truly provoked some thought in me, and I extend my gratitude for that.

    Colleges in Hyderabad For BBA

    ReplyDelete
  41. É bom, me ajudou muito, porém tenho que lembrar que felinos não é s여주출장샵ó gato. Vi que você retratou sobre outros animais, mas foi bem pouco.. Mesmo assim parabéns!

    ReplyDelete