CCC
CCC

Reputation: 2761

put resources in jar file and expose them to the web

  1. I got a web application, whose resources folder has a bunch of js and css files. How can I expose them to the web to be able to reference them in my web pages? And how are those files referenced?

  2. I also would like to later place those resources in a separate jar file and (like in the previous question) also expose them to the web. How can I do it using maven? I mean, package them so they can be in META-INF/resources.

Upvotes: 4

Views: 2950

Answers (1)

JB Nizet
JB Nizet

Reputation: 691835

Use a servlet-3.0 compliant container (Tomcat 7 and beyond, for example), and place your resources inside META-INF/resources in your jar file, and these files will be served by the container as if they were directly under the root of the application. The jar itself must be under WEB-INF/lib.

Maven doesn't have much to do with your question. If you want your resources to be served by the application, and not be in a jar file, you place them in src/main/webapp in the standard Maven directory layout.

If you want to build a jar file containing these resources, then this jar file should be built by another Maven project, and be one of the dependencies of the Maven war project. Inside the jar project, the resources will have to be under src/main/resources/META-INF/resources.

EDIT:

Suppose the file is named foo.png and is in the images folder under the root of the webapp, or under the META-INF/resources/images folder of a jar file, you reference it from inside a page of your app using a relative path or an absolute path. Suppose your app's context path is /myFirstApp. The address of the image will be /myFirstApp/images/png. Now suppse the URL of your page is /myFirstApp/bar/index.html, you can use

<img src="../images/foo.png" />

or

<img src="/myFirstApp/images/foo.png" />

An absolute path is much easier and safer to use, but you shouldn't hard-ce the context path of the application. So, inside a JSP, you would thus use

<img src="${pageContext.request.contextPath}/images/foo.png" />

or, using the JSTL:

<img src="<c:url value='/images/foo.png'/>" />

Upvotes: 6

Related Questions