使用@Controller在Spring-MVC 2.5编辑表单中的ID

时间:2012-01-31 10:52:30

标签: spring jpa controller annotations edit

我的控制器代码有问题。 GET 工作正常(从db填充的空表单+表单), POST 仅适用于创建新对象,但不适用于的编辑即可。 @Controller类的一部分:

    @RequestMapping(value = "/vehicle_save.html", method = RequestMethod.GET)
public String setUpForm(@RequestParam(value="id", required = false) Long id, ModelMap model) {
    Vehicle v;
    if (id == null) {
        v =  new Vehicle();
    } else {
        v = vehicleManager.findVehicle(id);
    }
    model.addAttribute("vehicle", v);
    return "vehicle_save";
}

@RequestMapping(value = "/vehicle_save.html", method = RequestMethod.POST)
public String save(@ModelAttribute("vehicle") Vehicle vehicle, BindingResult result, SessionStatus status) {
    vehicleValidator.validate(vehicle, result);
    if (result.hasErrors()) {
        return "vehicle_save";
    } 
    if(vehicle.getId() == null) {
        vehicleManager.createVehicle(vehicle);  
    } else {
        vehicleManager.updateVehicle(vehicle);  
    }
    status.setComplete();
    return "redirect:vehicle_list.html";
}

第一种方法是创建车辆对象(包括 ID )。但是第二种方法在没有 ID 字段(设置为null)的情况下获得相同的对象。

我该怎么做:手动设置vehicle.setID(参数中的id),然后将其保存到数据库。这会导致JPAOptimisticLockException +我不喜欢这个解决方案。

有没有办法将我的Vehicle对象 ID 传递给第二种方法?顺便说一句,我想避免在JSP中添加隐藏的ID字段。

3 个答案:

答案 0 :(得分:2)

您建议的示例是使用会话来存储值。 @SessionAttribute是将现有模型对象绑定到会话。查看类使用@SessionAttributes("pet")注释的源代码。这意味着名为“pet”的模型属性将存储在session中。另外,请查看EditPetForm类的processSubmit方法中的代码

    @RequestMapping(method = { RequestMethod.PUT, RequestMethod.POST })
    public String processSubmit(@ModelAttribute("pet") Pet pet, BindingResult result, SessionStatus status) {
        new PetValidator().validate(pet, result);
        if (result.hasErrors()) {
            return "pets/form";
        }
        else {
            this.clinic.storePet(pet);
            status.setComplete(); //look at its documentation
            return "redirect:/owners/" + pet.getOwner().getId();
        }
    }

我之前曾经使用过这样的东西。但是我想把你的id放在会话中就是这样

答案 1 :(得分:1)

  

顺便说一句,我想避免在JSP中添加隐藏的ID字段。

这是常见的解决方案。它出什么问题了 ?您应该使用id创建隐藏输入。

答案 2 :(得分:0)

可能您可以尝试使用会话,因为您无法在两个请求之间存储信息。但我想这会更加丑陋。 顺便问一下,你能解释一下为什么要避免添加隐藏字段吗?我有点好奇