spring-mvc.xml配置mvc:resources标签后,web项目访问controller404

本文介绍在SSM框架中配置静态资源后导致Controller出现404错误的问题及解决方案,并提供两种配置方法。

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

ssm框架,在spring-mvc.xml文件中配置了访问静态资源的标签后(如下),web项目本来可以访问的controller,现在报404。

<mvc:resources location="/resources/css/" mapping="/resources/css/**" />  
<mvc:resources location="/resources/img/" mapping="/resources/img/**" />  
<mvc:resources location="/resources/js/" mapping="/resources/js/**" />
<mvc:resources location="/resources/lang/" mapping="/resources/lang/**" />
<mvc:resources location="/resources/umeditor/" mapping="/resources/umeditor/**" />

解决办法:

在spring-mvc.xml配置文件的开头配置注解驱动就好了

<mvc:annotation-driven/>

延伸:

以上在spring-mvc.xml中访问静态资源的配置相当于在web.xml如下配置,二者择其一即可,如果选择了在web中如下的配置,则在spring-mvc.xml中不配置<mvc:annotation-driven/>也可访问静态资源,controller也可访问,若选择了上边mvc标签配置,则必须同时配置<mvc:annotation-driven/>:

<servlet-mapping>
	<servlet-name>default</servlet-name>
	<url-pattern>*.js</url-pattern>
  </servlet-mapping>
  <servlet-mapping>
	<servlet-name>default</servlet-name>
	<url-pattern>*.css</url-pattern>
  </servlet-mapping><!--图片等静态资源也可照此配置-->


以下是一个基本的spring-mvc.xml配置文件模板: ```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:context="http://www.springframework.org/schema/context" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 配置Spring MVC 的 DispatcherServlet --> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <!-- 配置静态资源的路径 --> <mvc:resources mapping="/static/**" location="/static/"/> <!-- 配置视图解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 配置扫描Controller--> <context:component-scan base-package="com.example.controller"/> </beans> ``` 其中: - `<mvc:annotation-driven/>` 表示启用Spring MVC的注解驱动,可以使用 `@Controller`、`@RequestMapping`等注解。 - `<mvc:default-servlet-handler/>` 表示将静态资源的请求交给Servlet容器处理。 - `<mvc:resources>` 用于配置静态资源的路径,mapping属性表示访问路径,location属性表示资源文件所在路径。 - `<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">` 表示配置JSP视图解析器,prefix属性表示JSP文件所在路径的前缀,suffix属性表示JSP文件的后缀。 - `<context:component-scan base-package="com.example.controller"/>` 表示扫描指定的包,查找带有注解的类,例如 `@Controller`、`@Service`等。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值