Spring Boot 默认将 /webjars/** 映射到 classpath:/META-INF/resources/webjars/ ,结合我们上面讲到的访问资源的规则,便可以得知我们在JSP页面中引入jquery.js的方法为:
想实现这样,我们只需要在pom.xml 文件中添加jquery的webjars 依赖即可,如下:
org.webjars
jquery
2.1.4
但是我们实际开发中,可能会遇到升级版本号的情况,如果我们有100多个页面,几乎每个页面上都有按上面引入jquery.js 那么我们要把版本号更换为3.0.0,一个一个替换显然不是最好的办法。
如何来解决?按如下方法处理即可。
首先在pom.xml 中添加依赖:
org.webjars
webjars-locator
然后增加一个WebJarsController:
package org.springboot.sample.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerMapping;
import org.webjars.WebJarAssetLocator;
/**
* 处理WebJars,自动读取版本号
*
* @author 单红宇(365384722)
* @myblog https://blog.csdn.net/catoop/
* @create 2016年1月8日
*/
@Controller
public class WebJarsController {
private final WebJarAssetLocator assetLocator = new WebJarAssetLocator();
@ResponseBody
@RequestMapping("/webjarslocator/{webjar}/**")
public ResponseEntitylocateWebjarAsset(@PathVariable String webjar, HttpServletRequest request) {
try {
String mvcPrefix = "/webjarslocator/" + webjar + "/"; // This prefix must match the mapping path!
String mvcPath = (String) request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
String fullPath = assetLocator.getFullPath(webjar, mvcPath.substring(mvcPrefix.length()));
return new ResponseEntity<>(new ClassPathResource(fullPath), HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
}
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/jisuanjixue/article-62262-4.html