有没有可能在一个Spring Boot应用程序中同时使用Controller和RestController注解?

huangapple go评论70阅读模式
英文:

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 = &quot;/api/&quot;)
public class PageRestController {
    @GetMapping(value = &quot;/getUserData&quot;)
    public ResponseEntity&lt;User&gt; getUser() {
        User user = new User();

        user.setName(&quot;Nika&quot;);
        user.setSurname(&quot;Beridze&quot;);
        user.setAge(19);

        return ResponseEntity.ok().body(user);
    }
}

Controller:

@Controller
public class PageController {
    @GetMapping(&quot;/index&quot;)
    public String index() {
        return &quot;index&quot;;
    }
}

答案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.

huangapple
  • 本文由 发表于 2023年3月4日 04:40:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631690.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定