在基于Spring的Web应用程序中拥有和使用Http会话有多种方法。 这是基于最近项目经验的总结。
方法1
只需在需要的HttpSession中注入即可。
@Service
public class ShoppingCartService {@Autowired private HttpSession 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