Where to place images/CSS in spring-mvc app?

2020-01-30 12:12发布

问题:

I used Netbeans to create a Spring MVC 3.0 app. I have a simple controller and JSP view. The JSP view appears correctly except for an image that doesn't render. My directory structure looks like this:

In my Home.jsp page, the image that doesn't render is referenced like so:

<img src="Images/face.png" />

I've verified that face.png is in the Images directory. So why doesn't it appear in the browser? In Spring MVC, where should I place files referenced by JSP views, like images, CSS, JS, etc?

回答1:

Alter your web.xml file:

<servlet>
    <servlet-name>spring-servlet</servlet-name>
    <servlet-class>com.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>spring-servlet</servlet-name>
    <url-pattern>/<url-pattern>
</servlet-mapping>

and add below configuration after it:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.css</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.js</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.gif</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.jpg</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>*.png</url-pattern>
</servlet-mapping>

If you have a better solution please share with me.



回答2:

I was able to find a workable answer here: How to handle static content in Spring MVC?

The problem was that my spring mvc dispatcher servlet was intercepting the calls to static resources. So I mapped Tomcat's default servlet to handle the static resources.



回答3:

anything under Web-Inf folder will be marked as private and can not be access by the browser. You suppose to move the image folder outside Web-Inf and under webapp.



回答4:

For set image in jsp file in Spring MVC framework :

You can simply set your image by following steps:

Step 1. Place images folder in resources

Step 2. write image path like : src="${pageContext.request.contextPath}/resources/images/logo.jpg"



回答5:

I believe it can only reference images/css in the WEB-INF folder. Moving your Images folder to WEB-INF should fix your problem.



回答6:

I think you can put all the static data such as image, css, javascripts etc out side the WEB-INF and then call it the normal way :)



回答7:

A bit old, but let me add my bit here. It is generally preferred to hide the .css/ .js files from direct public access by placing them into the main/java/webapp folder instead of the WEB-INF.

The reasons are explained very well in the posts below:

  • What is WEB-INF used for in a Java web application?
  • How to access css/js files in jsps, all of them are placed in WEB-INF?? (spring forum)


标签: spring-mvc