一、SpringBoot 静态资源访问
在我们开发 Web 应用的时候,需要引用大量的 js、css、图片等静态资源,在 Spring Boot 中默认提供静态资源访问目录位置需置于classpath下,目录名需符合如下规则:
#支持1.5版本,2.0版本
/static
#支持1.5版本,2.0版本
/public
#支持1.5版本,2.0版本
/resources
#支持1.5版本,2.0版本
/META-INF/resources
例如:我们可在资源目录 src/main/resources
下创建 static
目录,在该位置放置一个图片文件。启动程序后,尝试访问http://localhost:8080/xxx.jpg。如能显示图片,配置成功。
在这里,我们将touxiang.jpg
图片放到 src/main/resources/static
目录,然后启动项目,访问http://localhost:8080/touxiang.jpg
,
注意:在static 下可以建各种目录,例如 js,css,images 目录,然后访问其下的静态资源路径分别为http://localhost:8080/js/xxx.js
,http://localhost:8080/css/xxx.css
,http://localhost:8080/images/xxx.jpg
。
二、SpringBoot JSP页面渲染
1. pom.xml 文件中添加
<!-- spring-boot-starter-parent 整合第三方常用框架依赖信息 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.0.RELEASE</version>
</parent>
<dependencies>
<!-- spring-boot-starter-web 是Springboot整合SpringMVC Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- SpringBoot 外部tomcat支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>
</dependencies>
2. 配置 application.properties
在 application.properties
文件中添加配置
spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp
3. 编写 Controller
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
* @Description JSP 渲染
* @author 欧阳
* @since 2019年4月7日 下午5:11:05
* @version V1.0
*/
@Controller
public class RenderJsp {
@RequestMapping("/renderJsp")
public ModelAndView renderJsp() {
ModelAndView modelAndView = new ModelAndView("home");
modelAndView.addObject("msg", "渲染jsp页面");
return modelAndView;
}
}
注意:Controller 要用注解 @Controller
,不然就返回 ModelAndView
对象。
4. 编写 JSP
JSP 路径为 /springboot-demo/src/main/webapp/WEB-INF/jsp/home.jsp
,因为在配置文件application.properties
中 我们配置的路径前缀就是/WEB-INF/jsp/
,所以需要在 /WEB-INF/jsp/
目录下创建名称为 home.jsp
的 Jsp 页面。关键代码:
<body>
信息:${msg }
</body>
5. 测试
(1)访问地址:http://localhost:8080/renderJsp
(2)效果: