【问题标题】:Tomcat can't find Spring controllerTomcat 找不到 Spring 控制器
【发布时间】:2016-10-16 14:29:41
【问题描述】:

我正在尝试使用 SpringMVC 设置一个非常小的测试项目。 我已经设法让它运行在目标文件夹中创建的 jar 文件,如this tutorial 中所述。但是,我无法通过 IntelliJ IDEA 配置部署 war 文件。

应用:

@SpringBootApplication
public class Application {        
    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

你好控制器

@Controller
public class HelloController {
    @RequestMapping("/greeting")
    public String greeting(final Model model) {
        model.addAttribute("name", "bla");
        return "greeting";
    }
}

greeting.html

<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Getting Started: Serving Web Content</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</head>
<body>
    <p th:text="'Hello, ' + ${name} + '!'"/>
</body>
</html>

运行配置:

神器:

结构和目标输出

我在访问“localhost:8080/greeting”时收到 404。

如果有人能指出我做错了什么,我会很高兴。

【问题讨论】:

  • 您是否关注过the instructions 创建可部署的war 文件?
  • 你试过 localhost:8080/testwebapp/greeting 吗?
  • Spring Boot 应用程序通常不构建为 WAR 文件,而是构建为独立的 JAR 文件。是否有特殊原因使您从中制作 WAR 文件,或者您只是不知道您通常不会从 Spring Boot 应用程序中制作 WAR?

标签: java spring tomcat intellij-idea spring-boot


【解决方案1】:

按照this comment 的建议,我查看了these instructions。我在 Application.java 中遗漏了一些东西,即:

public class Application extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

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

【讨论】:

    【解决方案2】:

    我可以看到您将 Spring 作为独立应用程序启动

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

    Tomcat 仅适用于 servlet 应用程序。像往常一样启动你的 spring 应用程序控制台应用程序(在 main() 方法中的 Idea 中右键单击并选择“运行”菜单项)。 然后在浏览器中请求http://localhost:8080/greeting

    spring-boot example

    您根本不需要 IDEA 中的工件来启动应用程序。

    因此,如果您想在 Tomcat 等 servlet 容器中将 Spring boot 作为 war 运行,请阅读 this doc

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多