Warm tip: This article is reproduced from stackoverflow.com, please click
java redirect spring-mvc

RedirectView from Spring MVC dont works

发布于 2020-04-11 22:00:06

I think the fault comes from ulr introduced in the RedirectView parameter, but I tried different URL's and I can't make it work.

This is my project estructure:

Project Structure

And this is the get method from Spring MVC in controller package

@GetMapping("/planetForm")
@ResponseBody
public RedirectView toPlanetForm(Model model, @RequestParam(value = "idPlanet", required = false) String idPlanet) {
    if (idPlanet != null){
        Planet planet = planetService.getById(Integer.parseInt(idPlanet));
        model.addAttribute("planet", planet);
    }
    List<Satellite> satellites = satelliteService.findAll();
    model.addAttribute("satellites", satellites);
    return new RedirectView("./addPlanet");
}

As you can see I am trying to do the RedirectView to the JSP called addPlanet.jsp. I have also tried this url (among others): "../webapp/WEB-INF/jsp/addPlanet.jsp", I am convinced that it is a rookie nonsense, but I am unable to see the error

I have also tried to create another servlet and retrieve the object I need through the @ModelAtribute, but the object added in the first servlet is lost in the process, this is the code:

@GetMapping("/updatePlanet")
@ResponseBody
String update(Model model, @ModelAttribute("planet") Planet planet){
    model.addAttribute("planet",planet);
    return "addPlanet";
}

This wat sends the user to the addPlanet.jstl, but the object obtained by this method is an object just created by the constructor with attributes with the value of null or 0

Questioner
J.Doe
Viewed
49
J.Doe 2020-02-02 08:28

Finally I found the solution, here it is:

@GetMapping("/planetForm/{idPlanet}")
public String toPlanetForm(Model model, @PathVariable(value = "idPlanet", required = false) String idPlanet) {
    if (idPlanet != null){
        Planet planet = planetService.getById(Integer.parseInt(idPlanet));
        model.addAttribute("planet", planet);
    }
    List<Satellite> satellites = satelliteService.findAll();
    model.addAttribute("satellites", satellites);
    return "addPlanet";
}

As you can see I had to change the @GetMapping for a new URL, now the function returns a String which is the name of the JSP without extension. In addition to the parameter of the function @RequestParam I have had to change it to@PathVariable, which its value is the same as the mustache expression of @GetMapping