爲什麼把JS放在java包中?如果您將所有文件放在一個目錄中,例如/ ajaxloading /它應該工作。包中的Java資源放在WEB-INF \ classes中,你不能通過那裏的關聯url來尋找資源。
另一種可能性是編寫一個servlet,將所有文件形成一個包,然後將這個servlet映射到web.xml中的一個url小瓶servlet-mapping。
我也在項目中使用它。這裏的源:
public class StyleProviderServlet extends HttpServlet {
private static final long serialVersionUID = 7156462313946659366L;
/**
* read buffer.
*/
private static final int BUFFER_SIZE = 102400;
private final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(StyleProviderServlet.class);
/**
* Package
*/
private static final String PACKAGE = "com/mycompany/mypackage/style";
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.handleRequest(req, resp);
}
protected void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String pathInfo = req.getPathInfo();
logger.debug("pathInfo = {}", pathInfo);
StringBuilder resourcePathBuilder = new StringBuilder(100);
resourcePathBuilder.append("/");
resourcePathBuilder.append(PACKAGE);
resourcePathBuilder.append(pathInfo);
String resourcePath = resourcePathBuilder.toString();
logger.debug("resourcePath: {}", resourcePath);
InputStream inputStream = this.getClass().getResourceAsStream(resourcePath);
if (inputStream != null) {
String mimeType = getMimeType(pathInfo);
if (mimeType != null) {
resp.setContentType(mimeType);
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
try {
logger.debug("at least {} bytes are ready to be read", bufferedInputStream.available());
ServletOutputStream outputStream = resp.getOutputStream();
int index = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((index = bufferedInputStream.read(buffer)) != (-1)) {
outputStream.write(buffer, 0, index);
}
} finally {
bufferedInputStream.close();
}
} else {
logger.debug("no resource found for resourcePath '{}'", resourcePath);
}
}
protected String getMimeType(String pathinfo) {
if (pathinfo != null) {
ServletContext servletContext = getServletContext();
String mimeType = servletContext.getMimeType(pathinfo);
logger.debug("pathInfo :{}, mimeType={}", pathinfo, mimeType);
return mimeType;
} else {
return null;
}
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.handleRequest(req, resp);
}
}
而這裏的web.xml中的映射:
<servlet-mapping>
<servlet-name>StyleProviderServlet</servlet-name>
<url-pattern>/style/*</url-pattern>
</servlet-mapping>
現在你可以從包裝COM/myCompany中/ mypackage中/風格通過URL /風格/例如訪問所有文件/style/AjaxLoadingLink.css
你也可以把所有文件在JAR這種方式,並把這個JAR放到WEB-INF/lib目錄
什麼是Java的有,要怎麼辦? – jwueller 2011-05-27 07:21:07
用html將其重新標記。 – Jordan 2011-05-27 07:26:12