Scenario: Whenever an user enters your site, he is asked to pick a theme to use when navigating your site.
Solution: Store user's selection using Spring Session scoped bean
1. Annotate your bean
@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class UserSelection{
private String selectedTheme;
//and other session values
public void setSelectedTheme(String theme){
this.selectedTheme=selectedTheme;
}
public String getSelectedTheme(){
return this.selectedTheme;
}
}
2. Inject your session scoped bean
@Controller
@RequestMapping("/")
public class SomeController{
private UserSelection userSelection;
@Resource
public void setUserSelection(UserSelectio userSelection){
this.userSelection=userSelection;
}
@RequestMapping("saveThemeChoice")
public void saveThemeChoice(@RequestParam String selectedTheme){
userSelection.setSelectedTheme(selectedTheme);
}
public String doOperationBasedOnTheme(){
String theme=userSelection.selectedTheme();
//operation codes
}
}
In above code snippet, Although 'SomeController' has scope of singleton(default scope of Spring bean), each session will have its own instance of UserSelection. Spring will make the judgement, and inject a new instance of UserSelection if the request is a new session.
Required jars
Besides spring library, aopalliance and cglib jar are also required
http://mvnrepository.com/artifact/cglib/cglib-nodep
http://mvnrepository.com/artifact/aopalliance/aopalliance