spring - 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 方法,但可能我不明白应该如何正确实现。提前感谢您的想法。
解决方案
推荐阅读
- python - 最佳优化公式?
- c# - WebClient 未遵循 .Net Core 3.1 中的重定向
- javascript - ajax 向 PHP 提交错误的数据
- python-3.x - Qt:在包含子布局的 QFormLayout 中显示或隐藏行
- java - 如何使用 spring-data 检索 mongodb 集合?
- django - 使用 PyCharm 创建 Django 项目时出错
- javascript - 无法在反应组件中使用 postMessage
- azure-functions - 如何编写一个 CosmosDBTrigger 来更新已更改的同一文档?
- python - 编写代码对多个 pandas DataFrames 执行相同的操作
- python - 发送嵌入 discord.py 后收听反应或消息