首先创建一个Maven web项目,详情请参考:https://blog.csdn.net/weixin_42067873/article/details/114265889
1、引入springmvc jar包
进入 mvnrespository.com 网站搜索对应的jar包
(1)将依赖项加入到 pom.xml文件中
maven自动加载jar包及其依赖项(依赖传递原则)
2、配置servlet(DispatcherServlet)
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置在服务器启动时加载配置文件 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
(1)springmvc配置文件的命名方式
<servlet-name>springmvc</servlet-name>
该标签中为DispatcherServlet起的名字是什么,对应的配置文件就命名为:name-servlet.xml
(2)自定义springmvc配置文件命名
对namespace变量设置值:WebApplicationContext的命名空间。默认是[servlet-name]-servlet
<init-param>
<param-name>namespace</param-name>
<param-value>mySpringMVCName</param-value>
</init-param>
3、配置springmvc-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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
">
<!-- 开启直接驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 配置扫包-->
<context:component-scan base-package="com.hanmh.controller"></context:component-scan>
<!-- 配置资源文件 不会被核心拦截器拦截-->
<mvc:resources mapping="/resource/**" location="/resource/"></mvc:resources>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/webPages"></property>
<property name="suffix" value=".jsp"></property>
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
</bean>
</beans>
4、配置资源文件
首先需要明确的是:资源文件不能放在 /WEB-INF目录下。所以在webapp目录下,建立资源文件目录 resource
注:配置完裕兴不能直接生效,原因在于:生成目录target中没有同步过来resource中的资源,所以需要先删除target目录,再次运行进行资源同步
配置防止资源文件拦截:(springmvc-servlet.xml)
<!-- 配置资源文件 不会被核心拦截器拦截-->
<mvc:resources mapping="/resource/**" location="/resource/"></mvc:resources>
<!-- 配置扫描的包 -->
<context:component-scan base-package="com.hanmh.controller"></context:component-scan>