request.getSession().setAttribute("sessionvar", "session value");
@SessionAttributes("sessionvar")
How do these methods differ? Which is the appropriate way to create a session variable?
Both
request.getSession().setAttribute("sessionvar", "session value");
@SessionAttributes("sessionvar")
are used to store values in session . But there are differences.
1.) @SessionAttributes annotation
@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
// ...
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(
@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}
else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId=" + pet.getOwner().getId();
}
}
}
The type-level @SessionAttributes annotation declares session attributes used by a specific handler. This will typically list the names of model attributes which should be transparently stored in the session or some conversational storage, serving as form-backing beans between subsequent requests.Reference
2.)request.getSession().setAttribute("sessionvar", "session value");
request.getSession() returns HttpSession object
then
setAttribute("sessionvar", "session value");
You are manually forcing HttpSession to hold value With a key.