javascript
在基于Spring的Web应用程序中使用Http Session
在基于Spring的Web應用程序中擁有和使用Http會話有多種方法。 這是基于最近項目經驗的總結。
方法1
只需在需要的HttpSession中注入即可。
盡管令人驚訝,但由于上述服務是單例服務,因此效果很好。 Spring智能地將代理插入到實際的HttpSession中,并且該代理知道如何在內部委派給請求的正確會話。
但是,以這種方式處理會話的問題在于,必須由用戶來管理要在會話中檢索和保存回的對象:
public void removeFromCart(long productId) {ShoppingCart shoppingCart = getShoppingCartInSession();shoppingCart.removeItemFromCart(productId);updateCartInSession(shoppingCart); }方法2
接受它作為參數,盡管如此,它僅在Web層中有效:
@Controller public class ShoppingCartController {@RequestMapping("/addToCart")public String addToCart(long productId, HttpSession httpSession) {//do something with the httpSession }}方法3
創建一個bean并將其范圍設置為會話:
@Component @Scope(proxyMode=ScopedProxyMode.TARGET_CLASS, value="session") public class ShoppingCart implements Serializable{ ... }Spring為會話范圍的Bean創建代理,并使該代理可用于注入該Bean的服務。 使用這種方法的優點是,該bean上的任何狀態更改均由Spring處理,它將負責從會話中檢索此bean并將對bean的任何更改傳播回會話。 此外,如果bean具有任何Spring生命周期方法(例如@PostConstruct或@PreDestroy注釋的方法),則會對其進行適當調用。
方法4
使用@SessionAttribute批注來批注Spring MVC模型屬性:
@SessionAttributes("shoppingCart") public class OrderFlowController {public String step1(@ModelAttribute("shoppingCart") ShoppingCart shoppingCart) {}public String step2(@ModelAttribute("shoppingCart") ShoppingCart shoppingCart) {}public String step3(@ModelAttribute("shoppingCart") ShoppingCart shoppingCart, SessionStatus status) {status.setComplete();} }使用SessionAttributes批注的用例非常具體,可以在上述流程中保持狀態。
有了這些方法,我個人更喜歡使用會話范圍的bean的方法3,這種方法取決于Spring來管理將對象檢索和存儲到會話中的底層細節。 盡管根據您可能會遇到的情況,其他方法也很有用,從要求對原始Http會話進行更多控制到需要處理臨時狀態(如上述方法4)。
翻譯自: https://www.javacodegeeks.com/2014/04/using-http-session-with-spring-based-web-applications.html
總結
以上是生活随笔為你收集整理的在基于Spring的Web应用程序中使用Http Session的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 旧电脑应如何升级电脑如何升级配置
- 下一篇: 如何使用JSR107缓存注释