24. Defining the Scope of Components, Controllers and Services

PROBLEM

The HTTP protocol is a stateless protocol, and session management is the technique for making the stateless HTTP protocol support session state. There needs to be a mechanisn for the developer to specify session managed data.

SOLUTION

A developer can specify the scope of a Component, Controller and Service to any scope supported by Spring, which includes session and request. Session will scope the Spring component to the request to the http session, and Request will scope the Spring component to the http request..

HOW IT WORKS

The scope of a component is specified in scope configuration in the Spring Configuration tab.

The following figures shows an abbreviated version of the code that is generated from a Component. To see the fully generated code, see the SkywayBlog sample project.

Example 2.26. Model Scope (Generated)

package skywayblog.web.blogcontroller.postmodel;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import skywayblog.domain.SkywayBlog;
import skywayblog.domain.dataservice.Post;

/**
 * PostModelImpl - Conversation - Provides access to all public and private variables.
 * 
 * @generated
 */
@Scope("session")1
public class PostModelImpl implements PostModel {

  // Constructors, Getters, Setters, Etc...
  ....

}   

1

The @Scope anottation is reconfigured based on the configured scope.

RELATED RECIPES

  1. Managing User Session Data