I tried to find on how to redirect the link from the controller of Spring MVC but I only found the solution if the link doesn't have PathVariable.
This is my controller
@RequestMapping(value="dokter/update/{idDokter}", method = RequestMethod.POST)
public String changeDokterFormSubmit(@PathVariable Long idDokter, @ModelAttribute DokterModel dokter, Model model, HttpServletRequest request) throws Exception{
System.err.println(request.getParameter("Tanggal lahir"));
DateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
Date date = sdf.parse(request.getParameter("Tanggal lahir"));
dokter.setTanggalLahir(date);
System.err.println(dokter.getTempatLahir());
dokter.setNik(dokter.getNik());
DokterModel newDokterData = dokterService.changeDokter(dokter);
model.addAttribute("dokter", newDokterData);
return "redirect:'/dokter/view/'+${newDokterData.getNik()}";
}
where this is the method that I want to reach.
@RequestMapping("/dokter/view/{nikDokter}")
private String detilDokter(
@PathVariable String nikDokter,
Model model
){
DokterModel dokter = dokterService.getDokterByNik(nikDokter).get();
Boolean gender = dokter.getJenisKelamin();
String result = "Laki-laki";
if(gender){
result = "Perempuan";
}
model.addAttribute("dokter", dokter);
model.addAttribute("gender", result);
model.addAttribute("spesialis", spesialisService);
return "detil-dokter";
}
When i tried that, i got this error
java.lang.IllegalArgumentException: Model has no value for key 'newDokterData.getNik()'
But the POST itself actually works, as the data itself changed perfectly fine. How should I approach this problem?
BONUS
For future reference if my detilDokter method is like this.
@RequestMapping("/dokter")
private String detilDokter(
@RequestParam String nikDokter,
Model model
){
DokterModel dokter = dokterService.getDokterByNik(nikDokter).get();
Boolean gender = dokter.getJenisKelamin();
String result = "Laki-laki";
if(gender){
result = "Perempuan";
}
model.addAttribute("dokter", dokter);
model.addAttribute("gender", result);
model.addAttribute("spesialis", spesialisService);
return "detil-dokter";
}
How does the redirect should look like in changeDokterFormSubmit?
return "redirect:'/dokter/view/'+${dokter.getNik()}";- since that is the attribute name you getnewDokterDatain your model ...