简体   繁体   中英

Spring MVC - Strange redirect after a POST request

Good morning all.

My Controller has this method to save into the DB

@RequestMapping(value = { path+"/new" } , method = RequestMethod.POST)
    public String saveLight(@Valid Luce luce, BindingResult result, ModelMap model, final RedirectAttributes redirectAttributes) {

        if (result.hasErrors()) {
            return path + "/luce";
        }
        // Add message to flash scope
        redirectAttributes.addFlashAttribute("css", "success");
        redirectAttributes.addFlashAttribute("msg", "Luce aggiunta correttamente");
        luceService.saveLuci(luce);
        return "redirect:/"+path+"/"+luce.getIdLuce();
        }

getIdLuce() is the getter of the model Luce. When i submit the form, the information is sent to the DB correctly, but I'm redirected to /lights/0 as luce.getIdLuce() return a 0 (or null) value...

I'm not saving an input value of the idLuce , it's a simple auto-increment value

@NotNull
@Id
@Column(name="id_luce", unique = true, nullable = false)
public Integer getIdLuce() {
    return idLuce;
}

What I'm doing wrong? Thanks

Annotate your entity object with @GeneratedValue . That way, the attribute 'idLuce' will be set when you persist your object.

@NotNull
@Id
@GeneratedValue
@Column(name="id_luce", unique = true, nullable = false)
public Integer getIdLuce() {
    return idLuce;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM