首页 > 解决方案 > Spring MVC 在遍历应用程序时继续用户的表单(Dto)直到显式取消 - 控制器 @SessionScope 组件

问题描述

当用户遍历应用程序以及返回表单时,我在这里和那里尝试保持表单数据存在。表单正在使用绑定列表 (Dto.List),并且用户能够向其中添加条目,因此那里可能有一些工作,但并不是每次将新条目添加到列表时都必须保留表单(形式)。

普通控制器的方法没有实现这一点,因为每次用户离开该表单并返回时,这都会创建新的 Dto:

// Start with a brand new Dto
@GetMapping("/new")
public ModelAndView newDto() { return new ModelAndView( "form", "dto", new Dto() ); }

牢记以下几点: https ://rules.sonarsource.com/java/RSPEC-3750

我想出了以下实现,但我质疑它是否有更优雅的实现?

添加自定义.defaultSuccessUrl

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
...
.formLogin().loginPage("/login").defaultSuccessUrl( "/afterLogin", true )

添加/afterLogin端点并调整方法以在每次用户返回时不创建新对象

@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 );
  }
}

有更好的想法吗?如果用户的 Dto 已经存在,我尝试检查 keepDto 方法,但可能我不明白应该如何正确实现。提前感谢您的想法。

标签: springmodel-view-controllercomponentsstateful-session-bean

解决方案


推荐阅读