Posts Tagged ‘mvc’

Posted by Tatyana at 6 February 2012

Category: Dev, Java

Tags: , , , , , , , ,

Controllers in Spring MVC are desined to be shared between requests. Each controller has a default singleton scope so if you are using controllers you neeed to be aware of that. The easiest way to make sure your controller is thread-safe is to not to have class variables. F.ex. this example from Spring MVC tutorial:

@Controller
@RequestMapping("/editPet.do")
public class EditPetForm {

    private final Clinic clinic;

    public EditPetForm(Clinic clinic) {
        this.clinic = clinic;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }

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

In this example we can have a serious issue regarding thread-safety: private variable clinic. If there will be a situation where to different requests access the controller simultaniously, one of them will instanciate the controller and begin to process a form, then the other one comes inn. The result from processing of the first request will be sent to the other one, thus the requests receive fail data or nothing.

The solution to the problem may be the following:
1. Annotate Controller with @Scope(“request”) or @Scope(“session”)
2. Move private variable into one of the methods or save it in session or model.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share

Posted by kent at 5 January 2009

Category: Ikke interessant

Tags: , ,

No shit, it’s real name is Magic Voodoo Controller.

There’s so much stuff going on behind the scenes and no clear connection between the Model, View and Controller. But it works, somehow.

VN:F [1.9.13_1145]
Rating: 0.0/5 (0 votes cast)
Share