This application has no explicit mapping for /error, so you are seeing this as a fallback
最近在整合Springboot,刚入手就卡到了404,先说一下问题背景,我controller可以正常访问
@Controller
public class HelloController {
@RequestMapping("/")
public String getHello() {
return "index";
}
}
访问项目浏览器会打印index,但是我访问login.html会直接404 代码如下,刚开始还是以为form表单提交URL有问题,直接body打印"hello,spingboot"还是404
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
hello,spingboot
</body>
</html>
There was an unexpected error (type=Not Found, status=404).如下图所示
然后广大网友的建议有如下三条:
出现这个异常说明了跳转页面的url无对应的值.
-
原因1:
Application启动类的位置不对.要将Application类放在最外侧,即包含所有子包
原因:spring-boot会自动加载启动类所在包下及其子包下的所有组件. -
原因2:
在springboot的配置文件:application.yml或application.properties中关于视图解析器的配置问题:
当pom文件下的spring-boot-starter-paren版本高时使用:
spring.mvc.view.prefix/spring.mvc.view.suffix
当pom文件下的spring-boot-starter-paren版本低时使用:
spring.view.prefix/spring.view.suffix -
原因3:
控制器的URL路径书写问题
@RequestMapping(“xxxxxxxxxxxxxx”)
实际访问的路径与”xxx”不符合.
但是我全试了一遍并不能解决这个问题,最后贴一下我的解决办法。
Springboot中直接访问htmlSpringboot中直接访问html时
application.properties添加如下配置:
- 定位模板的目录
spring.mvc.view.prefix=classpath:/templates/ - 给返回的页面添加后缀名
spring.mvc.view.suffix=.html
controller返回页面:
@GetMapping("/index")
public String index(){
return "home";
//当浏览器输入/index时,会返回 /templates/home.html页面
}
注意:
spring boot默认开启了静态文件的配置,任何放在static文件夹下的资源都是静态文件。引用静态文件时以/或者前缀不加任何定位符,都会去static文件夹下查找。
Thymeleaf模版默认会使用templatess作为视图文件下