SpringMVC如何正确配置静态资源(css,js,images)?

WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_5.xsd"
    version="2.5">
    <!--configure the setting of springmvcDispatcherServlet and configure the mapping-->
  <servlet>
      <servlet-name>qiye</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/qiye-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
  </servlet>
 
  <servlet-mapping>
      <servlet-name>qiye</servlet-name>
      <url-pattern>/</url-pattern>
  </servlet-mapping>
  
  
</web-app>

qiye-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
   xsi:schemaLocation="
   http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
   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">
    <context:component-scan base-package="qiye.web" />
     <!-- 静态资源访问 -->
    <mvc:default-servlet-handler/>
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

我加上了<mvc:default-servlet-handler/>
但是页面报404错误.
如果去掉<mvc:default-servlet-handler/> SpringMVC视图就正常.但是css文件,js文件,图片加载不出来.
http://127.0.0.1:28080/Qiye/j...
我这这样访问的 ,有错吗?
图片描述

home文件夹下都是前端html

阅读 10k
3 个回答

把home文件夹挪到WebContent目录下就可以了。配置上

<mvc:default-servlet-handler/>

静态文件放在webapp目录下,设置过滤器或spring配置静态资源目录

<mvc:default-servlet-handler/>

这个确实很方便,但还是不建议使用,推荐使用静态资源映射标签

<!--静态资源访问(缓存一周) -->
<mvc:resources location="/images/" mapping="/images/**" cache-period="604800"/>
<mvc:resources location="/js/" mapping="/js/**" cache-period="604800"/>
<mvc:resources location="/css/" mapping="/css/**" cache-period="604800"/>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题