java - 带有Tomcat的Spring MVC不会打开Hello World html页面

标签 java spring spring-mvc tomcat

我正在尝试打开一个简单的 html 页面,该页面在 localhost:8080/hello 上写入 Hello world,但它位于 Spring MVC 应用程序中。我使用自带 tomcat 的 Spring Boot。

网络.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <display-name>Angular Rest Spring</display-name>

    <servlet>
        <servlet-name>angular</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>angular</servlet-name>
        <url-pattern>*</url-pattern>
    </servlet-mapping>
</web-app>

我试着把页面放在里面:

app/src/main/resources
app/src/main/resources/templates
web
web/WEB-INF

找不到。它说:

Whitelabel Error Page

This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Sep 07 15:52:20 EEST 2016
There was an unexpected error (type=Not Found, status=404).
No message available

有什么想法吗?

最佳答案

如果您使用的是 spring boot,则无需编写 web.xml。 Spring 自动映射所有带@Controller 注释的类并从中读取@RequestMapping 注释。

写一个应用类:

package com.sample.web;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication(scanBasePackages = "com.sample.web")
public class Application {

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

}

像这样写一个 Controller 类:

package com.sample.web;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class HelloController {

    @RequestMapping("/hello")
    public String hello(Model model) {
        return "hello";
    }

}

并在 src/main/resources/templates 中编写一个模板 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>
Hello
</body>
</html>

我使用 intellij,我可以在其中运行应用程序类,然后使问候页面在 http://localhost:8080/hello 上可用

关于java - 带有Tomcat的Spring MVC不会打开Hello World html页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39370927/

相关文章:

java - 在 Eclipse IDE 中获取无法突出显示或删除的奇怪符号

java - 交互式 JTable

java - "Less than or Equal to"与 "Less than"进行处理

java - 带有 spring 引导的 rabbitmq 中的异常

java - 没有可用的类型 [...] 的合格 Bean

java - map 的大小限制为 3 个元素

java - Spring 3.1 Web 应用程序问题

java - Spring Boot 中的 CORS 不起作用 - 得到空响应

java - Spring JPA异常翻译

java - 数据绑定(bind)到 Spring MVC 中的下拉框