Search code examples
spring-mvcmigrationstruts

Struts 1.2.9 to spring MVC migration - Handling Scope of ActionForms


We are migrating a Struts 1.2.9 application to Spring MVC.

We are stuck on one point of scope of ActionForm defined to be "session". By default these are on "request" scope and understand on migrating to Spring, we can reuse these as Model Objects that are set in "request" scope by default.

But am lost on how to handle the "session" scope. Kindly advise.

struts-config.xml

<action path="/editSvc" scope="session"
    type="com.xyz.myapp.actions.SvcCodeEditAction" name="svcCodeForm"
    validate="false" parameter="reqCode">
    <forward name="success" path="/WEB-INF/jsp/svccode_edit.jsp" />
</action>

Action Class

//Code in com.xyz.myapp.actions.SvcCodeEditAction
  if (request.equals(mapping.getScope())) {
        request.setAttribute(mapping.getAttribute(), form);
    } else {
        setSessionAttribute(session,mapping.getAttribute(), form);
    }

Solution

  • You could get the mostly same functionality by using Spring @Scope("session") annotation above the bean class declaration.

    It's well explained in reference guide to spring 3.0 version :

    https://docs.spring.io/spring-framework/docs/3.0.0.M3/reference/html/ch04s04.html

    In general, if you add a spring-webmvc and spring-web to your project you could use

    @Bean
    @Scope("session")
    public SomeBean someBean() {
        return new SomeBean();
    }
    

    Or, if you prefer to use xml instead of java config you could go with smth simmilar to this:

    <bean id="userPreferences" class="com.foo.UserPreferences" scope="session"/>
    

    Also there is a good tutorial about it:

    http://www.baeldung.com/spring-bean-scopes

    Then if you add the bean to the model, it will automatically set-up in session if the bean has @SessionScope or @Scope("session") or whenever else bean scope declaration. By default beans would be added to the request scope.