title: Spring MVC Continue user's Form (Dto) when traversing an app until explicit cancel - Controller @SessionScope Component
body: <p>here and there I was trying to keep form data present when a user is traversing an app
  and as well when he returns to a form. Form is using a binding list (Dto.List),
  and user is capable to add entries to it so there might be some work there, but not so much
  that the form must be persisted every time a new entry is added to the list (in a form).</p>
  <p>Trivial controller's method isn't achieving this, because this creates new Dto every time user leaves
  that form and returns back:</p>
  <pre><code>// Start with a brand new Dto
  @GetMapping(&quot;/new&quot;)
  public ModelAndView newDto() { return new ModelAndView( &quot;form&quot;, &quot;dto&quot;, new Dto() ); }
  </code></pre>
  <p>Keeping following in mind:
  <a href="https://rules.sonarsource.com/java/RSPEC-3750" rel="nofollow noreferrer">https://rules.sonarsource.com/java/RSPEC-3750</a></p>
  <p>I came up with the following implementation, but I am questioning it if there is more elegant one?</p>
  <p>add custom <strong>.defaultSuccessUrl</strong></p>
  <pre><code>@Configuration
  @EnableWebSecurity
  public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  ...
  .formLogin().loginPage(&quot;/login&quot;).defaultSuccessUrl( &quot;/afterLogin&quot;, true )
  </code></pre>
  <p>add <strong>/afterLogin</strong> endpoint and adjust method to not create new object every time user returns</p>
  <pre><code>@Controller
  public class DtoController {
  
    // Per user Dto
    Dto dto;
  
    // Initialize Dto
    @GetMapping(&quot;/afterLogin&quot;)
    public String afterLogin() {
      dto = new Dto();
      return &quot;redirect:/&quot;;
    }
  
    // Never Start with a brand-new Dto until user hits Cancel button
    @GetMapping(&quot;/new&quot;)
    public ModelAndView keepDto() { return new ModelAndView( &quot;form&quot;, &quot;dto&quot;, dto ); }
  
  
    // Add another Entry to Dto
    @PostMapping( value = &quot;/mgmt&quot;, params = &quot;Add&quot; )
    public ModelAndView add( @ModelAttribute(&quot;dto&quot;) Dto dto ) {
      this.dto = dto;                         // Binding List((re) set/change if changed or not)
      dto.add( nextID.getAndDecrement() );    // Add new entry to the list (these IDs will be ignored when creating new set @OneToMany)
      return new ModelAndView( &quot;form&quot;, &quot;dto&quot;, dto );
    }
  }
  </code></pre>
  <p>Any better ideas? I tried to check in keepDto method if user's Dto already exist,
  but probably I don't understand how that should be achieved properly.
  Thanks for ideas in advance.</p>