You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC集成Tiles后添加<mvc:resources>致控制器请求无法映射

解决Spring MVC添加<mvc:resources>后控制器请求无法到达的问题

我之前在做Spring MVC集成Tiles的项目时,完全碰到过和你一模一样的坑!加了静态资源配置后图片能正常加载了,但所有控制器请求都返回404,调试时发现RequestMappingHandlerMapping里根本没注册我的控制器方法,后来才搞明白原因:

当你在dispatcher-servlet.xml中添加<mvc:resources>标签时,Spring MVC会自动关闭默认的注解驱动处理器映射的自动注册,这就导致你的@RequestMapping注解的控制器方法无法被识别和映射。

解决方案很简单,只需两步:

  • 第一步:在配置文件中添加<mvc:annotation-driven />标签,这个标签会重新启用Spring MVC的注解驱动功能,让RequestMappingHandlerMapping能正常扫描并注册你的控制器映射。
  • 第二步:确保你已经配置了组件扫描,让Spring能找到你的控制器类(也就是<context:component-scan base-package="你的控制器所在包路径" />)。

给你一个完整的dispatcher-servlet.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"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 启用注解驱动,恢复RequestMappingHandlerMapping的自动注册 -->
    <mvc:annotation-driven />

    <!-- 静态资源映射配置 -->
    <mvc:resources mapping="/resources/**" location="/resources/" />

    <!-- 扫描控制器所在包,确保@Controller注解的类被Spring识别 -->
    <context:component-scan base-package="com.yourproject.controller" />

    <!-- Tiles配置部分 -->
    <bean id="tilesConfigurer" class="org.springframework.web.servlet.view.tiles3.TilesConfigurer">
        <property name="definitions">
            <list>
                <value>/WEB-INF/tiles.xml</value>
            </list>
        </property>
    </bean>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.tiles3.TilesViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.tiles3.TilesView" />
    </bean>
</beans>

额外检查点:

  • 确认你的控制器类上标注了@Controller注解,方法上的@RequestMapping路径没有拼写错误;
  • 组件扫描的包路径要准确,别把控制器所在的包漏掉了;
  • 如果用的是Tiles 2,记得把配置里的tiles3改成tiles2,对应类路径也要调整。

这样调整后,静态资源能正常加载,控制器请求也能正确映射到对应的方法了!

内容的提问来源于stack exchange,提问作者Mayank Vaid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:40:12