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).
Trivial controller's method isn't achieving this, because this creates new Dto every time user leaves that form and returns back:
// Start with a brand new Dto
@GetMapping("/new")
public ModelAndView newDto() { return new ModelAndView( "form", "dto", new Dto() ); }
Keeping following in mind: https://rules.sonarsource.com/java/RSPEC-3750
I came up with the following implementation, but I am questioning it if there is more elegant one?
add custom .defaultSuccessUrl
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
.formLogin().loginPage("/login").defaultSuccessUrl( "/afterLogin", true )
add /afterLogin endpoint and adjust method to not create new object every time user returns
@Controller
public class DtoController {
// Per user Dto
Dto dto;
// Initialize Dto
@GetMapping("/afterLogin")
public String afterLogin() {
dto = new Dto();
return "redirect:/";
}
// Never Start with a brand-new Dto until user hits Cancel button
@GetMapping("/new")
public ModelAndView keepDto() { return new ModelAndView( "form", "dto", dto ); }
// Add another Entry to Dto
@PostMapping( value = "/mgmt", params = "Add" )
public ModelAndView add( @ModelAttribute("dto") 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( "form", "dto", dto );
}
}
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.