SpringMVC配置正确,依然无法访问静态资源的问题(编译器IDEA)

本文详述了在IDEA环境下配置SpringMVC项目时,静态资源如css、js等无法正常访问的问题及解决办法。指出问题可能源于Maven生成的target文件未完全更新,并提供通过执行Maven的clean命令来解决该问题的有效方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringMVC配置正确,依然无法访问静态资源的问题(编译器IDEA)

IDEA项目结构

在这里插入图片描述
静态资源css、fonts、js、images、html文件夹等放在webapp目录下,没毛病。

项目web配置文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <servlet>
        <servlet-name>applicationContext</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--自定义配置文件路径-->
        <init-param>
            <!--contextConfigLocation是表示路径的属性-->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>applicationContext</servlet-name>
        <!--
            使用框架的时候, url-pattern可以使用两种值
            1. 使用扩展名方式
            2.使用斜杠 "/",会导致项目静态资源无法访问404
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

定义了SpringMVC中央调度器,使用了斜杠“/”的方式定义前后端交互的访问地址,没毛病。

Spring配置文件applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <mvc:resources mapping="/js/**" location="/js/"/>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/fonts/**" location="/fonts/"/>
    <mvc:resources mapping="/static/**" location="/static/"/>
    <mvc:resources mapping="/images/**" location="/images/"/>
    <mvc:annotation-driven/>
</beans>

应用了mvc:resources标签声明静态资源,并且应用了MVC注解驱动mvc:annotation-driven解决了mvc:resources标签与@RequestMapping注解的冲突问题,没毛病。

可启动tomcat,依然找不到静态资源

在这里插入图片描述

经过苦苦尝试,终于找到解决方案,问题不是出自代码,而是出自Maven生成的target文件夹没有完全更新。

解决方案如下

1点击进入对应工程项目的Maven生命周期栏,点击clean,清空target文件夹

在这里插入图片描述

2重启tomcat服务,问题便得以解决
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值