【问题标题】:Return HTML page with Spring Controller使用 Spring Controller 返回 HTML 页面
【发布时间】:2020-12-13 17:44:19
【问题描述】:

所以,显然,我正在尝试在 Spring 控制器的帮助下返回一个 HTML 文件。

我已经添加了 Thymeleaf 依赖,也尝试了以下方式进行配置:

1.

@RequestMapping ("/")
@ResponseBody
public String homeDisplay() {
    return "homepage";
}
@Controller
public class HomeController {

@RequestMapping ("/")
public ModelAndView index () {
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("homepage");
    return modelAndView;
}
}

无论如何,没有帮助,我得到了 Whitelabel 错误页面。

白标错误页面 此应用程序没有显式映射 /error,因此您将其视为后备。 2020 年 12 月 13 日星期日 20:14:04 EET 出现意外错误(类型=未找到,状态=404)。 没有可用的消息

如何修复它并显示我需要的 HTML。

【问题讨论】:

  • 问题到底是什么?
  • 问题是——如何解决问题并显示我需要的html文件。
  • 欢迎来到 SO。尽量提供尽可能多的相关信息。您的项目中可能存在许多问题。在SO这里没有魔法。 :-) 在这种情况下显示您的项目结构。一个图像可能是。!同时显示你的 pom/gradle。

标签: javascript java html spring


【解决方案1】:

尝试将@RequestMapping 替换为@GetMapping("/")@RequestMapping(value = "/", method = RequestMethod.GET)

为什么?因为@RequestMapping 将映射到对该 URL 的任何请求,所以你必须指定它是一个 GET 请求(我想这就是你想要使用的)。

由于您没有共享发送请求的前端代码,我们无法判断那里是否存在问题。也请分享一下。

【讨论】:

    【解决方案2】:

    在尝试让主页显示我正在制作的 REST API 时,我遇到了类似的问题。该项目虽然没有 Thymeleaf。我使用了以下内容,这对我有用。以下代码使 home.html 文件存储在 resources/static 中,以便在应用程序启动时显示。这是一个静态页面,没有数据发送给它。

    @Controller
    public class HomeController {
    
        @RequestMapping("/")
        public String welcome() throws Exception {
            return "home.html"; //note that this says .html
        }
    }
    

    对于我使用 Thymeleaf 的项目,我有以下代码,它显示了存储在资源/模板文件夹中的登录页面。

    @Controller
    public class LoginController {
    
        @GetMapping("/login")
        public String showLoginForm() {
            return "login"; //note that this is just the name of the file with no extension
        }
    }
    

    请务必将 html 文件放在正确的文件夹中。我的猜测是,由于您使用的是 Thymeleaf,您可能会使用一些模板。

    【讨论】:

      猜你喜欢
      • 2020-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-01
      相关资源
      最近更新 更多