在Maven項目,首先,你必須添加
<mvc:resources mapping="/resources/**" location="/resources/" />
或
<resources mapping="/resources/**" location="/resources/" />
到你的servlet-config.xml文件(它是我的項目中的spring-servlet.xml)。
然後,構建一個文件夾「資源」,如果它不存在於src/main/webapp下。 將包含CSS文件的CSS文件夾,包含圖像文件的圖像文件夾放在文件夾資源下。
現在你可以從JSP文件訪問的資源文件夾下的所有文件:
<img src="<%=request.getContextPath() %>/resources/images/image.jpg"/>
或
<link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/style.css" />
我的彈簧servlet.xml文件:
<?xml version="1.0" encoding="windows-1252"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<!-- Use @Component annotations for bean definitions -->
<context:component-scan base-package="form"/>
<!-- Use @Controller annotations for MVC controller definitions -->
<mvc:annotation-driven />
<mvc:resources mapping="/resources/**" location="/resources/" />
<!-- Add JPA support -->
<bean id="emf" class=
"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<bean class=
"org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<!-- Add Transaction support -->
<bean id="myTxManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf"/>
</bean>
<!-- Use @Transaction annotations for managing transactions -->
<tx:annotation-driven transaction-manager="myTxManager" />
<!-- View resolver -->
<bean class=
"org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/"/>
</bean>
</beans>
項目骨架:
src
--main
--webapp
--resources
--css+
--images+
--target
...等
這不包括任何.js或.css文件嗎? – 2014-04-14 16:08:10
如何在JSP中的src/main/resources'中添加鏈接到JS,CSS,圖像? – OO7 2015-03-11 10:44:57
似乎maven頁面不再具有上述結構。 – RuntimeException 2015-10-20 11:39:46