英文:
Is there any possible way to use Controller and RestController annotations in one Spring Boot application?
问题
我有我的应用程序,它运行在Spring Boot上。在我的应用程序中,我有两个控制器,@RestController和@Controller。
Rest用于返回JSON数据,Controller用于HTML页面。当我尝试在一个项目中使用这两个控制器时,它总是给我一个错误代码:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [index]: would dispatch back to the current handler URL [/index] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause
我的HTML页面位于resources:/templates。
RequestMappingClass:
@RestController
@RequestMapping(value = "/api/")
public class PageRestController {
@GetMapping(value = "/getUserData")
public ResponseEntity<User> getUser() {
User user = new User();
user.setName("Nika");
user.setSurname("Beridze");
user.setAge(19);
return ResponseEntity.ok().body(user);
}
}
Controller:
@Controller
public class PageController {
@GetMapping("/index")
public String index() {
return "index";
}
}
英文:
I have my application, which is running on Spring Boot. In my application, I have two controllers, @RestController and @Controller. <br>
Rest is for returning JSON data and Controller is for HTML pages. When I try to use these two boys in my one project, it always gives me an error code: <br>
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Circular view path [index]: would dispatch back to the current handler URL [/index] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)] with root cause <br>
My HTML page is located in resources:/templates. <br>
RequestMappingClass:
@RestController
@RequestMapping(value = "/api/")
public class PageRestController {
@GetMapping(value = "/getUserData")
public ResponseEntity<User> getUser() {
User user = new User();
user.setName("Nika");
user.setSurname("Beridze");
user.setAge(19);
return ResponseEntity.ok().body(user);
}
}
Controller:
@Controller
public class PageController {
@GetMapping("/index")
public String index() {
return "index";
}
}
答案1
得分: 1
添加spring-boot-starter-thymeleaf
依赖。这将自动为src/main/resources/templates
中的HTML文件注册一个视图解析器。
英文:
Add the spring-boot-starter-thymeleaf
dependency. This automatically registers a view resolver for HTML files in src/main/resources/templates.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论