为了在spring使用静态资源(html,css,img,js),请使用类似于以下内容的目录结构:
src/
package/
LayoutController.java
WebContent/
WEB-INF/
static/
html/
layout.html
images/
image.jpg
css/
test.css
js/
main.js
web.xml
springmvc-servlet.xml
@Controller
public class LayoutController {
@RequestMapping("/staticPage")
public String getIndexPage() {
return "layout.htm";
} }
<!-- in spring config file -->
<mvc:resources mapping="/static/**" location="/WEB-INF/static/" />
layout.html
<h1>Page with image</h1>
<img src="/static/img/image.jpg"/>
请注意,你必须提及/static/img/image.jpg而不只是/image.jpg ..同样适用于CSS和JS。
要么
你还可以使用内容协商视图解析器,如下所示:
<bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
<property name="order" value="1" />
<property name="mediaTypes">
<map>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
<entry key="RSS" value="application/RSS+xml" />
<entry key="html" value="text/html"/>
</map>
</property>
<property name="defaultViews">
<list>
<!-- JSON View -->
<bean
class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
</bean>
Spring MVC将使用“ ContentNegotiatingViewResolver”(order = 1)返回合适的视图(基于在“ mediaTypes ”属性中声明的文件扩展名),如果不匹配,则使用“ InternalResourceViewResolver”(order = 2)返回默认的JSP页面。
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="order" value="2" />
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
@Controller
public class LayoutController {
@RequestMapping("/index")
public String getIndexPage() {
return "index";
}
}
index.jsp
<form:form method="GET" action="/static/html/layout.html">
现在尝试通过http://yourapp.com/ / index 访问你的服务,显示上述表单操作,它将显示layout.html