3

I am trying to add a default path in my Spring controller.
For example: I would like http://localhost:8080 to render the same view as http://localhost:8080/index

I tried that:

@Controller
@RequestMapping("/")
public class RecipeController {

    @Autowired
    private RecipeService service;

    @RequestMapping // http://localhost:8080
    public String root(Model model) {
        List<Recipe> recipes = service.fetchAll();
        model.addAttribute("recipes", recipes);
        return "index";
    }

    @GetMapping(value = {"/index"}) // http://localhost:8080/index
    public String index(Model model) {
        List<Recipe> recipes = service.fetchAll();
        model.addAttribute("recipes", recipes);
        return "index";
    }

}

It is working fine on http://localhost:8080/index.
However, it never enters the root function on http://localhost:8080.

So I tried that:

@Controller
public class RecipeController {

    @Autowired
    private RecipeService service;

    @RequestMapping("/") // http://localhost:8080
    public String root(Model model) {
        List<Recipe> recipes = service.fetchAll();
        model.addAttribute("recipes", recipes);
        return "index";
    }

    @GetMapping(value = {"/index"}) // http://localhost:8080/index
    public String index(Model model) {
        List<Recipe> recipes = service.fetchAll();
        model.addAttribute("recipes", recipes);
        return "index";
    }

}

It gives the same result.

Malouette
  • 33
  • 5

1 Answers1

1

You could unify this as follows:

@RequestMapping(value = {"/", "/index"})

In Spring, the annotation @RequestMapping can receive multiple values to map different URLs to the same method of a controller.

Hope it works!