Spring MVC继续用户';s窗体(Dto)在遍历应用程序时,直到显式取消为止-Controller@SessionScope组件
当用户在浏览应用程序时,我会不时地尝试保持表单数据的存在 当他回到一种状态时也是如此。表单使用绑定列表(Dto.list), 用户可以向其中添加条目,这样可能会有一些工作,但不会太多 每次将新条目添加到列表(在表单中)时,必须持久化表单 琐碎控制器的方法无法实现这一点,因为每次用户离开时都会创建新的Dto 该表单并返回:Spring MVC继续用户';s窗体(Dto)在遍历应用程序时,直到显式取消为止-Controller@SessionScope组件,spring,model-view-controller,components,stateful-session-bean,Spring,Model View Controller,Components,Stateful Session Bean,当用户在浏览应用程序时,我会不时地尝试保持表单数据的存在 当他回到一种状态时也是如此。表单使用绑定列表(Dto.list), 用户可以向其中添加条目,这样可能会有一些工作,但不会太多 每次将新条目添加到列表(在表单中)时,必须持久化表单 琐碎控制器的方法无法实现这一点,因为每次用户离开时都会创建新的Dto 该表单并返回: // Start with a brand new Dto @GetMapping("/new") public ModelAndView newDto()
// Start with a brand new Dto
@GetMapping("/new")
public ModelAndView newDto() { return new ModelAndView( "form", "dto", new Dto() ); }
牢记以下几点:
我提出了以下实现,但我质疑是否有更优雅的实现
添加自定义。默认成功URL
@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方法,
但我可能不明白应该如何恰当地实现这一点。
提前感谢您的建议。您的上一个示例很危险,而且不是线程安全的。当m多个用户使用此功能时,他们会互相使用
Dto
。还有,安全性与此有什么关系?请加上你的实际控制员,这不起作用(根据你)。您应该使用的是@SessionAttributes
将dto存储在用户HTTP会话中以供重用。当我使用来自两个不同web浏览器的两个不同用户对其进行测试时,我看不到多个用户正在使用同一dto。顺便说一句,Dto当然是RSPEC建议的@SessionScope。不,Dto不是会话作用域,因为您自己正在创建一个新实例。如果有两个并发请求进入,它们将相互覆盖。这将在某个时候导致问题。所以你现在所做的同样是危险的。如前所述,您应该在控制器上使用@SessionAttributes
来确定会话中要坚持的内容。