Wednesday, July 10, 2013

How to create a session variable in Spring MVC 3

  1. request.getSession().setAttribute("sessionvar", "session value");
  2. @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.

Is java Purely Object Oriented



We are saying that java is not purely object oriented since primitive data types are not objects.


See the below code:

how object is holding primitive data type?


public class Test{

public Object meth(Object obj){
        System.out.println(obj instanceof Object);//It prints true
        System.out.println("Value = "+obj);//It prints "Value = 1"
        return obj;
}


public static void main(String[] args) {
    int a = 1;
    System.out.println(new Test().meth(a));
}
}
It's called autoboxing. Basically, the Java compiler converts primitive data types into objects for you when you use them in a context that requires them to be objects.
int are wrapped in a Integer Object.
Conclusion:-
Java is not purely object oriented.

SpringMVC : Read property values from jsp

Spring config

 <util:properties id="propertyConfigurer" 
                      location="classpath:yourPropertyFileClasspathHere "/>
<context:property-placeholder properties-ref="propertyConfigurer" />

jsp

    <spring:eval expression="@propertyConfigurer.getProperty('propertyNameHere')" />