Spring MVC:控制器之间共享@SessionAttributes? [英] Spring MVC: @SessionAttributes shared among controllers?
问题描述
我有一个用于搜索和结果列表的抽象控制器支持类:
I have an abstract controller support class for searches and result lists:
@Controller
@SessionAttributes("query")
public abstract class SearchController<Q extends SearchQuery> {
@RequestMapping
public String performSearch(@ModelAttribute("query") Q query) {
....
}
@ModelAttribute("query")
public abstract Q createDefaultSearchQuery();
}
几个实际的搜索控制器扩展了该基类.
Several actual search controllers extend this base class.
在访问了一个控制器(例如,使用BookSearchQuery implements SearchQuery
的/searchBooks.html
)之后,查询已正确存储在会话中,可用于后续请求.
After having accessed one of the controllers (say /searchBooks.html
using BookSearchQuery implements SearchQuery
) the query is correctly stored in the session, available for subsequent requests.
但是,当我访问另一个控制器(例如使用AuthorSearchQuery implements SearchQuery
的/searchAuthors.html
)时,来自上一个请求(BookSearchQuery
)的查询仍用于新控制器,从而导致稍后出现ClassCastException
.
However, when I access another controller (say /searchAuthors.html
using AuthorSearchQuery implements SearchQuery
) the query from the last request (BookSearchQuery
) is still being used for the new controller causing a ClassCastException
later on.
我尝试将@SessionAttribute
注释从支持类移至实现类,但无济于事.
I have tried moving the @SessionAttribute
annotation from the support class to the implementation classes, to no avail.
我在做错什么吗?或者这是设计使然?我该怎么办?
Is there something I'm doing wrong or is this by design? What can I do?
非常感谢!
推荐答案
使用@SessionAttributes
,这些对象将以相同的名称存储在HttpSession中,并且可以从不同的控制器进行访问(共享).因此,Spring的行为正确.
Using @SessionAttributes
this objects will be stored in your HttpSession with the same name and they will be accessible (shared) from different controllers. So, Spring is acting correctly.
我认为在您的方案中,最好的方法是在每个子类("BookQuery","AutorQuery",...)中重命名此属性.一点也不优雅:(
I think the best approach in your scenario is rename this attribute in every subclass ("BookQuery", "AutorQuery", ...). Not very elegant at all :(
这篇关于Spring MVC:控制器之间共享@SessionAttributes?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!