【问题标题】:Why is it mandatory to have separate @Controller class file for web-application in spring-boot?为什么必须在 spring-boot 中为 web 应用程序提供单独的 @Controller 类文件?
【发布时间】:2020-03-06 02:23:51
【问题描述】:

在 Thymeleaf 中,触发 index.html 页面(存在于资源的模板文件夹中)在应用程序的 Main 类中提供新的 @RequestMapping 方法不起作用(输出字符串而不是呈现 HTML 页面),而是创建一个单独的具有相同 @RequestMapping 方法的 @Controller 类正在触发所需的 UI。

方法一

Main类中的@RequestMapping方法

package com.personal.boot.spring.helloworld;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class HelloworldApplication {

    public static void main(String[] args) {
        SpringApplication.run(HelloworldApplication.class, args);
    }

    @RequestMapping(value = "/index")
    public String index() {
        return "index";
    }

}

现在,对 /index 的 get 请求将“index”输出为字符串

方法二

单独的@Controller 类中的@RequestMapping 方法

package com.personal.boot.spring.helloworld.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class WebController {
   @RequestMapping(value = "/index")
   public String index() {
      return "index";
   }
}

现在,对 /index 的 get 请求会在模板文件夹中呈现 index.html 页面。

为什么会这样?请帮忙。

【问题讨论】:

  • 尝试用@Controller而不是@RestController注释HelloworldApplication
  • @caco3 有效。你能详细说明一下吗? @RestController 确实包含@Controller 的功能对吧?
  • 我发现这个链接解释了差异。不过谢谢你。link
  • 没问题。您可能还想查看Spring MVC documentation。来自链接:“@RestController 是一个组合注解,它本身使用@Controller 和@ResponseBody 进行元注解,以指示一个控制器,其每个方法都继承了类型级别的@ResponseBody 注解,因此,直接写入响应正文与视图分辨率以及使用 HTML 模板进行渲染"

标签: java spring-boot web-applications


【解决方案1】:

这里的答案是@RestController 还包含@ResponseBody 注解,它强制spring 显式转换返回的参数

【讨论】:

    【解决方案2】:

    @Controller 是 @Component 注解的特化,与 spring mvc 相同。而@RestController 是用于支持 REST 服务的 @Controller 注释的特化。它实际上是一个使用 @Controller 和 @ResponseBody 注释的便利控制器。

    https://www.javacodegeeks.com/2017/08/difference-restcontroller-controller-annotation-spring-mvc-rest.html

    【讨论】:

      猜你喜欢
      • 2020-09-15
      • 2010-10-20
      • 1970-01-01
      • 1970-01-01
      • 2020-10-12
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多