英文:
How can I target the root path in Spring controller?
问题
我正在尝试在我的Spring控制器中添加默认路径。
例如:我希望http://localhost:8080渲染与http://localhost:8080/index相同的视图。
我尝试了以下内容:
@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";
}
}
在http://localhost:8080/index上运行良好。但是,在http://localhost:8080上从未进入root函数。
所以我尝试了这个:
@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";
}
}
它产生了相同的结果。
英文:
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.
答案1
得分: 1
你可以将它统一为以下形式:
@RequestMapping(value = {"/", "/index"})
在Spring中,注解 @RequestMapping 可以接受多个值,将不同的URL映射到控制器的同一个方法。
希望它能够正常工作!
英文:
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论