【问题标题】:RequestMapping results in 404 - Spring BootRequestMapping 结果为 404 - Spring Boot
【发布时间】:2015-11-10 09:57:54
【问题描述】:

我是 Spring Boot 的新手。在以下简单代码中,当我使用@RequestMapping 时,http://localhost:8080/person 会导致以下错误:

错误:

There was an unexpected error (type=Not Found, status=404).

代码:

@Configuration
@EnableAutoConfiguration
@ComponentScan
@Controller
public class SpringBootAlphaApplication {

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


    @RequestMapping("/person")
    public String  addPerson(Model model){
        Person person = new Person();
        person.setName("SomeName");
        person.setAge(28);
        model.addAttribute("person", person);
        return "personview";

    }

    @RequestMapping("/")
    public String testPath(){
        return "Test URL";
    }

}

【问题讨论】:

  • 您要返回什么?你要返回html还是json?
  • @ksokol addPerson 将返回 html,但 testPath 方法应该返回一个简单的字符串,但找不到资源。需要注意的一点是,如果我将 ResponseBody 与 RequestMapping 一起使用,则会返回它
  • 您想使用什么模板引擎? JSP、Freemarker、Velocity、Thymleaf?

标签: spring web-applications spring-boot http-status-code-404


【解决方案1】:

考虑到您的答案,那么您实际上应该得到另一个错误。如果您使用 spring-boot-starter-thymeleaf,如果您的视图可以解决(但不包含 </meta> 标签),您将得到的错误应该是:

org.xml.sax.SAXParseException: The element type "meta" must be terminated by the matching end-tag "</meta>".

您应该获得type=Internal Server Error, status=500 状态。

为了解决你实际上可以通过将其模式设置为LEGACYHTML来配置Thymeleaf的严格性:

spring.thymeleaf.mode=LEGACYHTML5

但是,它需要您添加另一个名为 nekohtml 的依赖项:

<dependency>
  <groupId>net.sourceforge.nekohtml</groupId>
  <artifactId>nekohtml</artifactId>
  <version>1.9.15</version>
</dependency>

未找到的错误通常意味着别的:

  • 您的视图无法解析:可能是您拼错了 HTML 的名称,或者您没有将它放在正确的文件夹中
  • 您的请求映射无法解析:可能是您拼错了名称,或者您使用了错误的上下文路径
  • 您没有用于解析视图的模板引擎

【讨论】:

    【解决方案2】:

    这是由&lt;meta&gt; 没有结束标签&lt;/meta&gt; 引起的。显然 Thymleaf 对标签非常严格,希望返回更有意义的消息而不是 404 Not Found。

    【讨论】:

    • 它实际上确实为您提供了更有意义的信息。
    猜你喜欢
    • 1970-01-01
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-29
    相关资源
    最近更新 更多