SpringBoot 页面资源小探
众里寻他千百度,蓦然回首,那人却在灯火阑珊处
视图,是Web开发最熟悉的小伙伴。最难过的时候,莫过于你觉得路径对了,但他隐身了。本文简单阐述springboot 的页面资源的理解,希望对你有帮助。
springboot的静态资源小探
springboot 默认的资源放在resources目录下。其中,static 常用于存放css,js,image等静态资源。templates 则存放视图文件(不能直接访问,同原始的WEB-INF下的jsp一致,需要再控制器做页面跳转)。
PS:springboot 默认使用的是thymeleaf 作为视图,不推荐使用JSP。
默认情况下直接访问的目录资源如下:
- classpath:/META-INF/resources/index.html
- classpath:/resources/index.html
- classpath:/static/index.html
- classpath:/public/index.html
SpringBoot与JSP的整合
虽然springBoot 不推荐使用JSP,但因为历史原因,开发者不得不使用JSP,以下简述整合步骤以及注意项。
1、pom.xml
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
<!--<scope>provided</scope>-->
</dependency>
2、application.properties(springboot 1.3及以下去掉mvc)
# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp
3、controller
@SpringBootApplication
@Controller
public class DemoApplication {
@RequestMapping("/test1")
public String test(){
return "test";
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4、在webapp/WEB-INF/jsp文件夹下创建test.jsp
5、点击点击运行,可能会发现
There was an unexpected error (type=Not Found, status=404).
/WEB-INF/jsp/test.jsp
如果当前模块是主模块则可以正常显示。如果是子模块则只能通过maven启动。
【IDEA点击右侧maven project ,找到module的plugins中的springboot-run,点击运行。】
参考文献
[1]: JavaEE开发的颠覆者
[2]: 刘忠旭`为什么整合jsp后必须通过spring-boot:run方式启动?