在jsp当中引入静态资源还是很容易的,但是考虑到扩展性的问题,直接在jsp用路径引入静态资源不是很合理。可能实际部署时,静态资源是放在另外的主机的。所以基于这些情况考虑,我是这样处理的:
在web.xml文件中配置一个resourceRoot初始化参数,指明静态资源位置。如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<display-name>Archetype Created Web Application</display-name>
<!-- 不要在jsp当中写死这个resource,未来要是使用cdn就呵呵了 -->
<context-param>
<param-name>resourcesRoot</param-name>
<param-value>/path/to/resources/or/cdn/location</param-value>
</context-param>
</web-app>
在相应的jsp文件当中 通过${initParam.resourceRoot}来获取这个静态路径:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<c:set var="resourcesRoot" value="${initParam.resourcesRoot}" />
<title>search the events</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0,maximum-scale=1.0 user-scalable=no">
<link rel="shortcut icon" href="${resourcesRoot }/image/favicon.ico">
<script type="text/javascript" src="${resourcesRoot }/js/jquery.js"></script>
<script type="text/javascript" src="${resourcesRoot }/js/bootstrap.js"></script>
<link rel="Stylesheet" type="text/css" href="${resourcesRoot}/resources/css/bootstrap.css" />
</head>
将来要是需要更改静态资源的路径,相对来说就方便很多了。