之前有个一片文章介绍springmvc和springboot的静态资源文件处理方式,本文再根据一个示例彻底把springboot的静态资源文件使用方法介绍一下。
1、application.properties:
# 页面默认前缀目录 server.jsp-servlet.init-parameters.development=true spring.mvc.view.prefix=/page/ spring.mvc.view.suffix=.jsp
这里没有把jsp放到WEB-INF下(放到WEB-INF下会比较安全,无法通过浏览器直接访问jsp),主要是习惯原因在springmvc项目中我们经常直接把jsp放到webapp目录下。
2、controller:
@RequestMapping("/index") public String index(HttpServletRequest request) { logger.info("index"); return "index"; }
直接返回jsp页面。
3、自定义资源路径:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; @Configuration public class MyMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/img/**") .addResourceLocations("classpath:/imgs/"); super.addResourceHandlers(registry); } }
4、jsp:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>sprint-boot jsp</title> </head> <body> <font size=3 color=red>图片1:'<img alt="" src="1.png">' 请求url:http://localhost:8080/1.png,利用的是springboot默认静态资源路径classpath:/static</font><br/> <img alt="" src="1.png" height="200"><br> <font size=3 color=red>图片2:'<img alt="" src="../images/2.png">',请求url:http://localhost:8080/images/2.png,利用的是springboot在webapp下资源可以直接访问</font><br> <img alt="" src="../images/2.png" height="200"><br> <font size=3 color=red>图片3:'<img alt="" src="/img/3.png">',请求url:http://localhost:8080/img/3.png,利用的是springboot自定义资源位置(在classpath:/imgs)</font><br> <img alt="" src="/img/3.png" height="200"> </body> </html>
5、资源结构如下图:
6、访问:
在浏览器上输入http://localhost:8080/index 如下
我们可以看到favicon.ico和三种不同方式的图片资源引用方式。通过F12抓包,可以看到不同方式图片的请求url,根据url我们可以看到springboot是如何处理资源文件的。
其中favicon.ico的url是:http://localhost:8080/favicon.ico,使用的也是webapp目录下资源可以直接访问。