背景:和同事协同开发,他用eclipse提交代码后我拉取完用idea启动就报错,之前代码是一点问题没有的,而且配置文件也基本没改,但就是启动错误:
No mapping found for HTTP request with URI [/main/index.do] in DispatcherServlet with name ‘dispatcher’…
框架使用的是Spring+SpringMVC
曾经也出现过这个问题,然后我用eclipse启动就行,用idea启动就报错,不过曾经时间紧就屈服用eclipse了,这次时间充裕,专门花了好久找到了解决办法,代码如下:
web.xml中的相关配置:
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:META-INF/spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
其次再次确定你的resources文件夹设置的为Resources Root,不知为何项目启动一次我的Resources文件夹不是Resources Root而是Resources下的一个文件夹变成了Resources Root!!!
然后启动项目如下图:因为dispatcher的全名涉及到公司,因此给遮住了,不过web.xml中的名字对应这下面的名字;见谅
可以看到访问controller时发生了错误,在浏览器看错误代码是404,说白了就是跳转路径错误,可是可以肯定的是路径绝对没写错,但还是报404;
博主的问题是没有加载进配置文件,从而没有加载controller,当然还有一些人可能真的是路径写错了,自己面壁反思!
解决思路,把你的项目打的war包,看相关的配置文件是否也打包进去了,若没有打包进去,问题就出来了
解决办法:
pom.xml:
<build>
<resources>
<resource>
<!--配置文件的路径-->
<directory>src/main/resource/META-INF</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>
问题解决,皆大欢喜;可能每个人遇到的问题都不一样,这里只提供一种解决思路
后续补充:
后来发现,真正的原因是项目的pom;我的项目是dao、service、controller分开的,下面放个图,因涉及到公司名字,这里只截图部分:
但最外层的pom指定了配置文件的路径如下:
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<excludes>
<exclude>**</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources${env}</directory>
<filtering>true</filtering>
</resource>
</resources>
</build>
但controller项目下的resources文件夹下又有三套配置文件(分别对应不同环境),虽然pom中设置了默认启动开发环境,但idea应该是未识别到"/",如下,所以报了404错误,
<profile>
<id>local</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<properties>
<env>/</env>
</properties>
</profile>
<profile>
<id>test</id>
<properties>
<env>/test</env>
</properties>
</profile>
<profile>
<id>pro</id>
<properties>
<env>/product</env>
</properties>
</profile>
<profile>
<id>idc</id>
<properties>
<env>/idc</env>
</properties>
</profile>
两种解决方案:
1.把上面pom中的注掉
<resources>
<excludes>... </excludes>
</resources>
手动指定配置文件路径
<resource>
<!--配置文件的路径-->
<directory>src/main/resource/META-INF</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
</resource>
2.通过maven指定启动环境(推荐这一种),图如下