DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Migrating Spring Java Applications to Azure App Service (Part 1: DataSources and Credentials)
  • How To Build Web Service Using Spring Boot 2.x
  • Authentication With Remote LDAP Server in Spring Web MVC

Trending

  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • How to Ensure Cross-Time Zone Data Integrity and Consistency in Global Data Pipelines
  1. DZone
  2. Coding
  3. Frameworks
  4. Using Http Session With Spring Based Web Applications

Using Http Session With Spring Based Web Applications

By 
Biju Kunjummen user avatar
Biju Kunjummen
·
Apr. 29, 14 · Interview
Likes (1)
Comment
Save
Tweet
Share
142.5K Views

Join the DZone community and get the full member experience.

Join For Free

There are multiple ways to get hold of and use an Http session with a Spring based web application. This is a summarization based on an experience with a recent project.

Approach 1

Just inject in HttpSession where it is required.

@Service
public class ShoppingCartService {

 @Autowired 
 private HttpSession httpSession;

 ...
} 

Though surprising, since the service above is a singleton, this works well. Spring intelligently injects in a proxy to the actual HttpSession and this proxy knows how to internally delegate to the right session for the request.

The catch with handling session this way though is that the object being retrieved and saved back in the session will have to be managed by the user:

public void removeFromCart(long productId) {
 ShoppingCart shoppingCart = getShoppingCartInSession();
 shoppingCart.removeItemFromCart(productId);
 updateCartInSession(shoppingCart);
}


Approach 2

Accept it as a parameter, this will work only in the web tier though:

@Controller
public class ShoppingCartController {

  @RequestMapping("/addToCart")
  public String addToCart(long productId, HttpSession httpSession) {
    //do something with the httpSession 
  }

}


Approach 3
Create a bean and scope it to the session this way:


@Component
@Scope(proxyMode=ScopedProxyMode.TARGET_CLASS, value="session")
public class ShoppingCart implements Serializable{
...
}


Spring creates a proxy for a session scoped bean and makes the proxy available to services which inject in this bean. An advantage of using this approach is that any state changes on this bean are handled by Spring, it would take care of retrieving this bean from the session and propagating any changes to the bean back to the session. Further if the bean were to have any Spring lifecycle methods(say @PostConstruct or @PreDestroy annotated methods), they would get called appropriately.

Approach 4
Annotating Spring MVC model attributes with @SessionAttribute annotation:

@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();
 } 

}


The use case for using SessionAttributes annotation is very specific, to hold state during a flow like above


Given these approaches, I personally prefer Approach 3 of using session scoped beans, this way depending on Spring to manage the underlying details of retrieving and storing the object into session. Other approaches have value though based on the scenario that you may be faced with, ranging from requiring more control over raw Http Sessions to needing to handle temporary state like in Approach 4 above.

Spring Framework Session (web analytics) application Web Service

Published at DZone with permission of Biju Kunjummen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enterprise RIA With Spring 3, Flex 4 and GraniteDS
  • Migrating Spring Java Applications to Azure App Service (Part 1: DataSources and Credentials)
  • How To Build Web Service Using Spring Boot 2.x
  • Authentication With Remote LDAP Server in Spring Web MVC

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: